forked from aljungberg/LPKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LPViewAnimation.j
393 lines (313 loc) · 13.9 KB
/
LPViewAnimation.j
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
* LPViewAnimation.j
*
* Created by Ludwig Pettersson on April 3, 2010.
*
* The MIT License
*
* Copyright (c) 2010 Ludwig Pettersson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
@import <Foundation/CPObject.j>
LPCSSAnimationsAreAvailable = NO;
var _browserPrefixes = [@"webkit", @"Moz", @"moz", @"o", @"ms"],
_tmpDOMElement = nil;
LPFadeAnimationKey = @"LPFadeAnimation";
LPFrameAnimationKey = @"LPFrameAnimation";
LPOriginAnimationKey = @"LPOriginAnimation";
LPTestCSSFeature = function(/*CPString*/aFeature)
{
if (typeof document === "undefined")
return NO;
if (!_tmpDOMElement)
_tmpDOMElement = document.createElement("div");
var properties = [aFeature];
for (var i = 0; i < _browserPrefixes.length; i++)
properties.push(_browserPrefixes[i] + aFeature);
for (var i = 0; i < properties.length; i++)
{
if (typeof _tmpDOMElement.style[properties[i]] !== "undefined")
return YES;
}
return NO;
}
// Check if we can do CSS Animations
LPCSSAnimationsAreAvailable = LPTestCSSFeature(@"AnimationName");
var appendCSSValueToKey = function(/*DOMElement*/ anElement, /*CPString*/aValue, /*CPString*/aKey, /*BOOL*/ shouldAppend)
{
if (shouldAppend)
anElement.style[aKey] = anElement.style[aKey] + @", " + aValue;
else
anElement.style[aKey] = aValue;
}
@implementation LPViewAnimation : CPAnimation
{
BOOL _isAnimating;
CPArray _viewAnimations @accessors(property=viewAnimations);
id _animationDidEndTimeout;
BOOL _shouldUseCSSAnimations @accessors(property=shouldUseCSSAnimations);
}
- (void)initWithViewAnimations:(CPArray)viewAnimations
{
if (self = [self initWithDuration:1.0 animationCurve:CPAnimationLinear])
{
_isAnimating = NO;
_viewAnimations = viewAnimations;
_shouldUseCSSAnimations = NO;
}
return self;
}
- (void)startAnimation
{
if (LPCSSAnimationsAreAvailable && _shouldUseCSSAnimations)
{
if (_isAnimating)
return;
_isAnimating = YES;
for (var i = 0; i < _viewAnimations.length; i++)
{
var viewAnimation = _viewAnimations[i],
target = viewAnimation[@"target"];
// Prepare target with general animation stuff.
[self target:target setCSSAnimationDuration:_duration];
[self target:target setCSSAnimationCurve:_animationCurve];
for (var x = 0; x < viewAnimation[@"animations"].length; x++)
{
var animation = viewAnimation[@"animations"][x],
kind = animation[0],
start = animation[1],
end = animation[2];
if (kind === LPFadeAnimationKey)
{
[target setAlphaValue:start];
// Prepare target for this specific animation.
[self target:target addCSSAnimationPropertyForKey:kind append:x !== 0];
// Oddly enough, this does not need to be wrapped in a setTimeout.
setTimeout(function(_target, _end){
[_target setAlphaValue:_end];
}, 0, target, end);
}
else if(kind === LPOriginAnimationKey)
{
if (!CGPointEqualToPoint(start, end))
{
[target setFrameOrigin:start];
// Prepare target for this specific animation.
[self target:target addCSSAnimationPropertyForKey:kind append:x !== 0];
// Need to call it later for the animation to work.
setTimeout(function(_target, _start, _end){
var x = _end.x - _start.x,
y = _end.y - _start.y;
_target._DOMElement.style["-webkit-transform"] = "translate(" + x +"px, " + y + "px)";
// Need to match the new position with the actual frame
setTimeout(function(){
// Make sure we got rid of the animation specific css
[self _clearCSS];
// Reset the translate
_target._DOMElement.style["-webkit-transform"] = "translate(0px, 0px)";
// Set the real frame
[_target setFrameOrigin:_end];
}, (1000 * _duration) + 100);
}, 0, target, start, end);
}
}
else if(kind === LPFrameAnimationKey)
{
CPLog.error("LPViewAnimation does not currently support CSS frame animations. This should fall back to the regular javascript animation.")
}
}
}
if (_animationDidEndTimeout)
clearTimeout(_animationDidEndTimeout);
_animationDidEndTimeout = setTimeout(function(animation){
_isAnimating = NO;
// Clear CSS
[animation _clearCSS];
if ([_delegate respondsToSelector:@selector(animationDidEnd:)])
[_delegate animationDidEnd:animation];
// We delay it by 100 extra mseconds to make sure that all css animations have finished,
// it's not always *exactly* 1000 * duration.
}, (1000 * _duration) + 100, self);
}
else
{
// Set the start value for each animation on the target view
for (var i = 0; i < _viewAnimations.length; i++)
{
var viewAnimation = _viewAnimations[i],
target = viewAnimation[@"target"];
for (var x = 0; x < viewAnimation[@"animations"].length; x++)
{
var animation = viewAnimation[@"animations"][x],
kind = animation[0],
start = animation[1],
end = animation[2];
if (kind === LPFadeAnimationKey)
[target setAlphaValue:start];
else if(kind === LPOriginAnimationKey)
[target setFrameOrigin:start];
else if(kind === LPFrameAnimationKey)
[target setFrame:start];
}
}
[super startAnimation];
}
}
/*
This is used when CSS animations are not available,
or have been turned off.
*/
- (void)setCurrentProgress:(float)aProgress
{
_progress = aProgress;
var value = [self currentValue],
length = _viewAnimations.length;
for (var i = 0; i < length; i++)
{
var viewAnimation = _viewAnimations[i],
target = viewAnimation["target"];
for (var x = 0; x < viewAnimation["animations"].length; x++)
{
var animation = viewAnimation["animations"][x],
kind = animation[0],
start = animation[1],
end = animation[2];
if (kind === LPFadeAnimationKey)
{
[target setAlphaValue:(value * (end - start)) + start];
}
else if(kind === LPOriginAnimationKey)
{
[target setFrameOrigin:CGPointMake(start.x + (value * (end.x - start.x)),
start.y + (value * (end.y - start.y)))];
}
else if(kind === LPFrameAnimationKey)
{
[target setFrame:CGRectMake(start.origin.x + (value * (end.origin.x - start.origin.x)),
start.origin.y + (value * (end.origin.y - start.origin.y)),
start.size.width + (value * (end.size.width - start.size.width)),
start.size.height + (value * (end.size.height - start.size.height)))];
}
}
}
}
- (float)currentValue
{
var c1 = [],
c2 = [];
[_timingFunction getControlPointAtIndex:1 values:c1];
[_timingFunction getControlPointAtIndex:2 values:c2];
return CubicBezierAtTime(_progress, c1[0], c1[1], c2[0], c2[1], _duration);
}
- (BOOL)isAnimating
{
if (LPCSSAnimationsAreAvailable && _shouldUseCSSAnimations)
return _isAnimating;
else
return [super isAnimating];
}
- (void)stopAnimation
{
if (LPCSSAnimationsAreAvailable && _shouldUseCSSAnimations)
{
//_isAnimating = NO;
//if (_animationDidEndTimeout)
// window.clearTimeout(_animationDidEndTimeout);
//[self _stopCSSAnimation];
//if ([_delegate respondsToSelector:@selector(animationDidStop:)])
// [_delegate animationDidStop:self];
}
else
[super stopAnimation];
}
- (void)_clearCSS
{
// Reset the css on each target
for (var i = 0; i < _viewAnimations.length; i++)
_viewAnimations[i][@"target"]._DOMElement.style[@"-webkit-transition-property"] = @"none";
}
- (void)target:(id)aTarget setCSSAnimationDuration:(CPTimeInterval)aDuration
{
aTarget._DOMElement.style["-webkit-transition-duration"] = aDuration + @"s";
}
- (void)target:(id)aTarget setCSSAnimationCurve:(id)anAnimationCurve
{
var curve = nil;
switch (anAnimationCurve)
{
case CPAnimationLinear: curve = @"linear";
break;
case CPAnimationEaseIn: curve = @"ease-in";
break;
case CPAnimationEaseOut: curve = @"ease-out";
break;
case CPAnimationEaseInOut: curve = @"ease-in-out";
break;
}
aTarget._DOMElement.style["-webkit-transition-timing-function"] = curve;
}
- (void)target:(id)aTarget addCSSAnimationPropertyForKey:(CPString)aKey append:(BOOL)shouldAppend
{
var CSSValue = nil;
switch(aKey)
{
case LPFadeAnimationKey: CSSValue = @"opacity";
break;
case LPOriginAnimationKey: CSSValue = @"-webkit-transform";
break;
case LPFrameAnimationKey: CSSValue = @"top, left, width, height";
break;
default: CSSValue = @"none";
}
appendCSSValueToKey(aTarget._DOMElement, CSSValue, @"-webkit-transition-property", shouldAppend);
}
@end
/*
Inlined this, because I managed to crank out a few more fps by doing that. I think.
*/
// currently used function to determine time
// 1:1 conversion to js from webkit source files
// UnitBezier.h, WebCore_animation_AnimationBase.cpp
var CubicBezierAtTime = function CubicBezierAtTime(t,p1x,p1y,p2x,p2y,duration)
{
var ax=0,bx=0,cx=0,ay=0,by=0,cy=0;
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
function sampleCurveX(t) {return ((ax*t+bx)*t+cx)*t;};
function sampleCurveY(t) {return ((ay*t+by)*t+cy)*t;};
function sampleCurveDerivativeX(t) {return (3.0*ax*t+2.0*bx)*t+cx;};
// The epsilon value to pass given that the animation is going to run over |duration| seconds. The longer the animation, the more precision is needed in the timing function result to avoid ugly discontinuities.
function solveEpsilon(duration) {return 1.0/(200.0*duration);};
function solve(x,epsilon) {return sampleCurveY(solveCurveX(x,epsilon));};
// Given an x value, find a parametric value it came from.
function solveCurveX(x,epsilon) {var t0,t1,t2,x2,d2,i;
function fabs(n) {if(n>=0) {return n;}else {return 0-n;}};
// First try a few iterations of Newton's method -- normally very fast.
for(t2=x, i=0; i<8; i++) {x2=sampleCurveX(t2)-x; if(fabs(x2)<epsilon) {return t2;} d2=sampleCurveDerivativeX(t2); if(fabs(d2)<1e-6) {break;} t2=t2-x2/d2;}
// Fall back to the bisection method for reliability.
t0=0.0; t1=1.0; t2=x; if(t2<t0) {return t0;} if(t2>t1) {return t1;}
while(t0<t1) {x2=sampleCurveX(t2); if(fabs(x2-x)<epsilon) {return t2;} if(x>x2) {t0=t2;}else {t1=t2;} t2=(t1-t0)*.5+t0;}
return t2; // Failure.
};
// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
cx=3.0*p1x; bx=3.0*(p2x-p1x)-cx; ax=1.0-cx-bx; cy=3.0*p1y; by=3.0*(p2y-p1y)-cy; ay=1.0-cy-by;
// Convert from input time to parametric value in curve, then from that to output time.
return solve(t, solveEpsilon(duration));
}