1/*
2 * Copyright (C) 2017-2018 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include "KeyframeEffect.h"
28
29#include "Animation.h"
30#include "CSSAnimation.h"
31#include "CSSComputedStyleDeclaration.h"
32#include "CSSKeyframeRule.h"
33#include "CSSPropertyAnimation.h"
34#include "CSSPropertyNames.h"
35#include "CSSStyleDeclaration.h"
36#include "CSSTimingFunctionValue.h"
37#include "CSSTransition.h"
38#include "Element.h"
39#include "FontCascade.h"
40#include "FrameView.h"
41#include "GeometryUtilities.h"
42#include "JSCompositeOperation.h"
43#include "JSCompositeOperationOrAuto.h"
44#include "JSKeyframeEffect.h"
45#include "RenderBox.h"
46#include "RenderBoxModelObject.h"
47#include "RenderElement.h"
48#include "RenderStyle.h"
49#include "StylePendingResources.h"
50#include "StyleResolver.h"
51#include "TimingFunction.h"
52#include "TranslateTransformOperation.h"
53#include "WillChangeData.h"
54#include <JavaScriptCore/Exception.h>
55#include <wtf/UUID.h>
56
57namespace WebCore {
58using namespace JSC;
59
60static inline void invalidateElement(Element* element)
61{
62 if (element)
63 element->invalidateStyle();
64}
65
66static inline String CSSPropertyIDToIDLAttributeName(CSSPropertyID cssPropertyId)
67{
68 // https://drafts.csswg.org/web-animations-1/#animation-property-name-to-idl-attribute-name
69 // 1. If property follows the <custom-property-name> production, return property.
70 // FIXME: We don't handle custom properties yet.
71
72 // 2. If property refers to the CSS float property, return the string "cssFloat".
73 if (cssPropertyId == CSSPropertyFloat)
74 return "cssFloat";
75
76 // 3. If property refers to the CSS offset property, return the string "cssOffset".
77 // FIXME: we don't support the CSS "offset" property
78
79 // 4. Otherwise, return the result of applying the CSS property to IDL attribute algorithm [CSSOM] to property.
80 return getJSPropertyName(cssPropertyId);
81}
82
83static inline CSSPropertyID IDLAttributeNameToAnimationPropertyName(const String& idlAttributeName)
84{
85 // https://drafts.csswg.org/web-animations-1/#idl-attribute-name-to-animation-property-name
86 // 1. If attribute conforms to the <custom-property-name> production, return attribute.
87 // FIXME: We don't handle custom properties yet.
88
89 // 2. If attribute is the string "cssFloat", then return an animation property representing the CSS float property.
90 if (idlAttributeName == "cssFloat")
91 return CSSPropertyFloat;
92
93 // 3. If attribute is the string "cssOffset", then return an animation property representing the CSS offset property.
94 // FIXME: We don't support the CSS "offset" property.
95
96 // 4. Otherwise, return the result of applying the IDL attribute to CSS property algorithm [CSSOM] to attribute.
97 auto cssPropertyId = CSSStyleDeclaration::getCSSPropertyIDFromJavaScriptPropertyName(idlAttributeName);
98
99 // We need to check that converting the property back to IDL form yields the same result such that a property passed
100 // in non-IDL form is rejected, for instance "font-size".
101 if (idlAttributeName != CSSPropertyIDToIDLAttributeName(cssPropertyId))
102 return CSSPropertyInvalid;
103
104 return cssPropertyId;
105}
106
107static inline void computeMissingKeyframeOffsets(Vector<KeyframeEffect::ParsedKeyframe>& keyframes)
108{
109 // https://drafts.csswg.org/web-animations-1/#compute-missing-keyframe-offsets
110
111 if (keyframes.isEmpty())
112 return;
113
114 // 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe offset value.
115 // In our implementation, we only set non-null values to avoid making computedOffset Optional<double>. Instead, we'll know
116 // that a keyframe hasn't had a computed offset by checking if it has a null offset and a 0 computedOffset, since the first
117 // keyframe will already have a 0 computedOffset.
118 for (auto& keyframe : keyframes) {
119 auto computedOffset = keyframe.offset;
120 keyframe.computedOffset = computedOffset ? *computedOffset : 0;
121 }
122
123 // 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in keyframes is null,
124 // set the computed keyframe offset of the first keyframe to 0.
125 if (keyframes.size() > 1 && !keyframes[0].offset)
126 keyframes[0].computedOffset = 0;
127
128 // 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset to 1.
129 if (!keyframes.last().offset)
130 keyframes.last().computedOffset = 1;
131
132 // 4. For each pair of keyframes A and B where:
133 // - A appears before B in keyframes, and
134 // - A and B have a computed keyframe offset that is not null, and
135 // - all keyframes between A and B have a null computed keyframe offset,
136 // calculate the computed keyframe offset of each keyframe between A and B as follows:
137 // 1. Let offsetk be the computed keyframe offset of a keyframe k.
138 // 2. Let n be the number of keyframes between and including A and B minus 1.
139 // 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the first keyframe after A has an index of 1.
140 // 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.
141 size_t indexOfLastKeyframeWithNonNullOffset = 0;
142 for (size_t i = 1; i < keyframes.size(); ++i) {
143 auto& keyframe = keyframes[i];
144 // Keyframes with a null offset that don't yet have a non-zero computed offset are keyframes
145 // with an offset that needs to be computed.
146 if (!keyframe.offset && !keyframe.computedOffset)
147 continue;
148 if (indexOfLastKeyframeWithNonNullOffset != i - 1) {
149 double lastNonNullOffset = keyframes[indexOfLastKeyframeWithNonNullOffset].computedOffset;
150 double offsetDelta = keyframe.computedOffset - lastNonNullOffset;
151 double offsetIncrement = offsetDelta / (i - indexOfLastKeyframeWithNonNullOffset);
152 size_t indexOfFirstKeyframeWithNullOffset = indexOfLastKeyframeWithNonNullOffset + 1;
153 for (size_t j = indexOfFirstKeyframeWithNullOffset; j < i; ++j)
154 keyframes[j].computedOffset = lastNonNullOffset + (j - indexOfLastKeyframeWithNonNullOffset) * offsetIncrement;
155 }
156 indexOfLastKeyframeWithNonNullOffset = i;
157 }
158}
159
160static inline ExceptionOr<KeyframeEffect::KeyframeLikeObject> processKeyframeLikeObject(ExecState& state, Strong<JSObject>&& keyframesInput, bool allowLists)
161{
162 // https://drafts.csswg.org/web-animations-1/#process-a-keyframe-like-object
163
164 VM& vm = state.vm();
165 auto scope = DECLARE_THROW_SCOPE(vm);
166
167 // 1. Run the procedure to convert an ECMAScript value to a dictionary type [WEBIDL] with keyframe input as the ECMAScript value as follows:
168 //
169 // If allow lists is true, use the following dictionary type:
170 //
171 // dictionary BasePropertyIndexedKeyframe {
172 // (double? or sequence<double?>) offset = [];
173 // (DOMString or sequence<DOMString>) easing = [];
174 // (CompositeOperationOrAuto or sequence<CompositeOperationOrAuto>) composite = [];
175 // };
176 //
177 // Otherwise, use the following dictionary type:
178 //
179 // dictionary BaseKeyframe {
180 // double? offset = null;
181 // DOMString easing = "linear";
182 // CompositeOperationOrAuto composite = "auto";
183 // };
184 //
185 // Store the result of this procedure as keyframe output.
186 KeyframeEffect::BasePropertyIndexedKeyframe baseProperties;
187 if (allowLists)
188 baseProperties = convert<IDLDictionary<KeyframeEffect::BasePropertyIndexedKeyframe>>(state, keyframesInput.get());
189 else {
190 auto baseKeyframe = convert<IDLDictionary<KeyframeEffect::BaseKeyframe>>(state, keyframesInput.get());
191 if (baseKeyframe.offset)
192 baseProperties.offset = baseKeyframe.offset.value();
193 else
194 baseProperties.offset = nullptr;
195 baseProperties.easing = baseKeyframe.easing;
196 baseProperties.composite = baseKeyframe.composite;
197 }
198 RETURN_IF_EXCEPTION(scope, Exception { TypeError });
199
200 KeyframeEffect::KeyframeLikeObject keyframeOuput;
201 keyframeOuput.baseProperties = baseProperties;
202
203 // 2. Build up a list of animatable properties as follows:
204 //
205 // 1. Let animatable properties be a list of property names (including shorthand properties that have longhand sub-properties
206 // that are animatable) that can be animated by the implementation.
207 // 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the animation property
208 // name to IDL attribute name algorithm.
209
210 // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the object.
211 PropertyNameArray inputProperties(&vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude);
212 JSObject::getOwnPropertyNames(keyframesInput.get(), &state, inputProperties, EnumerationMode());
213
214 // 4. Make up a new list animation properties that consists of all of the properties that are in both input properties and animatable
215 // properties, or which are in input properties and conform to the <custom-property-name> production.
216 Vector<JSC::Identifier> animationProperties;
217 size_t numberOfProperties = inputProperties.size();
218 for (size_t i = 0; i < numberOfProperties; ++i) {
219 if (CSSPropertyAnimation::isPropertyAnimatable(IDLAttributeNameToAnimationPropertyName(inputProperties[i].string())))
220 animationProperties.append(inputProperties[i]);
221 }
222
223 // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name.
224 std::sort(animationProperties.begin(), animationProperties.end(), [](auto& lhs, auto& rhs) {
225 return lhs.string().utf8() < rhs.string().utf8();
226 });
227
228 // 6. For each property name in animation properties,
229 size_t numberOfAnimationProperties = animationProperties.size();
230 for (size_t i = 0; i < numberOfAnimationProperties; ++i) {
231 // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name as the property
232 // key and keyframe input as the receiver.
233 auto rawValue = keyframesInput->get(&state, animationProperties[i]);
234
235 // 2. Check the completion record of raw value.
236 RETURN_IF_EXCEPTION(scope, Exception { TypeError });
237
238 // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:
239 Vector<String> propertyValues;
240 if (allowLists) {
241 // If allow lists is true,
242 // Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>)
243 // using the procedures defined for converting an ECMAScript value to an IDL value [WEBIDL].
244 // If property values is a single DOMString, replace property values with a sequence of DOMStrings with the original value of property
245 // Values as the only element.
246 if (rawValue.isString())
247 propertyValues = { rawValue.toWTFString(&state) };
248 else if (rawValue.isObject())
249 propertyValues = convert<IDLSequence<IDLDOMString>>(state, rawValue);
250 } else {
251 // Otherwise,
252 // Let property values be the result of converting raw value to a DOMString using the procedure for converting an ECMAScript value to a DOMString.
253 propertyValues = { convert<IDLDOMString>(state, rawValue) };
254 }
255 RETURN_IF_EXCEPTION(scope, Exception { TypeError });
256
257 // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation property name algorithm to property name.
258 auto cssPropertyID = IDLAttributeNameToAnimationPropertyName(animationProperties[i].string());
259
260 // 5. Add a property to to keyframe output with normalized property name as the property name, and property values as the property value.
261 keyframeOuput.propertiesAndValues.append({ cssPropertyID, propertyValues });
262 }
263
264 // 7. Return keyframe output.
265 return { WTFMove(keyframeOuput) };
266}
267
268static inline ExceptionOr<void> processIterableKeyframes(ExecState& state, Strong<JSObject>&& keyframesInput, JSValue method, Vector<KeyframeEffect::ParsedKeyframe>& parsedKeyframes)
269{
270 // 1. Let iter be GetIterator(object, method).
271 forEachInIterable(state, keyframesInput.get(), method, [&parsedKeyframes](VM& vm, ExecState& state, JSValue nextValue) -> ExceptionOr<void> {
272 // Steps 2 through 6 are already implemented by forEachInIterable().
273 auto scope = DECLARE_THROW_SCOPE(vm);
274 if (!nextValue || !nextValue.isObject()) {
275 throwException(&state, scope, JSC::Exception::create(vm, createTypeError(&state)));
276 return { };
277 }
278
279 // 7. Append to processed keyframes the result of running the procedure to process a keyframe-like object passing nextItem
280 // as the keyframe input and with the allow lists flag set to false.
281 auto processKeyframeLikeObjectResult = processKeyframeLikeObject(state, Strong<JSObject>(vm, nextValue.toObject(&state)), false);
282 if (processKeyframeLikeObjectResult.hasException())
283 return processKeyframeLikeObjectResult.releaseException();
284 auto keyframeLikeObject = processKeyframeLikeObjectResult.returnValue();
285
286 KeyframeEffect::ParsedKeyframe keyframeOutput;
287
288 // When calling processKeyframeLikeObject() with the "allow lists" flag set to false, the only offset
289 // alternatives we should expect are double and nullptr.
290 if (WTF::holds_alternative<double>(keyframeLikeObject.baseProperties.offset))
291 keyframeOutput.offset = WTF::get<double>(keyframeLikeObject.baseProperties.offset);
292 else
293 ASSERT(WTF::holds_alternative<std::nullptr_t>(keyframeLikeObject.baseProperties.offset));
294
295 // When calling processKeyframeLikeObject() with the "allow lists" flag set to false, the only easing
296 // alternative we should expect is String.
297 ASSERT(WTF::holds_alternative<String>(keyframeLikeObject.baseProperties.easing));
298 keyframeOutput.easing = WTF::get<String>(keyframeLikeObject.baseProperties.easing);
299
300 // When calling processKeyframeLikeObject() with the "allow lists" flag set to false, the only composite
301 // alternatives we should expect is CompositeOperationAuto.
302 ASSERT(WTF::holds_alternative<CompositeOperationOrAuto>(keyframeLikeObject.baseProperties.composite));
303 keyframeOutput.composite = WTF::get<CompositeOperationOrAuto>(keyframeLikeObject.baseProperties.composite);
304
305 for (auto& propertyAndValue : keyframeLikeObject.propertiesAndValues) {
306 auto cssPropertyId = propertyAndValue.property;
307 // When calling processKeyframeLikeObject() with the "allow lists" flag set to false,
308 // there should only ever be a single value for a given property.
309 ASSERT(propertyAndValue.values.size() == 1);
310 auto stringValue = propertyAndValue.values[0];
311 if (keyframeOutput.style->setProperty(cssPropertyId, stringValue))
312 keyframeOutput.unparsedStyle.set(cssPropertyId, stringValue);
313 }
314
315 parsedKeyframes.append(WTFMove(keyframeOutput));
316
317 return { };
318 });
319
320 return { };
321}
322
323static inline ExceptionOr<void> processPropertyIndexedKeyframes(ExecState& state, Strong<JSObject>&& keyframesInput, Vector<KeyframeEffect::ParsedKeyframe>& parsedKeyframes, Vector<String>& unusedEasings)
324{
325 // 1. Let property-indexed keyframe be the result of running the procedure to process a keyframe-like object passing object as the keyframe input.
326 auto processKeyframeLikeObjectResult = processKeyframeLikeObject(state, WTFMove(keyframesInput), true);
327 if (processKeyframeLikeObjectResult.hasException())
328 return processKeyframeLikeObjectResult.releaseException();
329 auto propertyIndexedKeyframe = processKeyframeLikeObjectResult.returnValue();
330
331 // 2. For each member, m, in property-indexed keyframe, perform the following steps:
332 for (auto& m : propertyIndexedKeyframe.propertiesAndValues) {
333 // 1. Let property name be the key for m.
334 auto propertyName = m.property;
335 // 2. If property name is “composite”, or “easing”, or “offset”, skip the remaining steps in this loop and continue from the next member in property-indexed
336 // keyframe after m.
337 // We skip this test since we split those properties and the actual CSS properties that we're currently iterating over.
338 // 3. Let property values be the value for m.
339 auto propertyValues = m.values;
340 // 4. Let property keyframes be an empty sequence of keyframes.
341 Vector<KeyframeEffect::ParsedKeyframe> propertyKeyframes;
342 // 5. For each value, v, in property values perform the following steps:
343 for (auto& v : propertyValues) {
344 // 1. Let k be a new keyframe with a null keyframe offset.
345 KeyframeEffect::ParsedKeyframe k;
346 // 2. Add the property-value pair, property name → v, to k.
347 if (k.style->setProperty(propertyName, v))
348 k.unparsedStyle.set(propertyName, v);
349 // 3. Append k to property keyframes.
350 propertyKeyframes.append(WTFMove(k));
351 }
352 // 6. Apply the procedure to compute missing keyframe offsets to property keyframes.
353 computeMissingKeyframeOffsets(propertyKeyframes);
354
355 // 7. Add keyframes in property keyframes to processed keyframes.
356 for (auto& keyframe : propertyKeyframes)
357 parsedKeyframes.append(WTFMove(keyframe));
358 }
359
360 // 3. Sort processed keyframes by the computed keyframe offset of each keyframe in increasing order.
361 std::sort(parsedKeyframes.begin(), parsedKeyframes.end(), [](auto& lhs, auto& rhs) {
362 return lhs.computedOffset < rhs.computedOffset;
363 });
364
365 // 4. Merge adjacent keyframes in processed keyframes when they have equal computed keyframe offsets.
366 size_t i = 1;
367 while (i < parsedKeyframes.size()) {
368 auto& keyframe = parsedKeyframes[i];
369 auto& previousKeyframe = parsedKeyframes[i - 1];
370 // If the offsets of this keyframe and the previous keyframe are different,
371 // this means that the two keyframes should not be merged and we can move
372 // on to the next keyframe.
373 if (keyframe.computedOffset != previousKeyframe.computedOffset) {
374 i++;
375 continue;
376 }
377 // Otherwise, both this keyframe and the previous keyframe should be merged.
378 // Unprocessed keyframes in parsedKeyframes at this stage have at most a single
379 // property in cssPropertiesAndValues, so just set this on the previous keyframe.
380 // In case an invalid or null value was originally provided, then the property
381 // was not set and the property count is 0, in which case there is nothing to merge.
382 if (keyframe.style->propertyCount()) {
383 auto property = keyframe.style->propertyAt(0);
384 previousKeyframe.style->setProperty(property.id(), property.value());
385 previousKeyframe.unparsedStyle.set(property.id(), keyframe.unparsedStyle.get(property.id()));
386 }
387 // Since we've processed this keyframe, we can remove it and keep i the same
388 // so that we process the next keyframe in the next loop iteration.
389 parsedKeyframes.remove(i);
390 }
391
392 // 5. Let offsets be a sequence of nullable double values assigned based on the type of the “offset” member of the property-indexed keyframe as follows:
393 // - sequence<double?>, the value of “offset” as-is.
394 // - double?, a sequence of length one with the value of “offset” as its single item, i.e. « offset »,
395 Vector<Optional<double>> offsets;
396 if (WTF::holds_alternative<Vector<Optional<double>>>(propertyIndexedKeyframe.baseProperties.offset))
397 offsets = WTF::get<Vector<Optional<double>>>(propertyIndexedKeyframe.baseProperties.offset);
398 else if (WTF::holds_alternative<double>(propertyIndexedKeyframe.baseProperties.offset))
399 offsets.append(WTF::get<double>(propertyIndexedKeyframe.baseProperties.offset));
400 else if (WTF::holds_alternative<std::nullptr_t>(propertyIndexedKeyframe.baseProperties.offset))
401 offsets.append(WTF::nullopt);
402
403 // 6. Assign each value in offsets to the keyframe offset of the keyframe with corresponding position in property keyframes until the end of either sequence is reached.
404 for (size_t i = 0; i < offsets.size() && i < parsedKeyframes.size(); ++i)
405 parsedKeyframes[i].offset = offsets[i];
406
407 // 7. Let easings be a sequence of DOMString values assigned based on the type of the “easing” member of the property-indexed keyframe as follows:
408 // - sequence<DOMString>, the value of “easing” as-is.
409 // - DOMString, a sequence of length one with the value of “easing” as its single item, i.e. « easing »,
410 Vector<String> easings;
411 if (WTF::holds_alternative<Vector<String>>(propertyIndexedKeyframe.baseProperties.easing))
412 easings = WTF::get<Vector<String>>(propertyIndexedKeyframe.baseProperties.easing);
413 else if (WTF::holds_alternative<String>(propertyIndexedKeyframe.baseProperties.easing))
414 easings.append(WTF::get<String>(propertyIndexedKeyframe.baseProperties.easing));
415
416 // 8. If easings is an empty sequence, let it be a sequence of length one containing the single value “linear”, i.e. « "linear" ».
417 if (easings.isEmpty())
418 easings.append("linear");
419
420 // 9. If easings has fewer items than property keyframes, repeat the elements in easings successively starting from the beginning of the list until easings has as many
421 // items as property keyframes.
422 if (easings.size() < parsedKeyframes.size()) {
423 size_t initialNumberOfEasings = easings.size();
424 for (i = initialNumberOfEasings; i < parsedKeyframes.size(); ++i)
425 easings.append(easings[i % initialNumberOfEasings]);
426 }
427
428 // 10. If easings has more items than property keyframes, store the excess items as unused easings.
429 while (easings.size() > parsedKeyframes.size())
430 unusedEasings.append(easings.takeLast());
431
432 // 11. Assign each value in easings to a property named “easing” on the keyframe with the corresponding position in property keyframes until the end of property keyframes
433 // is reached.
434 for (size_t i = 0; i < parsedKeyframes.size(); ++i)
435 parsedKeyframes[i].easing = easings[i];
436
437 // 12. If the “composite” member of the property-indexed keyframe is not an empty sequence:
438 Vector<CompositeOperationOrAuto> compositeModes;
439 if (WTF::holds_alternative<Vector<CompositeOperationOrAuto>>(propertyIndexedKeyframe.baseProperties.composite))
440 compositeModes = WTF::get<Vector<CompositeOperationOrAuto>>(propertyIndexedKeyframe.baseProperties.composite);
441 else if (WTF::holds_alternative<CompositeOperationOrAuto>(propertyIndexedKeyframe.baseProperties.composite))
442 compositeModes.append(WTF::get<CompositeOperationOrAuto>(propertyIndexedKeyframe.baseProperties.composite));
443 if (!compositeModes.isEmpty()) {
444 // 1. Let composite modes be a sequence of CompositeOperationOrAuto values assigned from the “composite” member of property-indexed keyframe. If that member is a single
445 // CompositeOperationOrAuto value operation, let composite modes be a sequence of length one, with the value of the “composite” as its single item.
446 // 2. As with easings, if composite modes has fewer items than processed keyframes, repeat the elements in composite modes successively starting from the beginning of
447 // the list until composite modes has as many items as processed keyframes.
448 if (compositeModes.size() < parsedKeyframes.size()) {
449 size_t initialNumberOfCompositeModes = compositeModes.size();
450 for (i = initialNumberOfCompositeModes; i < parsedKeyframes.size(); ++i)
451 compositeModes.append(compositeModes[i % initialNumberOfCompositeModes]);
452 }
453 // 3. Assign each value in composite modes that is not auto to the keyframe-specific composite operation on the keyframe with the corresponding position in processed
454 // keyframes until the end of processed keyframes is reached.
455 for (size_t i = 0; i < compositeModes.size() && i < parsedKeyframes.size(); ++i) {
456 if (compositeModes[i] != CompositeOperationOrAuto::Auto)
457 parsedKeyframes[i].composite = compositeModes[i];
458 }
459 }
460
461 return { };
462}
463
464ExceptionOr<Ref<KeyframeEffect>> KeyframeEffect::create(ExecState& state, Element* target, Strong<JSObject>&& keyframes, Optional<Variant<double, KeyframeEffectOptions>>&& options)
465{
466 auto keyframeEffect = adoptRef(*new KeyframeEffect(target));
467
468 if (options) {
469 OptionalEffectTiming timing;
470 auto optionsValue = options.value();
471 if (WTF::holds_alternative<double>(optionsValue)) {
472 Variant<double, String> duration = WTF::get<double>(optionsValue);
473 timing.duration = duration;
474 } else {
475 auto keyframeEffectOptions = WTF::get<KeyframeEffectOptions>(optionsValue);
476 timing = {
477 keyframeEffectOptions.duration,
478 keyframeEffectOptions.iterations,
479 keyframeEffectOptions.delay,
480 keyframeEffectOptions.endDelay,
481 keyframeEffectOptions.iterationStart,
482 keyframeEffectOptions.easing,
483 keyframeEffectOptions.fill,
484 keyframeEffectOptions.direction
485 };
486 }
487 auto updateTimingResult = keyframeEffect->updateTiming(timing);
488 if (updateTimingResult.hasException())
489 return updateTimingResult.releaseException();
490 }
491
492 auto processKeyframesResult = keyframeEffect->processKeyframes(state, WTFMove(keyframes));
493 if (processKeyframesResult.hasException())
494 return processKeyframesResult.releaseException();
495
496 return keyframeEffect;
497}
498
499ExceptionOr<Ref<KeyframeEffect>> KeyframeEffect::create(JSC::ExecState&, Ref<KeyframeEffect>&& source)
500{
501 auto keyframeEffect = adoptRef(*new KeyframeEffect(nullptr));
502 keyframeEffect->copyPropertiesFromSource(WTFMove(source));
503 return keyframeEffect;
504}
505
506Ref<KeyframeEffect> KeyframeEffect::create(const Element& target)
507{
508 return adoptRef(*new KeyframeEffect(const_cast<Element*>(&target)));
509}
510
511KeyframeEffect::KeyframeEffect(Element* target)
512 : m_target(target)
513{
514}
515
516void KeyframeEffect::copyPropertiesFromSource(Ref<KeyframeEffect>&& source)
517{
518 m_target = source->m_target;
519 m_compositeOperation = source->m_compositeOperation;
520 m_iterationCompositeOperation = source->m_iterationCompositeOperation;
521
522 Vector<ParsedKeyframe> parsedKeyframes;
523 for (auto& sourceParsedKeyframe : source->m_parsedKeyframes) {
524 ParsedKeyframe parsedKeyframe;
525 parsedKeyframe.easing = sourceParsedKeyframe.easing;
526 parsedKeyframe.offset = sourceParsedKeyframe.offset;
527 parsedKeyframe.composite = sourceParsedKeyframe.composite;
528 parsedKeyframe.unparsedStyle = sourceParsedKeyframe.unparsedStyle;
529 parsedKeyframe.computedOffset = sourceParsedKeyframe.computedOffset;
530 parsedKeyframe.timingFunction = sourceParsedKeyframe.timingFunction;
531 parsedKeyframe.style = sourceParsedKeyframe.style->mutableCopy();
532 parsedKeyframes.append(WTFMove(parsedKeyframe));
533 }
534 m_parsedKeyframes = WTFMove(parsedKeyframes);
535
536 setFill(source->fill());
537 setDelay(source->delay());
538 setEndDelay(source->endDelay());
539 setDirection(source->direction());
540 setIterations(source->iterations());
541 setTimingFunction(source->timingFunction());
542 setIterationStart(source->iterationStart());
543 setIterationDuration(source->iterationDuration());
544
545 KeyframeList keyframeList("keyframe-effect-" + createCanonicalUUIDString());
546 for (auto& keyframe : source->m_blendingKeyframes.keyframes()) {
547 KeyframeValue keyframeValue(keyframe.key(), RenderStyle::clonePtr(*keyframe.style()));
548 for (auto propertyId : keyframe.properties())
549 keyframeValue.addProperty(propertyId);
550 keyframeList.insert(WTFMove(keyframeValue));
551 }
552 setBlendingKeyframes(keyframeList);
553}
554
555Vector<Strong<JSObject>> KeyframeEffect::getKeyframes(ExecState& state)
556{
557 // https://drafts.csswg.org/web-animations-1/#dom-keyframeeffectreadonly-getkeyframes
558
559 auto lock = JSLockHolder { &state };
560
561 // Since keyframes are represented by a partially open-ended dictionary type that is not currently able to be expressed with WebIDL,
562 // the procedure used to prepare the result of this method is defined in prose below:
563 //
564 // 1. Let result be an empty sequence of objects.
565 Vector<Strong<JSObject>> result;
566
567 // 2. Let keyframes be the result of applying the procedure to compute missing keyframe offsets to the keyframes for this keyframe effect.
568
569 // 3. For each keyframe in keyframes perform the following steps:
570 if (is<DeclarativeAnimation>(animation())) {
571 auto computedStyleExtractor = ComputedStyleExtractor(m_target.get());
572 for (size_t i = 0; i < m_blendingKeyframes.size(); ++i) {
573 // 1. Initialize a dictionary object, output keyframe, using the following definition:
574 //
575 // dictionary BaseComputedKeyframe {
576 // double? offset = null;
577 // double computedOffset;
578 // DOMString easing = "linear";
579 // CompositeOperationOrAuto composite = "auto";
580 // };
581
582 auto& keyframe = m_blendingKeyframes[i];
583
584 // 2. Set offset, computedOffset, easing members of output keyframe to the respective values keyframe offset, computed keyframe offset,
585 // and keyframe-specific timing function of keyframe.
586 BaseComputedKeyframe computedKeyframe;
587 computedKeyframe.offset = keyframe.key();
588 computedKeyframe.computedOffset = keyframe.key();
589 // For CSS transitions, there are only two keyframes and the second keyframe should always report "linear". In practice, this value
590 // has no bearing since, as the last keyframe, its value will never be used.
591 computedKeyframe.easing = is<CSSTransition>(animation()) && i == 1 ? "linear" : timingFunctionForKeyframeAtIndex(0)->cssText();
592
593 auto outputKeyframe = convertDictionaryToJS(state, *jsCast<JSDOMGlobalObject*>(state.lexicalGlobalObject()), computedKeyframe);
594
595 // 3. For each animation property-value pair specified on keyframe, declaration, perform the following steps:
596 auto& style = *keyframe.style();
597 for (auto cssPropertyId : keyframe.properties()) {
598 if (cssPropertyId == CSSPropertyCustom)
599 continue;
600 // 1. Let property name be the result of applying the animation property name to IDL attribute name algorithm to the property name of declaration.
601 auto propertyName = CSSPropertyIDToIDLAttributeName(cssPropertyId);
602 // 2. Let IDL value be the result of serializing the property value of declaration by passing declaration to the algorithm to serialize a CSS value.
603 String idlValue = "";
604 if (auto cssValue = computedStyleExtractor.valueForPropertyinStyle(style, cssPropertyId))
605 idlValue = cssValue->cssText();
606 // 3. Let value be the result of converting IDL value to an ECMAScript String value.
607 auto value = toJS<IDLDOMString>(state, idlValue);
608 // 4. Call the [[DefineOwnProperty]] internal method on output keyframe with property name property name,
609 // Property Descriptor { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true, [[Value]]: value } and Boolean flag false.
610 JSObject::defineOwnProperty(outputKeyframe, &state, AtomicString(propertyName).impl(), PropertyDescriptor(value, 0), false);
611 }
612
613 // 5. Append output keyframe to result.
614 result.append(JSC::Strong<JSC::JSObject> { state.vm(), outputKeyframe });
615 }
616 } else {
617 for (size_t i = 0; i < m_parsedKeyframes.size(); ++i) {
618 // 1. Initialize a dictionary object, output keyframe, using the following definition:
619 //
620 // dictionary BaseComputedKeyframe {
621 // double? offset = null;
622 // double computedOffset;
623 // DOMString easing = "linear";
624 // CompositeOperationOrAuto composite = "auto";
625 // };
626
627 auto& parsedKeyframe = m_parsedKeyframes[i];
628
629 // 2. Set offset, computedOffset, easing, composite members of output keyframe to the respective values keyframe offset, computed keyframe
630 // offset, keyframe-specific timing function and keyframe-specific composite operation of keyframe.
631 BaseComputedKeyframe computedKeyframe;
632 computedKeyframe.offset = parsedKeyframe.offset;
633 computedKeyframe.computedOffset = parsedKeyframe.computedOffset;
634 computedKeyframe.easing = timingFunctionForKeyframeAtIndex(i)->cssText();
635 computedKeyframe.composite = parsedKeyframe.composite;
636
637 auto outputKeyframe = convertDictionaryToJS(state, *jsCast<JSDOMGlobalObject*>(state.lexicalGlobalObject()), computedKeyframe);
638
639 // 3. For each animation property-value pair specified on keyframe, declaration, perform the following steps:
640 for (auto it = parsedKeyframe.unparsedStyle.begin(), end = parsedKeyframe.unparsedStyle.end(); it != end; ++it) {
641 // 1. Let property name be the result of applying the animation property name to IDL attribute name algorithm to the property name of declaration.
642 auto propertyName = CSSPropertyIDToIDLAttributeName(it->key);
643 // 2. Let IDL value be the result of serializing the property value of declaration by passing declaration to the algorithm to serialize a CSS value.
644 // 3. Let value be the result of converting IDL value to an ECMAScript String value.
645 auto value = toJS<IDLDOMString>(state, it->value);
646 // 4. Call the [[DefineOwnProperty]] internal method on output keyframe with property name property name,
647 // Property Descriptor { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true, [[Value]]: value } and Boolean flag false.
648 JSObject::defineOwnProperty(outputKeyframe, &state, AtomicString(propertyName).impl(), PropertyDescriptor(value, 0), false);
649 }
650
651 // 4. Append output keyframe to result.
652 result.append(JSC::Strong<JSC::JSObject> { state.vm(), outputKeyframe });
653 }
654 }
655
656 // 4. Return result.
657 return result;
658}
659
660ExceptionOr<void> KeyframeEffect::setKeyframes(ExecState& state, Strong<JSObject>&& keyframesInput)
661{
662 return processKeyframes(state, WTFMove(keyframesInput));
663}
664
665ExceptionOr<void> KeyframeEffect::processKeyframes(ExecState& state, Strong<JSObject>&& keyframesInput)
666{
667 // 1. If object is null, return an empty sequence of keyframes.
668 if (!keyframesInput.get())
669 return { };
670
671 VM& vm = state.vm();
672 auto scope = DECLARE_THROW_SCOPE(vm);
673
674 // 2. Let processed keyframes be an empty sequence of keyframes.
675 Vector<ParsedKeyframe> parsedKeyframes;
676
677 // 3. Let method be the result of GetMethod(object, @@iterator).
678 auto method = keyframesInput.get()->get(&state, vm.propertyNames->iteratorSymbol);
679
680 // 4. Check the completion record of method.
681 RETURN_IF_EXCEPTION(scope, Exception { TypeError });
682
683 // 5. Perform the steps corresponding to the first matching condition from below,
684 Vector<String> unusedEasings;
685 if (!method.isUndefined())
686 processIterableKeyframes(state, WTFMove(keyframesInput), WTFMove(method), parsedKeyframes);
687 else
688 processPropertyIndexedKeyframes(state, WTFMove(keyframesInput), parsedKeyframes, unusedEasings);
689
690 // 6. If processed keyframes is not loosely sorted by offset, throw a TypeError and abort these steps.
691 // 7. If there exist any keyframe in processed keyframes whose keyframe offset is non-null and less than
692 // zero or greater than one, throw a TypeError and abort these steps.
693 double lastNonNullOffset = -1;
694 for (auto& keyframe : parsedKeyframes) {
695 if (!keyframe.offset)
696 continue;
697 auto offset = keyframe.offset.value();
698 if (offset < lastNonNullOffset || offset < 0 || offset > 1)
699 return Exception { TypeError };
700 lastNonNullOffset = offset;
701 }
702
703 // We take a slight detour from the spec text and compute the missing keyframe offsets right away
704 // since they can be computed up-front.
705 computeMissingKeyframeOffsets(parsedKeyframes);
706
707 // 8. For each frame in processed keyframes, perform the following steps:
708 for (auto& keyframe : parsedKeyframes) {
709 // Let the timing function of frame be the result of parsing the “easing” property on frame using the CSS syntax
710 // defined for the easing property of the AnimationEffectTiming interface.
711 // If parsing the “easing” property fails, throw a TypeError and abort this procedure.
712 auto timingFunctionResult = TimingFunction::createFromCSSText(keyframe.easing);
713 if (timingFunctionResult.hasException())
714 return timingFunctionResult.releaseException();
715 keyframe.timingFunction = timingFunctionResult.returnValue();
716 }
717
718 // 9. Parse each of the values in unused easings using the CSS syntax defined for easing property of the
719 // AnimationEffectTiming interface, and if any of the values fail to parse, throw a TypeError
720 // and abort this procedure.
721 for (auto& easing : unusedEasings) {
722 auto timingFunctionResult = TimingFunction::createFromCSSText(easing);
723 if (timingFunctionResult.hasException())
724 return timingFunctionResult.releaseException();
725 }
726
727 m_parsedKeyframes = WTFMove(parsedKeyframes);
728
729 m_blendingKeyframes.clear();
730
731 return { };
732}
733
734void KeyframeEffect::updateBlendingKeyframes(RenderStyle& elementStyle)
735{
736 if (!m_blendingKeyframes.isEmpty() || !m_target)
737 return;
738
739 KeyframeList keyframeList("keyframe-effect-" + createCanonicalUUIDString());
740 StyleResolver& styleResolver = m_target->styleResolver();
741
742 for (auto& keyframe : m_parsedKeyframes) {
743 styleResolver.setNewStateWithElement(*m_target);
744 KeyframeValue keyframeValue(keyframe.computedOffset, nullptr);
745
746 auto styleProperties = keyframe.style->immutableCopyIfNeeded();
747 for (unsigned i = 0; i < styleProperties->propertyCount(); ++i)
748 keyframeList.addProperty(styleProperties->propertyAt(i).id());
749
750 auto keyframeRule = StyleRuleKeyframe::create(WTFMove(styleProperties));
751 keyframeValue.setStyle(styleResolver.styleForKeyframe(&elementStyle, keyframeRule.ptr(), keyframeValue));
752 keyframeList.insert(WTFMove(keyframeValue));
753 }
754
755 setBlendingKeyframes(keyframeList);
756}
757
758bool KeyframeEffect::forceLayoutIfNeeded()
759{
760 if (!m_needsForcedLayout || !m_target)
761 return false;
762
763 auto* renderer = m_target->renderer();
764 if (!renderer || !renderer->parent())
765 return false;
766
767 auto* frameView = m_target->document().view();
768 if (!frameView)
769 return false;
770
771 frameView->forceLayout();
772 return true;
773}
774
775void KeyframeEffect::setBlendingKeyframes(KeyframeList& blendingKeyframes)
776{
777 m_blendingKeyframes = WTFMove(blendingKeyframes);
778
779 computedNeedsForcedLayout();
780 computeStackingContextImpact();
781 computeShouldRunAccelerated();
782
783 checkForMatchingTransformFunctionLists();
784 checkForMatchingFilterFunctionLists();
785#if ENABLE(FILTERS_LEVEL_2)
786 checkForMatchingBackdropFilterFunctionLists();
787#endif
788 checkForMatchingColorFilterFunctionLists();
789}
790
791void KeyframeEffect::checkForMatchingTransformFunctionLists()
792{
793 m_transformFunctionListsMatch = false;
794
795 if (m_blendingKeyframes.size() < 2 || !m_blendingKeyframes.containsProperty(CSSPropertyTransform))
796 return;
797
798 // Empty transforms match anything, so find the first non-empty entry as the reference.
799 size_t numKeyframes = m_blendingKeyframes.size();
800 size_t firstNonEmptyTransformKeyframeIndex = numKeyframes;
801
802 for (size_t i = 0; i < numKeyframes; ++i) {
803 const KeyframeValue& currentKeyframe = m_blendingKeyframes[i];
804 if (currentKeyframe.style()->transform().operations().size()) {
805 firstNonEmptyTransformKeyframeIndex = i;
806 break;
807 }
808 }
809
810 if (firstNonEmptyTransformKeyframeIndex == numKeyframes)
811 return;
812
813 const TransformOperations* firstVal = &m_blendingKeyframes[firstNonEmptyTransformKeyframeIndex].style()->transform();
814 for (size_t i = firstNonEmptyTransformKeyframeIndex + 1; i < numKeyframes; ++i) {
815 const KeyframeValue& currentKeyframe = m_blendingKeyframes[i];
816 const TransformOperations* val = &currentKeyframe.style()->transform();
817
818 // An empty transform list matches anything.
819 if (val->operations().isEmpty())
820 continue;
821
822 if (!firstVal->operationsMatch(*val))
823 return;
824 }
825
826 m_transformFunctionListsMatch = true;
827}
828
829bool KeyframeEffect::checkForMatchingFilterFunctionLists(CSSPropertyID propertyID, const std::function<const FilterOperations& (const RenderStyle&)>& filtersGetter) const
830{
831 if (m_blendingKeyframes.size() < 2 || !m_blendingKeyframes.containsProperty(propertyID))
832 return false;
833
834 // Empty filters match anything, so find the first non-empty entry as the reference.
835 size_t numKeyframes = m_blendingKeyframes.size();
836 size_t firstNonEmptyKeyframeIndex = numKeyframes;
837
838 for (size_t i = 0; i < numKeyframes; ++i) {
839 if (filtersGetter(*m_blendingKeyframes[i].style()).operations().size()) {
840 firstNonEmptyKeyframeIndex = i;
841 break;
842 }
843 }
844
845 if (firstNonEmptyKeyframeIndex == numKeyframes)
846 return false;
847
848 auto& firstVal = filtersGetter(*m_blendingKeyframes[firstNonEmptyKeyframeIndex].style());
849 for (size_t i = firstNonEmptyKeyframeIndex + 1; i < numKeyframes; ++i) {
850 auto& value = filtersGetter(*m_blendingKeyframes[i].style());
851
852 // An empty filter list matches anything.
853 if (value.operations().isEmpty())
854 continue;
855
856 if (!firstVal.operationsMatch(value))
857 return false;
858 }
859
860 return true;
861}
862
863void KeyframeEffect::checkForMatchingFilterFunctionLists()
864{
865 m_filterFunctionListsMatch = checkForMatchingFilterFunctionLists(CSSPropertyFilter, [] (const RenderStyle& style) -> const FilterOperations& {
866 return style.filter();
867 });
868}
869
870#if ENABLE(FILTERS_LEVEL_2)
871void KeyframeEffect::checkForMatchingBackdropFilterFunctionLists()
872{
873 m_backdropFilterFunctionListsMatch = checkForMatchingFilterFunctionLists(CSSPropertyWebkitBackdropFilter, [] (const RenderStyle& style) -> const FilterOperations& {
874 return style.backdropFilter();
875 });
876}
877#endif
878
879void KeyframeEffect::checkForMatchingColorFilterFunctionLists()
880{
881 m_colorFilterFunctionListsMatch = checkForMatchingFilterFunctionLists(CSSPropertyAppleColorFilter, [] (const RenderStyle& style) -> const FilterOperations& {
882 return style.appleColorFilter();
883 });
884}
885
886void KeyframeEffect::computeDeclarativeAnimationBlendingKeyframes(const RenderStyle* oldStyle, const RenderStyle& newStyle)
887{
888 ASSERT(is<DeclarativeAnimation>(animation()));
889 if (is<CSSAnimation>(animation()))
890 computeCSSAnimationBlendingKeyframes();
891 else if (is<CSSTransition>(animation()))
892 computeCSSTransitionBlendingKeyframes(oldStyle, newStyle);
893}
894
895void KeyframeEffect::computeCSSAnimationBlendingKeyframes()
896{
897 ASSERT(is<CSSAnimation>(animation()));
898
899 auto cssAnimation = downcast<CSSAnimation>(animation());
900 auto& backingAnimation = cssAnimation->backingAnimation();
901
902 KeyframeList keyframeList(backingAnimation.name());
903 if (auto* styleScope = Style::Scope::forOrdinal(*m_target, backingAnimation.nameStyleScopeOrdinal()))
904 styleScope->resolver().keyframeStylesForAnimation(*m_target, &cssAnimation->unanimatedStyle(), keyframeList);
905
906 // Ensure resource loads for all the frames.
907 for (auto& keyframe : keyframeList.keyframes()) {
908 if (auto* style = const_cast<RenderStyle*>(keyframe.style()))
909 Style::loadPendingResources(*style, m_target->document(), m_target.get());
910 }
911
912 setBlendingKeyframes(keyframeList);
913}
914
915void KeyframeEffect::computeCSSTransitionBlendingKeyframes(const RenderStyle* oldStyle, const RenderStyle& newStyle)
916{
917 ASSERT(is<CSSTransition>(animation()));
918
919 if (!oldStyle || m_blendingKeyframes.size())
920 return;
921
922 auto property = downcast<CSSTransition>(animation())->property();
923
924 auto toStyle = RenderStyle::clonePtr(newStyle);
925 if (m_target)
926 Style::loadPendingResources(*toStyle, m_target->document(), m_target.get());
927
928 KeyframeList keyframeList("keyframe-effect-" + createCanonicalUUIDString());
929 keyframeList.addProperty(property);
930
931 KeyframeValue fromKeyframeValue(0, RenderStyle::clonePtr(*oldStyle));
932 fromKeyframeValue.addProperty(property);
933 keyframeList.insert(WTFMove(fromKeyframeValue));
934
935 KeyframeValue toKeyframeValue(1, WTFMove(toStyle));
936 toKeyframeValue.addProperty(property);
937 keyframeList.insert(WTFMove(toKeyframeValue));
938
939 setBlendingKeyframes(keyframeList);
940}
941
942void KeyframeEffect::computedNeedsForcedLayout()
943{
944 m_needsForcedLayout = false;
945 if (is<CSSTransition>(animation()) || !m_blendingKeyframes.containsProperty(CSSPropertyTransform))
946 return;
947
948 size_t numberOfKeyframes = m_blendingKeyframes.size();
949 for (size_t i = 0; i < numberOfKeyframes; i++) {
950 auto* keyframeStyle = m_blendingKeyframes[i].style();
951 if (!keyframeStyle) {
952 ASSERT_NOT_REACHED();
953 continue;
954 }
955 if (keyframeStyle->hasTransform()) {
956 auto& transformOperations = keyframeStyle->transform();
957 for (const auto& operation : transformOperations.operations()) {
958 if (operation->isTranslateTransformOperationType()) {
959 auto translation = downcast<TranslateTransformOperation>(operation.get());
960 if (translation->x().isPercent() || translation->y().isPercent()) {
961 m_needsForcedLayout = true;
962 return;
963 }
964 }
965 }
966 }
967 }
968}
969
970void KeyframeEffect::computeStackingContextImpact()
971{
972 m_triggersStackingContext = false;
973 for (auto cssPropertyId : m_blendingKeyframes.properties()) {
974 if (WillChangeData::propertyCreatesStackingContext(cssPropertyId)) {
975 m_triggersStackingContext = true;
976 break;
977 }
978 }
979}
980
981void KeyframeEffect::setTarget(RefPtr<Element>&& newTarget)
982{
983 if (m_target == newTarget)
984 return;
985
986 auto previousTarget = std::exchange(m_target, WTFMove(newTarget));
987
988 if (auto* effectAnimation = animation())
989 effectAnimation->effectTargetDidChange(previousTarget.get(), m_target.get());
990
991 m_blendingKeyframes.clear();
992
993 // We need to invalidate the effect now that the target has changed
994 // to ensure the effect's styles are applied to the new target right away.
995 invalidate();
996
997 // Likewise, we need to invalidate styles on the previous target so that
998 // any animated styles are removed immediately.
999 invalidateElement(previousTarget.get());
1000}
1001
1002void KeyframeEffect::apply(RenderStyle& targetStyle)
1003{
1004 if (!m_target)
1005 return;
1006
1007 updateBlendingKeyframes(targetStyle);
1008
1009 updateAcceleratedAnimationState();
1010
1011 auto progress = getComputedTiming().progress;
1012 if (!progress)
1013 return;
1014
1015 setAnimatedPropertiesInStyle(targetStyle, progress.value());
1016
1017 // https://w3c.github.io/web-animations/#side-effects-section
1018 // For every property targeted by at least one animation effect that is current or in effect, the user agent
1019 // must act as if the will-change property ([css-will-change-1]) on the target element includes the property.
1020 if (m_triggersStackingContext && targetStyle.hasAutoZIndex())
1021 targetStyle.setZIndex(0);
1022}
1023
1024void KeyframeEffect::invalidate()
1025{
1026 invalidateElement(m_target.get());
1027}
1028
1029void KeyframeEffect::computeShouldRunAccelerated()
1030{
1031 m_shouldRunAccelerated = hasBlendingKeyframes();
1032 for (auto cssPropertyId : m_blendingKeyframes.properties()) {
1033 if (!CSSPropertyAnimation::animationOfPropertyIsAccelerated(cssPropertyId)) {
1034 m_shouldRunAccelerated = false;
1035 return;
1036 }
1037 }
1038}
1039
1040void KeyframeEffect::getAnimatedStyle(std::unique_ptr<RenderStyle>& animatedStyle)
1041{
1042 if (!m_target || !animation())
1043 return;
1044
1045 auto progress = getComputedTiming().progress;
1046 if (!progress)
1047 return;
1048
1049 if (!animatedStyle)
1050 animatedStyle = RenderStyle::clonePtr(renderer()->style());
1051
1052 setAnimatedPropertiesInStyle(*animatedStyle.get(), progress.value());
1053}
1054
1055void KeyframeEffect::setAnimatedPropertiesInStyle(RenderStyle& targetStyle, double iterationProgress)
1056{
1057 // 4.4.3. The effect value of a keyframe effect
1058 // https://drafts.csswg.org/web-animations-1/#the-effect-value-of-a-keyframe-animation-effect
1059 //
1060 // The effect value of a single property referenced by a keyframe effect as one of its target properties,
1061 // for a given iteration progress, current iteration and underlying value is calculated as follows.
1062
1063 updateBlendingKeyframes(targetStyle);
1064 if (m_blendingKeyframes.isEmpty())
1065 return;
1066
1067 bool isCSSAnimation = is<CSSAnimation>(animation());
1068
1069 for (auto cssPropertyId : m_blendingKeyframes.properties()) {
1070 // 1. If iteration progress is unresolved abort this procedure.
1071 // 2. Let target property be the longhand property for which the effect value is to be calculated.
1072 // 3. If animation type of the target property is not animatable abort this procedure since the effect cannot be applied.
1073 // 4. Define the neutral value for composition as a value which, when combined with an underlying value using the add composite operation,
1074 // produces the underlying value.
1075
1076 // 5. Let property-specific keyframes be the result of getting the set of computed keyframes for this keyframe effect.
1077 // 6. Remove any keyframes from property-specific keyframes that do not have a property value for target property.
1078 unsigned numberOfKeyframesWithZeroOffset = 0;
1079 unsigned numberOfKeyframesWithOneOffset = 0;
1080 Vector<Optional<size_t>> propertySpecificKeyframes;
1081 for (size_t i = 0; i < m_blendingKeyframes.size(); ++i) {
1082 auto& keyframe = m_blendingKeyframes[i];
1083 auto offset = keyframe.key();
1084 if (!keyframe.containsProperty(cssPropertyId)) {
1085 // If we're dealing with a CSS animation, we consider the first and last keyframes to always have the property listed
1086 // since the underlying style was provided and should be captured.
1087 if (!isCSSAnimation || (offset && offset < 1))
1088 continue;
1089 }
1090 if (!offset)
1091 numberOfKeyframesWithZeroOffset++;
1092 if (offset == 1)
1093 numberOfKeyframesWithOneOffset++;
1094 propertySpecificKeyframes.append(i);
1095 }
1096
1097 // 7. If property-specific keyframes is empty, return underlying value.
1098 if (propertySpecificKeyframes.isEmpty())
1099 continue;
1100
1101 // 8. If there is no keyframe in property-specific keyframes with a computed keyframe offset of 0, create a new keyframe with a computed keyframe
1102 // offset of 0, a property value set to the neutral value for composition, and a composite operation of add, and prepend it to the beginning of
1103 // property-specific keyframes.
1104 if (!numberOfKeyframesWithZeroOffset) {
1105 propertySpecificKeyframes.insert(0, WTF::nullopt);
1106 numberOfKeyframesWithZeroOffset = 1;
1107 }
1108
1109 // 9. Similarly, if there is no keyframe in property-specific keyframes with a computed keyframe offset of 1, create a new keyframe with a computed
1110 // keyframe offset of 1, a property value set to the neutral value for composition, and a composite operation of add, and append it to the end of
1111 // property-specific keyframes.
1112 if (!numberOfKeyframesWithOneOffset) {
1113 propertySpecificKeyframes.append(WTF::nullopt);
1114 numberOfKeyframesWithOneOffset = 1;
1115 }
1116
1117 // 10. Let interval endpoints be an empty sequence of keyframes.
1118 Vector<Optional<size_t>> intervalEndpoints;
1119
1120 // 11. Populate interval endpoints by following the steps from the first matching condition from below:
1121 if (iterationProgress < 0 && numberOfKeyframesWithZeroOffset > 1) {
1122 // If iteration progress < 0 and there is more than one keyframe in property-specific keyframes with a computed keyframe offset of 0,
1123 // Add the first keyframe in property-specific keyframes to interval endpoints.
1124 intervalEndpoints.append(propertySpecificKeyframes.first());
1125 } else if (iterationProgress >= 1 && numberOfKeyframesWithOneOffset > 1) {
1126 // If iteration progress ≥ 1 and there is more than one keyframe in property-specific keyframes with a computed keyframe offset of 1,
1127 // Add the last keyframe in property-specific keyframes to interval endpoints.
1128 intervalEndpoints.append(propertySpecificKeyframes.last());
1129 } else {
1130 // Otherwise,
1131 // 1. Append to interval endpoints the last keyframe in property-specific keyframes whose computed keyframe offset is less than or equal
1132 // to iteration progress and less than 1. If there is no such keyframe (because, for example, the iteration progress is negative),
1133 // add the last keyframe whose computed keyframe offset is 0.
1134 // 2. Append to interval endpoints the next keyframe in property-specific keyframes after the one added in the previous step.
1135 size_t indexOfLastKeyframeWithZeroOffset = 0;
1136 int indexOfFirstKeyframeToAddToIntervalEndpoints = -1;
1137 for (size_t i = 0; i < propertySpecificKeyframes.size(); ++i) {
1138 auto keyframeIndex = propertySpecificKeyframes[i];
1139 auto offset = [&] () -> double {
1140 if (!keyframeIndex)
1141 return i ? 1 : 0;
1142 return m_blendingKeyframes[keyframeIndex.value()].key();
1143 }();
1144 if (!offset)
1145 indexOfLastKeyframeWithZeroOffset = i;
1146 if (offset <= iterationProgress && offset < 1)
1147 indexOfFirstKeyframeToAddToIntervalEndpoints = i;
1148 else
1149 break;
1150 }
1151
1152 if (indexOfFirstKeyframeToAddToIntervalEndpoints >= 0) {
1153 intervalEndpoints.append(propertySpecificKeyframes[indexOfFirstKeyframeToAddToIntervalEndpoints]);
1154 intervalEndpoints.append(propertySpecificKeyframes[indexOfFirstKeyframeToAddToIntervalEndpoints + 1]);
1155 } else {
1156 ASSERT(indexOfLastKeyframeWithZeroOffset < propertySpecificKeyframes.size() - 1);
1157 intervalEndpoints.append(propertySpecificKeyframes[indexOfLastKeyframeWithZeroOffset]);
1158 intervalEndpoints.append(propertySpecificKeyframes[indexOfLastKeyframeWithZeroOffset + 1]);
1159 }
1160 }
1161
1162 // 12. For each keyframe in interval endpoints…
1163 // FIXME: we don't support this step yet since we don't deal with any composite operation other than "replace".
1164
1165 // 13. If there is only one keyframe in interval endpoints return the property value of target property on that keyframe.
1166 if (intervalEndpoints.size() == 1) {
1167 auto keyframeIndex = intervalEndpoints[0];
1168 auto keyframeStyle = !keyframeIndex ? &targetStyle : m_blendingKeyframes[keyframeIndex.value()].style();
1169 CSSPropertyAnimation::blendProperties(this, cssPropertyId, &targetStyle, keyframeStyle, keyframeStyle, 0);
1170 continue;
1171 }
1172
1173 // 14. Let start offset be the computed keyframe offset of the first keyframe in interval endpoints.
1174 auto startKeyframeIndex = intervalEndpoints.first();
1175 auto startOffset = !startKeyframeIndex ? 0 : m_blendingKeyframes[startKeyframeIndex.value()].key();
1176
1177 // 15. Let end offset be the computed keyframe offset of last keyframe in interval endpoints.
1178 auto endKeyframeIndex = intervalEndpoints.last();
1179 auto endOffset = !endKeyframeIndex ? 1 : m_blendingKeyframes[endKeyframeIndex.value()].key();
1180
1181 // 16. Let interval distance be the result of evaluating (iteration progress - start offset) / (end offset - start offset).
1182 auto intervalDistance = (iterationProgress - startOffset) / (endOffset - startOffset);
1183
1184 // 17. Let transformed distance be the result of evaluating the timing function associated with the first keyframe in interval endpoints
1185 // passing interval distance as the input progress.
1186 auto transformedDistance = intervalDistance;
1187 if (startKeyframeIndex) {
1188 if (auto duration = iterationDuration()) {
1189 auto rangeDuration = (endOffset - startOffset) * duration.seconds();
1190 if (auto* timingFunction = timingFunctionForKeyframeAtIndex(startKeyframeIndex.value()))
1191 transformedDistance = timingFunction->transformTime(intervalDistance, rangeDuration);
1192 }
1193 }
1194
1195 // 18. Return the result of applying the interpolation procedure defined by the animation type of the target property, to the values of the target
1196 // property specified on the two keyframes in interval endpoints taking the first such value as Vstart and the second as Vend and using transformed
1197 // distance as the interpolation parameter p.
1198 auto startStyle = !startKeyframeIndex ? &targetStyle : m_blendingKeyframes[startKeyframeIndex.value()].style();
1199 auto endStyle = !endKeyframeIndex ? &targetStyle : m_blendingKeyframes[endKeyframeIndex.value()].style();
1200 CSSPropertyAnimation::blendProperties(this, cssPropertyId, &targetStyle, startStyle, endStyle, transformedDistance);
1201 }
1202}
1203
1204TimingFunction* KeyframeEffect::timingFunctionForKeyframeAtIndex(size_t index)
1205{
1206 if (!m_parsedKeyframes.isEmpty())
1207 return m_parsedKeyframes[index].timingFunction.get();
1208
1209 auto effectAnimation = animation();
1210 if (is<DeclarativeAnimation>(effectAnimation)) {
1211 // If we're dealing with a CSS Animation, the timing function is specified either on the keyframe itself.
1212 if (is<CSSAnimation>(effectAnimation)) {
1213 if (auto* timingFunction = m_blendingKeyframes[index].timingFunction())
1214 return timingFunction;
1215 }
1216
1217 // Failing that, or for a CSS Transition, the timing function is inherited from the backing Animation object.
1218 return downcast<DeclarativeAnimation>(effectAnimation)->backingAnimation().timingFunction();
1219 }
1220
1221 return nullptr;
1222}
1223
1224void KeyframeEffect::updateAcceleratedAnimationState()
1225{
1226 if (!m_shouldRunAccelerated)
1227 return;
1228
1229 if (!renderer()) {
1230 if (isRunningAccelerated())
1231 addPendingAcceleratedAction(AcceleratedAction::Stop);
1232 return;
1233 }
1234
1235 auto localTime = animation()->currentTime();
1236
1237 // If we don't have a localTime or localTime < 0, we either don't have a start time or we're before the startTime
1238 // so we shouldn't be running.
1239 if (!localTime || localTime.value() < 0_s) {
1240 if (isRunningAccelerated())
1241 addPendingAcceleratedAction(AcceleratedAction::Stop);
1242 return;
1243 }
1244
1245 auto playState = animation()->playState();
1246 if (playState == WebAnimation::PlayState::Paused) {
1247 if (m_lastRecordedAcceleratedAction != AcceleratedAction::Pause) {
1248 if (m_lastRecordedAcceleratedAction == AcceleratedAction::Stop)
1249 addPendingAcceleratedAction(AcceleratedAction::Play);
1250 addPendingAcceleratedAction(AcceleratedAction::Pause);
1251 }
1252 return;
1253 }
1254
1255 if (playState == WebAnimation::PlayState::Finished) {
1256 if (isRunningAccelerated())
1257 addPendingAcceleratedAction(AcceleratedAction::Stop);
1258 else {
1259 m_lastRecordedAcceleratedAction = AcceleratedAction::Stop;
1260 m_pendingAcceleratedActions.clear();
1261 animation()->acceleratedStateDidChange();
1262 }
1263 return;
1264 }
1265
1266 if (playState == WebAnimation::PlayState::Running && localTime >= 0_s) {
1267 if (m_lastRecordedAcceleratedAction != AcceleratedAction::Play)
1268 addPendingAcceleratedAction(AcceleratedAction::Play);
1269 return;
1270 }
1271}
1272
1273void KeyframeEffect::addPendingAcceleratedAction(AcceleratedAction action)
1274{
1275 if (action == AcceleratedAction::Stop)
1276 m_pendingAcceleratedActions.clear();
1277 m_pendingAcceleratedActions.append(action);
1278 if (action != AcceleratedAction::Seek)
1279 m_lastRecordedAcceleratedAction = action;
1280 animation()->acceleratedStateDidChange();
1281}
1282
1283void KeyframeEffect::animationDidSeek()
1284{
1285 // There is no need to seek if we're not playing an animation already. If seeking
1286 // means we're moving into an active state, we'll pick this up in apply().
1287 if (m_shouldRunAccelerated && isRunningAccelerated())
1288 addPendingAcceleratedAction(AcceleratedAction::Seek);
1289}
1290
1291void KeyframeEffect::animationSuspensionStateDidChange(bool animationIsSuspended)
1292{
1293 if (m_shouldRunAccelerated)
1294 addPendingAcceleratedAction(animationIsSuspended ? AcceleratedAction::Pause : AcceleratedAction::Play);
1295}
1296
1297void KeyframeEffect::applyPendingAcceleratedActions()
1298{
1299 // Once an accelerated animation has been committed, we no longer want to force a layout.
1300 // This should have been performed by a call to forceLayoutIfNeeded() prior to applying
1301 // pending accelerated actions.
1302 m_needsForcedLayout = false;
1303
1304 if (m_pendingAcceleratedActions.isEmpty())
1305 return;
1306
1307 auto* renderer = this->renderer();
1308 if (!renderer || !renderer->isComposited())
1309 return;
1310
1311 auto pendingAcceleratedActions = m_pendingAcceleratedActions;
1312 m_pendingAcceleratedActions.clear();
1313
1314 auto* compositedRenderer = downcast<RenderBoxModelObject>(renderer);
1315
1316 // To simplify the code we use a default of 0s for an unresolved current time since for a Stop action that is acceptable.
1317 auto timeOffset = animation()->currentTime().valueOr(0_s).seconds() - delay().seconds();
1318
1319 for (const auto& action : pendingAcceleratedActions) {
1320 switch (action) {
1321 case AcceleratedAction::Play:
1322 if (!compositedRenderer->startAnimation(timeOffset, backingAnimationForCompositedRenderer(), m_blendingKeyframes)) {
1323 m_shouldRunAccelerated = false;
1324 m_lastRecordedAcceleratedAction = AcceleratedAction::Stop;
1325 animation()->acceleratedStateDidChange();
1326 return;
1327 }
1328 break;
1329 case AcceleratedAction::Pause:
1330 compositedRenderer->animationPaused(timeOffset, m_blendingKeyframes.animationName());
1331 break;
1332 case AcceleratedAction::Seek:
1333 compositedRenderer->animationSeeked(timeOffset, m_blendingKeyframes.animationName());
1334 break;
1335 case AcceleratedAction::Stop:
1336 compositedRenderer->animationFinished(m_blendingKeyframes.animationName());
1337 if (!m_target->document().renderTreeBeingDestroyed())
1338 m_target->invalidateStyleAndLayerComposition();
1339 break;
1340 }
1341 }
1342}
1343
1344Ref<const Animation> KeyframeEffect::backingAnimationForCompositedRenderer() const
1345{
1346 auto effectAnimation = animation();
1347 if (is<DeclarativeAnimation>(effectAnimation))
1348 return downcast<DeclarativeAnimation>(effectAnimation)->backingAnimation();
1349
1350 // FIXME: The iterationStart and endDelay AnimationEffectTiming properties do not have
1351 // corresponding Animation properties.
1352 auto animation = Animation::create();
1353 animation->setDuration(iterationDuration().seconds());
1354 animation->setDelay(delay().seconds());
1355 animation->setIterationCount(iterations());
1356 animation->setTimingFunction(timingFunction()->clone());
1357
1358 switch (fill()) {
1359 case FillMode::None:
1360 case FillMode::Auto:
1361 animation->setFillMode(AnimationFillMode::None);
1362 break;
1363 case FillMode::Backwards:
1364 animation->setFillMode(AnimationFillMode::Backwards);
1365 break;
1366 case FillMode::Forwards:
1367 animation->setFillMode(AnimationFillMode::Forwards);
1368 break;
1369 case FillMode::Both:
1370 animation->setFillMode(AnimationFillMode::Both);
1371 break;
1372 }
1373
1374 switch (direction()) {
1375 case PlaybackDirection::Normal:
1376 animation->setDirection(Animation::AnimationDirectionNormal);
1377 break;
1378 case PlaybackDirection::Alternate:
1379 animation->setDirection(Animation::AnimationDirectionAlternate);
1380 break;
1381 case PlaybackDirection::Reverse:
1382 animation->setDirection(Animation::AnimationDirectionReverse);
1383 break;
1384 case PlaybackDirection::AlternateReverse:
1385 animation->setDirection(Animation::AnimationDirectionAlternateReverse);
1386 break;
1387 }
1388
1389 return animation;
1390}
1391
1392RenderElement* KeyframeEffect::renderer() const
1393{
1394 return m_target ? m_target->renderer() : nullptr;
1395}
1396
1397const RenderStyle& KeyframeEffect::currentStyle() const
1398{
1399 if (auto* renderer = this->renderer())
1400 return renderer->style();
1401 return RenderStyle::defaultStyle();
1402}
1403
1404bool KeyframeEffect::computeExtentOfTransformAnimation(LayoutRect& bounds) const
1405{
1406 ASSERT(m_blendingKeyframes.containsProperty(CSSPropertyTransform));
1407
1408 if (!is<RenderBox>(renderer()))
1409 return true; // Non-boxes don't get transformed;
1410
1411 auto& box = downcast<RenderBox>(*renderer());
1412 auto rendererBox = snapRectToDevicePixels(box.borderBoxRect(), box.document().deviceScaleFactor());
1413
1414 auto cumulativeBounds = bounds;
1415
1416 for (const auto& keyframe : m_blendingKeyframes.keyframes()) {
1417 const auto* keyframeStyle = keyframe.style();
1418
1419 // FIXME: maybe for declarative animations we always say it's true for the first and last keyframe.
1420 if (!keyframe.containsProperty(CSSPropertyTransform)) {
1421 // If the first keyframe is missing transform style, use the current style.
1422 if (!keyframe.key())
1423 keyframeStyle = &box.style();
1424 else
1425 continue;
1426 }
1427
1428 auto keyframeBounds = bounds;
1429
1430 bool canCompute;
1431 if (transformFunctionListsMatch())
1432 canCompute = computeTransformedExtentViaTransformList(rendererBox, *keyframeStyle, keyframeBounds);
1433 else
1434 canCompute = computeTransformedExtentViaMatrix(rendererBox, *keyframeStyle, keyframeBounds);
1435
1436 if (!canCompute)
1437 return false;
1438
1439 cumulativeBounds.unite(keyframeBounds);
1440 }
1441
1442 bounds = cumulativeBounds;
1443 return true;
1444}
1445
1446static bool containsRotation(const Vector<RefPtr<TransformOperation>>& operations)
1447{
1448 for (const auto& operation : operations) {
1449 if (operation->type() == TransformOperation::ROTATE)
1450 return true;
1451 }
1452 return false;
1453}
1454
1455bool KeyframeEffect::computeTransformedExtentViaTransformList(const FloatRect& rendererBox, const RenderStyle& style, LayoutRect& bounds) const
1456{
1457 FloatRect floatBounds = bounds;
1458 FloatPoint transformOrigin;
1459
1460 bool applyTransformOrigin = containsRotation(style.transform().operations()) || style.transform().affectedByTransformOrigin();
1461 if (applyTransformOrigin) {
1462 transformOrigin.setX(rendererBox.x() + floatValueForLength(style.transformOriginX(), rendererBox.width()));
1463 transformOrigin.setY(rendererBox.y() + floatValueForLength(style.transformOriginY(), rendererBox.height()));
1464 // Ignore transformOriginZ because we'll bail if we encounter any 3D transforms.
1465
1466 floatBounds.moveBy(-transformOrigin);
1467 }
1468
1469 for (const auto& operation : style.transform().operations()) {
1470 if (operation->type() == TransformOperation::ROTATE) {
1471 // For now, just treat this as a full rotation. This could take angle into account to reduce inflation.
1472 floatBounds = boundsOfRotatingRect(floatBounds);
1473 } else {
1474 TransformationMatrix transform;
1475 operation->apply(transform, rendererBox.size());
1476 if (!transform.isAffine())
1477 return false;
1478
1479 if (operation->type() == TransformOperation::MATRIX || operation->type() == TransformOperation::MATRIX_3D) {
1480 TransformationMatrix::Decomposed2Type toDecomp;
1481 transform.decompose2(toDecomp);
1482 // Any rotation prevents us from using a simple start/end rect union.
1483 if (toDecomp.angle)
1484 return false;
1485 }
1486
1487 floatBounds = transform.mapRect(floatBounds);
1488 }
1489 }
1490
1491 if (applyTransformOrigin)
1492 floatBounds.moveBy(transformOrigin);
1493
1494 bounds = LayoutRect(floatBounds);
1495 return true;
1496}
1497
1498bool KeyframeEffect::computeTransformedExtentViaMatrix(const FloatRect& rendererBox, const RenderStyle& style, LayoutRect& bounds) const
1499{
1500 TransformationMatrix transform;
1501 style.applyTransform(transform, rendererBox, RenderStyle::IncludeTransformOrigin);
1502 if (!transform.isAffine())
1503 return false;
1504
1505 TransformationMatrix::Decomposed2Type fromDecomp;
1506 transform.decompose2(fromDecomp);
1507 // Any rotation prevents us from using a simple start/end rect union.
1508 if (fromDecomp.angle)
1509 return false;
1510
1511 bounds = LayoutRect(transform.mapRect(bounds));
1512 return true;
1513}
1514
1515} // namespace WebCore
1516