KeyframeEffect.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. /*
  2. * Copyright (c) 2023-2024, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibJS/Runtime/Iterator.h>
  8. #include <LibWeb/Animations/Animation.h>
  9. #include <LibWeb/Animations/KeyframeEffect.h>
  10. #include <LibWeb/Animations/PseudoElementParsing.h>
  11. #include <LibWeb/Bindings/KeyframeEffectPrototype.h>
  12. #include <LibWeb/CSS/Parser/Parser.h>
  13. #include <LibWeb/CSS/StyleComputer.h>
  14. #include <LibWeb/Layout/Node.h>
  15. #include <LibWeb/Painting/Paintable.h>
  16. #include <LibWeb/WebIDL/ExceptionOr.h>
  17. namespace Web::Animations {
  18. JS_DEFINE_ALLOCATOR(KeyframeEffect);
  19. template<typename T>
  20. WebIDL::ExceptionOr<Variant<T, Vector<T>>> convert_value_to_maybe_list(JS::Realm& realm, JS::Value value, Function<WebIDL::ExceptionOr<T>(JS::Value)>& value_converter)
  21. {
  22. auto& vm = realm.vm();
  23. if (TRY(value.is_array(vm))) {
  24. Vector<T> offsets;
  25. auto iterator = TRY(JS::get_iterator(vm, value, JS::IteratorHint::Sync));
  26. auto values = TRY(JS::iterator_to_list(vm, iterator));
  27. for (auto const& element : values) {
  28. if (element.is_undefined()) {
  29. offsets.append({});
  30. } else {
  31. offsets.append(TRY(value_converter(element)));
  32. }
  33. }
  34. return offsets;
  35. }
  36. return TRY(value_converter(value));
  37. }
  38. enum class AllowLists {
  39. Yes,
  40. No,
  41. };
  42. template<AllowLists AL>
  43. using KeyframeType = Conditional<AL == AllowLists::Yes, BasePropertyIndexedKeyframe, BaseKeyframe>;
  44. // https://www.w3.org/TR/web-animations-1/#process-a-keyframe-like-object
  45. template<AllowLists AL>
  46. static WebIDL::ExceptionOr<KeyframeType<AL>> process_a_keyframe_like_object(JS::Realm& realm, JS::Value keyframe_input)
  47. {
  48. auto& vm = realm.vm();
  49. Function<WebIDL::ExceptionOr<Optional<double>>(JS::Value)> to_offset = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Optional<double>> {
  50. if (value.is_undefined())
  51. return Optional<double> {};
  52. auto double_value = TRY(value.to_double(vm));
  53. if (isnan(double_value) || isinf(double_value))
  54. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Invalid offset value: {}", TRY(value.to_string(vm)))) };
  55. return double_value;
  56. };
  57. Function<WebIDL::ExceptionOr<String>(JS::Value)> to_string = [&vm](JS::Value value) -> WebIDL::ExceptionOr<String> {
  58. return TRY(value.to_string(vm));
  59. };
  60. Function<WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto>(JS::Value)> to_composite_operation = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto> {
  61. if (value.is_undefined())
  62. return Bindings::CompositeOperationOrAuto::Auto;
  63. auto string_value = TRY(value.to_string(vm));
  64. if (string_value == "replace")
  65. return Bindings::CompositeOperationOrAuto::Replace;
  66. if (string_value == "add")
  67. return Bindings::CompositeOperationOrAuto::Add;
  68. if (string_value == "accumulate")
  69. return Bindings::CompositeOperationOrAuto::Accumulate;
  70. if (string_value == "auto")
  71. return Bindings::CompositeOperationOrAuto::Auto;
  72. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid composite value"sv };
  73. };
  74. // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript
  75. // value, and the dictionary type depending on the value of the allow lists flag as follows:
  76. //
  77. // -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.
  78. // -> Otherwise, use the following dictionary type: <BaseKeyframe>.
  79. //
  80. // Store the result of this procedure as keyframe output.
  81. KeyframeType<AL> keyframe_output;
  82. if (keyframe_input.is_nullish())
  83. return keyframe_output;
  84. auto& keyframe_object = keyframe_input.as_object();
  85. auto composite = TRY(keyframe_object.get("composite"));
  86. if (composite.is_undefined())
  87. composite = JS::PrimitiveString::create(vm, "auto"_string);
  88. auto easing = TRY(keyframe_object.get("easing"));
  89. if (easing.is_undefined())
  90. easing = JS::PrimitiveString::create(vm, "linear"_string);
  91. auto offset = TRY(keyframe_object.get("offset"));
  92. if constexpr (AL == AllowLists::Yes) {
  93. keyframe_output.composite = TRY(convert_value_to_maybe_list(realm, composite, to_composite_operation));
  94. auto easing_maybe_list = TRY(convert_value_to_maybe_list(realm, easing, to_string));
  95. easing_maybe_list.visit(
  96. [&](String const& value) {
  97. keyframe_output.easing = EasingValue { value };
  98. },
  99. [&](Vector<String> const& values) {
  100. Vector<EasingValue> easing_values;
  101. for (auto& easing_value : values)
  102. easing_values.append(easing_value);
  103. keyframe_output.easing = move(easing_values);
  104. });
  105. keyframe_output.offset = TRY(convert_value_to_maybe_list(realm, offset, to_offset));
  106. } else {
  107. keyframe_output.composite = TRY(to_composite_operation(composite));
  108. keyframe_output.easing = TRY(to_string(easing));
  109. keyframe_output.offset = TRY(to_offset(offset));
  110. }
  111. // 2. Build up a list of animatable properties as follows:
  112. //
  113. // 1. Let animatable properties be a list of property names (including shorthand properties that have longhand
  114. // sub-properties that are animatable) that can be animated by the implementation.
  115. // 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the
  116. // animation property name to IDL attribute name algorithm.
  117. // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the
  118. // object.
  119. // 4. Make up a new list animation properties that consists of all of the properties that are in both input
  120. // properties and animatable properties, or which are in input properties and conform to the
  121. // <custom-property-name> production.
  122. auto input_properties = TRY(keyframe_object.enumerable_own_property_names(JS::Object::PropertyKind::Key));
  123. Vector<String> animation_properties;
  124. Optional<JS::Value> all_value;
  125. for (auto const& input_property : input_properties) {
  126. if (!input_property.is_string())
  127. continue;
  128. auto name = input_property.as_string().utf8_string();
  129. if (name == "all"sv) {
  130. all_value = TRY(keyframe_object.get(JS::PropertyKey { name }));
  131. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  132. auto property = static_cast<CSS::PropertyID>(i);
  133. if (CSS::is_animatable_property(property))
  134. animation_properties.append(String { CSS::string_from_property_id(property) });
  135. }
  136. } else {
  137. // Handle the two special cases
  138. if (name == "cssFloat"sv || name == "cssOffset"sv) {
  139. animation_properties.append(name);
  140. } else if (name == "float"sv || name == "offset"sv) {
  141. // Ignore these property names
  142. } else if (auto property = CSS::property_id_from_camel_case_string(name); property.has_value()) {
  143. if (CSS::is_animatable_property(property.value()))
  144. animation_properties.append(name);
  145. }
  146. }
  147. }
  148. // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name.
  149. quick_sort(animation_properties);
  150. // 6. For each property name in animation properties,
  151. for (auto const& property_name : animation_properties) {
  152. // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name
  153. // as the property key and keyframe input as the receiver.
  154. // 2. Check the completion record of raw value.
  155. JS::PropertyKey key { property_name };
  156. auto raw_value = TRY(keyframe_object.has_property(key)) ? TRY(keyframe_object.get(key)) : *all_value;
  157. using PropertyValuesType = Conditional<AL == AllowLists::Yes, Vector<String>, String>;
  158. PropertyValuesType property_values;
  159. // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:
  160. // -> If allow lists is true,
  161. if constexpr (AL == AllowLists::Yes) {
  162. // Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>)
  163. // using the procedures defined for converting an ECMAScript value to an IDL value [WEBIDL].
  164. auto intermediate_property_values = TRY(convert_value_to_maybe_list(realm, raw_value, to_string));
  165. // If property values is a single DOMString, replace property values with a sequence of DOMStrings with the
  166. // original value of property values as the only element.
  167. if (intermediate_property_values.has<String>())
  168. property_values = Vector { intermediate_property_values.get<String>() };
  169. else
  170. property_values = intermediate_property_values.get<Vector<String>>();
  171. }
  172. // -> Otherwise,
  173. else {
  174. // Let property values be the result of converting raw value to a DOMString using the procedure for
  175. // converting an ECMAScript value to a DOMString [WEBIDL].
  176. property_values = TRY(raw_value.to_string(vm));
  177. }
  178. // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation
  179. // property name algorithm to property name.
  180. // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL
  181. // attribute name) in the steps above.
  182. // 5. Add a property to keyframe output with normalized property name as the property name, and property values
  183. // as the property value.
  184. if constexpr (AL == AllowLists::Yes) {
  185. keyframe_output.properties.set(property_name, property_values);
  186. } else {
  187. keyframe_output.unparsed_properties().set(property_name, property_values);
  188. }
  189. }
  190. return keyframe_output;
  191. }
  192. // https://www.w3.org/TR/web-animations-1/#compute-missing-keyframe-offsets
  193. static void compute_missing_keyframe_offsets(Vector<BaseKeyframe>& keyframes)
  194. {
  195. // 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe
  196. // offset value.
  197. for (auto& keyframe : keyframes)
  198. keyframe.computed_offset = keyframe.offset;
  199. // 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in
  200. // keyframes is null, set the computed keyframe offset of the first keyframe to 0.
  201. if (keyframes.size() > 1 && !keyframes[0].computed_offset.has_value())
  202. keyframes[0].computed_offset = 0.0;
  203. // 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset
  204. // to 1.
  205. if (!keyframes.is_empty() && !keyframes.last().computed_offset.has_value())
  206. keyframes.last().computed_offset = 1.0;
  207. // 4. For each pair of keyframes A and B where:
  208. // - A appears before B in keyframes, and
  209. // - A and B have a computed keyframe offset that is not null, and
  210. // - all keyframes between A and B have a null computed keyframe offset,
  211. auto find_next_index_of_keyframe_with_computed_offset = [&](size_t starting_index) -> Optional<size_t> {
  212. for (size_t index = starting_index; index < keyframes.size(); index++) {
  213. if (keyframes[index].computed_offset.has_value())
  214. return index;
  215. }
  216. return {};
  217. };
  218. auto maybe_index_a = find_next_index_of_keyframe_with_computed_offset(0);
  219. if (!maybe_index_a.has_value())
  220. return;
  221. auto index_a = maybe_index_a.value();
  222. auto maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_a + 1);
  223. while (maybe_index_b.has_value()) {
  224. auto index_b = maybe_index_b.value();
  225. // calculate the computed keyframe offset of each keyframe between A and B as follows:
  226. for (size_t keyframe_index = index_a + 1; keyframe_index < index_b; keyframe_index++) {
  227. // 1. Let offsetk be the computed keyframe offset of a keyframe k.
  228. auto offset_a = keyframes[index_a].computed_offset.value();
  229. auto offset_b = keyframes[index_b].computed_offset.value();
  230. // 2. Let n be the number of keyframes between and including A and B minus 1.
  231. auto n = static_cast<double>(index_b - index_a);
  232. // 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the
  233. // first keyframe after A has an index of 1.
  234. auto index = static_cast<double>(keyframe_index - index_a);
  235. // 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.
  236. keyframes[keyframe_index].computed_offset = (offset_a + (offset_b - offset_a)) * index / n;
  237. }
  238. index_a = index_b;
  239. maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_b + 1);
  240. }
  241. }
  242. // https://www.w3.org/TR/web-animations-1/#loosely-sorted-by-offset
  243. static bool is_loosely_sorted_by_offset(Vector<BaseKeyframe> const& keyframes)
  244. {
  245. // The list of keyframes for a keyframe effect must be loosely sorted by offset which means that for each keyframe
  246. // in the list that has a keyframe offset that is not null, the offset is greater than or equal to the offset of the
  247. // previous keyframe in the list with a keyframe offset that is not null, if any.
  248. Optional<double> last_offset;
  249. for (auto const& keyframe : keyframes) {
  250. if (!keyframe.offset.has_value())
  251. continue;
  252. if (last_offset.has_value() && keyframe.offset.value() < last_offset.value())
  253. return false;
  254. last_offset = keyframe.offset;
  255. }
  256. return true;
  257. }
  258. // https://www.w3.org/TR/web-animations-1/#process-a-keyframes-argument
  259. static WebIDL::ExceptionOr<Vector<BaseKeyframe>> process_a_keyframes_argument(JS::Realm& realm, JS::GCPtr<JS::Object> object)
  260. {
  261. auto& vm = realm.vm();
  262. // 1. If object is null, return an empty sequence of keyframes.
  263. if (!object)
  264. return Vector<BaseKeyframe> {};
  265. // 2. Let processed keyframes be an empty sequence of keyframes.
  266. Vector<BaseKeyframe> processed_keyframes;
  267. Vector<EasingValue> unused_easings;
  268. // 3. Let method be the result of GetMethod(object, @@iterator).
  269. // 4. Check the completion record of method.
  270. auto method = TRY(JS::Value(object).get_method(vm, vm.well_known_symbol_iterator()));
  271. // 5. Perform the steps corresponding to the first matching condition from below,
  272. // -> If method is not undefined,
  273. if (method) {
  274. // 1. Let iter be GetIterator(object, method).
  275. // 2. Check the completion record of iter.
  276. auto iter = TRY(JS::get_iterator_from_method(vm, object, *method));
  277. // 3. Repeat:
  278. while (true) {
  279. // 1. Let next be IteratorStep(iter).
  280. // 2. Check the completion record of next.
  281. auto next = TRY(JS::iterator_step(vm, iter));
  282. // 3. If next is false abort this loop.
  283. if (!next)
  284. break;
  285. // 4. Let nextItem be IteratorValue(next).
  286. // 5. Check the completion record of nextItem.
  287. auto next_item = TRY(JS::iterator_value(vm, *next));
  288. // 6. If Type(nextItem) is not Undefined, Null or Object, then throw a TypeError and abort these steps.
  289. if (!next_item.is_nullish() && !next_item.is_object())
  290. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOrNull, next_item.to_string_without_side_effects());
  291. // 7. Append to processed keyframes the result of running the procedure to process a keyframe-like object
  292. // passing nextItem as the keyframe input and with the allow lists flag set to false.
  293. processed_keyframes.append(TRY(process_a_keyframe_like_object<AllowLists::No>(realm, next_item)));
  294. }
  295. }
  296. // -> Otherwise,
  297. else {
  298. // 1. Let property-indexed keyframe be the result of running the procedure to process a keyframe-like object
  299. // passing object as the keyframe input and with the allow lists flag set to true.
  300. auto property_indexed_keyframe = TRY(process_a_keyframe_like_object<AllowLists::Yes>(realm, object));
  301. // 2. For each member, m, in property-indexed keyframe, perform the following steps:
  302. for (auto const& [property_name, property_values] : property_indexed_keyframe.properties) {
  303. // 1. Let property name be the key for m.
  304. // 2. If property name is "composite", or "easing", or "offset", skip the remaining steps in this loop and
  305. // continue from the next member in property-indexed keyframe after m.
  306. // Note: This will never happen, since these fields have dedicated members on BasePropertyIndexedKeyframe
  307. // 3. Let property values be the value for m.
  308. // 4. Let property keyframes be an empty sequence of keyframes.
  309. Vector<BaseKeyframe> property_keyframes;
  310. // 5. For each value, v, in property values perform the following steps:
  311. for (auto const& value : property_values) {
  312. // 1. Let k be a new keyframe with a null keyframe offset.
  313. BaseKeyframe keyframe;
  314. // 2. Add the property-value pair, property name → v, to k.
  315. keyframe.unparsed_properties().set(property_name, value);
  316. // 3. Append k to property keyframes.
  317. property_keyframes.append(keyframe);
  318. }
  319. // 6. Apply the procedure to compute missing keyframe offsets to property keyframes.
  320. compute_missing_keyframe_offsets(property_keyframes);
  321. // 7. Add keyframes in property keyframes to processed keyframes.
  322. processed_keyframes.extend(move(property_keyframes));
  323. }
  324. // 3. Sort processed keyframes by the computed keyframe offset of each keyframe in increasing order.
  325. quick_sort(processed_keyframes, [](auto const& a, auto const& b) {
  326. return a.computed_offset.value() < b.computed_offset.value();
  327. });
  328. // 4. Merge adjacent keyframes in processed keyframes when they have equal computed keyframe offsets.
  329. // Note: The spec doesn't specify how to merge them, but WebKit seems to just override the properties of the
  330. // earlier keyframe with the properties of the later keyframe.
  331. for (int i = 0; i < static_cast<int>(processed_keyframes.size() - 1); i++) {
  332. auto& keyframe_a = processed_keyframes[i];
  333. auto& keyframe_b = processed_keyframes[i + 1];
  334. if (keyframe_a.computed_offset.value() == keyframe_b.computed_offset.value()) {
  335. keyframe_a.easing = keyframe_b.easing;
  336. keyframe_a.composite = keyframe_b.composite;
  337. for (auto const& [property_name, property_value] : keyframe_b.unparsed_properties())
  338. keyframe_a.unparsed_properties().set(property_name, property_value);
  339. processed_keyframes.remove(i + 1);
  340. i--;
  341. }
  342. }
  343. // 5. Let offsets be a sequence of nullable double values assigned based on the type of the "offset" member
  344. // of the property-indexed keyframe as follows:
  345. //
  346. // -> sequence<double?>,
  347. // The value of "offset" as-is.
  348. // -> double?,
  349. // A sequence of length one with the value of "offset" as its single item, i.e. « offset »,
  350. auto offsets = property_indexed_keyframe.offset.has<Optional<double>>()
  351. ? Vector { property_indexed_keyframe.offset.get<Optional<double>>() }
  352. : property_indexed_keyframe.offset.get<Vector<Optional<double>>>();
  353. // 6. Assign each value in offsets to the keyframe offset of the keyframe with corresponding position in
  354. // processed keyframes until the end of either sequence is reached.
  355. for (size_t i = 0; i < offsets.size() && i < processed_keyframes.size(); i++)
  356. processed_keyframes[i].offset = offsets[i];
  357. // 7. Let easings be a sequence of DOMString values assigned based on the type of the "easing" member of the
  358. // property-indexed keyframe as follows:
  359. //
  360. // -> sequence<DOMString>,
  361. // The value of "easing" as-is.
  362. // -> DOMString,
  363. // A sequence of length one with the value of "easing" as its single item, i.e. « easing »,
  364. auto easings = property_indexed_keyframe.easing.has<EasingValue>()
  365. ? Vector { property_indexed_keyframe.easing.get<EasingValue>() }
  366. : property_indexed_keyframe.easing.get<Vector<EasingValue>>();
  367. // 8. If easings is an empty sequence, let it be a sequence of length one containing the single value "linear",
  368. // i.e. « "linear" ».
  369. if (easings.is_empty())
  370. easings.append("linear"_string);
  371. // 9. If easings has fewer items than processed keyframes, repeat the elements in easings successively starting
  372. // from the beginning of the list until easings has as many items as processed keyframes.
  373. //
  374. // For example, if processed keyframes has five items, and easings is the sequence « "ease-in", "ease-out" »,
  375. // easings would be repeated to become « "ease-in", "ease-out", "ease-in", "ease-out", "ease-in" ».
  376. size_t num_easings = easings.size();
  377. size_t index = 0;
  378. while (easings.size() < processed_keyframes.size())
  379. easings.append(easings[index++ % num_easings]);
  380. // 10. If easings has more items than processed keyframes, store the excess items as unused easings.
  381. while (easings.size() > processed_keyframes.size())
  382. unused_easings.append(easings.take_last());
  383. // 11. Assign each value in easings to a property named "easing" on the keyframe with the corresponding position
  384. // in processed keyframes until the end of processed keyframes is reached.
  385. for (size_t i = 0; i < processed_keyframes.size(); i++)
  386. processed_keyframes[i].easing = easings[i];
  387. // 12. If the "composite" member of the property-indexed keyframe is not an empty sequence:
  388. auto composite_value = property_indexed_keyframe.composite;
  389. if (!composite_value.has<Vector<Bindings::CompositeOperationOrAuto>>() || !composite_value.get<Vector<Bindings::CompositeOperationOrAuto>>().is_empty()) {
  390. // 1. Let composite modes be a sequence of CompositeOperationOrAuto values assigned from the "composite"
  391. // member of property-indexed keyframe. If that member is a single CompositeOperationOrAuto value
  392. // operation, let composite modes be a sequence of length one, with the value of the "composite" as its
  393. // single item.
  394. auto composite_modes = composite_value.has<Bindings::CompositeOperationOrAuto>()
  395. ? Vector { composite_value.get<Bindings::CompositeOperationOrAuto>() }
  396. : composite_value.get<Vector<Bindings::CompositeOperationOrAuto>>();
  397. // 2. As with easings, if composite modes has fewer items than processed keyframes, repeat the elements in
  398. // composite modes successively starting from the beginning of the list until composite modes has as
  399. // many items as processed keyframes.
  400. size_t num_composite_modes = composite_modes.size();
  401. index = 0;
  402. while (composite_modes.size() < processed_keyframes.size())
  403. composite_modes.append(composite_modes[index++ % num_composite_modes]);
  404. // 3. Assign each value in composite modes that is not auto to the keyframe-specific composite operation on
  405. // the keyframe with the corresponding position in processed keyframes until the end of processed
  406. // keyframes is reached.
  407. for (size_t i = 0; i < processed_keyframes.size(); i++) {
  408. if (composite_modes[i] != Bindings::CompositeOperationOrAuto::Auto)
  409. processed_keyframes[i].composite = composite_modes[i];
  410. }
  411. }
  412. }
  413. // 6. If processed keyframes is not loosely sorted by offset, throw a TypeError and abort these steps.
  414. if (!is_loosely_sorted_by_offset(processed_keyframes))
  415. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Keyframes are not in ascending order based on offset"sv };
  416. // 7. If there exist any keyframe in processed keyframes whose keyframe offset is non-null and less than zero or
  417. // greater than one, throw a TypeError and abort these steps.
  418. for (size_t i = 0; i < processed_keyframes.size(); i++) {
  419. auto const& keyframe = processed_keyframes[i];
  420. if (!keyframe.offset.has_value())
  421. continue;
  422. auto offset = keyframe.offset.value();
  423. if (offset < 0.0 || offset > 1.0)
  424. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Keyframe {} has invalid offset value {}"sv, i, offset)) };
  425. }
  426. // 8. For each frame in processed keyframes, perform the following steps:
  427. for (auto& keyframe : processed_keyframes) {
  428. // 1. For each property-value pair in frame, parse the property value using the syntax specified for that
  429. // property.
  430. //
  431. // If the property value is invalid according to the syntax for the property, discard the property-value pair.
  432. // User agents that provide support for diagnosing errors in content SHOULD produce an appropriate warning
  433. // highlight
  434. BaseKeyframe::ParsedProperties parsed_properties;
  435. for (auto& [property_string, value_string] : keyframe.unparsed_properties()) {
  436. Optional<CSS::PropertyID> property_id;
  437. // Handle some special cases
  438. if (property_string == "cssFloat"sv) {
  439. property_id = CSS::PropertyID::Float;
  440. } else if (property_string == "cssOffset"sv) {
  441. // FIXME: Support CSS offset property
  442. } else if (property_string == "float"sv || property_string == "offset"sv) {
  443. // Ignore these properties
  444. } else if (auto property = CSS::property_id_from_camel_case_string(property_string); property.has_value()) {
  445. property_id = *property;
  446. }
  447. if (!property_id.has_value())
  448. continue;
  449. auto parser = CSS::Parser::Parser::create(CSS::Parser::ParsingContext(realm), value_string);
  450. if (auto style_value = parser.parse_as_css_value(*property_id)) {
  451. // Handle 'initial' here so we don't have to get the default value of the property every frame in StyleComputer
  452. if (style_value->is_initial())
  453. style_value = CSS::property_initial_value(realm, *property_id);
  454. parsed_properties.set(*property_id, *style_value);
  455. }
  456. }
  457. keyframe.properties.set(move(parsed_properties));
  458. // 2. Let the timing function of frame be the result of parsing the "easing" property on frame using the CSS
  459. // syntax defined for the easing member of the EffectTiming dictionary.
  460. //
  461. // If parsing the "easing" property fails, throw a TypeError and abort this procedure.
  462. auto easing_string = keyframe.easing.get<String>();
  463. auto easing_value = AnimationEffect::parse_easing_string(realm, easing_string);
  464. if (!easing_value)
  465. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Invalid animation easing value: \"{}\"", easing_string)) };
  466. keyframe.easing.set(NonnullRefPtr<CSS::CSSStyleValue const> { *easing_value });
  467. }
  468. // 9. Parse each of the values in unused easings using the CSS syntax defined for easing member of the EffectTiming
  469. // interface, and if any of the values fail to parse, throw a TypeError and abort this procedure.
  470. for (auto& unused_easing : unused_easings) {
  471. auto easing_string = unused_easing.get<String>();
  472. auto easing_value = AnimationEffect::parse_easing_string(realm, easing_string);
  473. if (!easing_value)
  474. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Invalid animation easing value: \"{}\"", easing_string)) };
  475. }
  476. return processed_keyframes;
  477. }
  478. // https://www.w3.org/TR/css-animations-2/#keyframe-processing
  479. void KeyframeEffect::generate_initial_and_final_frames(RefPtr<KeyFrameSet> keyframe_set, HashTable<CSS::PropertyID> const& animated_properties)
  480. {
  481. // 1. Find or create the initial keyframe, a keyframe with a keyframe offset of 0%, default timing function
  482. // as its keyframe timing function, and default composite as its keyframe composite.
  483. KeyFrameSet::ResolvedKeyFrame* initial_keyframe;
  484. if (auto existing_keyframe = keyframe_set->keyframes_by_key.find(0)) {
  485. initial_keyframe = existing_keyframe;
  486. } else {
  487. keyframe_set->keyframes_by_key.insert(0, {});
  488. initial_keyframe = keyframe_set->keyframes_by_key.find(0);
  489. }
  490. // 2. For any property in animated properties that is not otherwise present in a keyframe with an offset of
  491. // 0% or one that would be positioned earlier in the used keyframe order, add the computed value of that
  492. // property on element to initial keyframe’s keyframe values.
  493. for (auto property : animated_properties) {
  494. if (!initial_keyframe->properties.contains(property))
  495. initial_keyframe->properties.set(property, KeyFrameSet::UseInitial {});
  496. }
  497. // 3. If initial keyframe’s keyframe values is not empty, prepend initial keyframe to keyframes.
  498. // 4. Repeat for final keyframe, using an offset of 100%, considering keyframes positioned later in the used
  499. // keyframe order, and appending to keyframes.
  500. KeyFrameSet::ResolvedKeyFrame* final_keyframe;
  501. if (auto existing_keyframe = keyframe_set->keyframes_by_key.find(100 * AnimationKeyFrameKeyScaleFactor)) {
  502. final_keyframe = existing_keyframe;
  503. } else {
  504. keyframe_set->keyframes_by_key.insert(100 * AnimationKeyFrameKeyScaleFactor, {});
  505. final_keyframe = keyframe_set->keyframes_by_key.find(100 * AnimationKeyFrameKeyScaleFactor);
  506. }
  507. for (auto property : animated_properties) {
  508. if (!final_keyframe->properties.contains(property))
  509. final_keyframe->properties.set(property, KeyFrameSet::UseInitial {});
  510. }
  511. }
  512. // https://www.w3.org/TR/web-animations-1/#animation-composite-order
  513. int KeyframeEffect::composite_order(JS::NonnullGCPtr<KeyframeEffect> a, JS::NonnullGCPtr<KeyframeEffect> b)
  514. {
  515. // 1. Let the associated animation of an animation effect be the animation associated with the animation effect.
  516. auto a_animation = a->associated_animation();
  517. auto b_animation = b->associated_animation();
  518. // 2. Sort A and B by applying the following conditions in turn until the order is resolved,
  519. // 1. If A and B’s associated animations differ by class, sort by any inter-class composite order defined for
  520. // the corresponding classes.
  521. auto a_class = a_animation->animation_class();
  522. auto b_class = b_animation->animation_class();
  523. // From https://www.w3.org/TR/css-animations-2/#animation-composite-order:
  524. // "CSS Animations with an owning element have a later composite order than CSS Transitions but an earlier
  525. // composite order than animations without a specific animation class."
  526. if (a_class != b_class)
  527. return to_underlying(a_class) - to_underlying(b_class);
  528. // 2. If A and B are still not sorted, sort by any class-specific composite order defined by the common class of
  529. // A and B’s associated animations.
  530. if (auto order = a_animation->class_specific_composite_order(*b_animation); order.has_value())
  531. return order.value();
  532. // 3. If A and B are still not sorted, sort by the position of their associated animations in the global
  533. // animation list.
  534. return a_animation->global_animation_list_order() - b_animation->global_animation_list_order();
  535. }
  536. JS::NonnullGCPtr<KeyframeEffect> KeyframeEffect::create(JS::Realm& realm)
  537. {
  538. return realm.create<KeyframeEffect>(realm);
  539. }
  540. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect
  541. WebIDL::ExceptionOr<JS::NonnullGCPtr<KeyframeEffect>> KeyframeEffect::construct_impl(
  542. JS::Realm& realm,
  543. JS::Handle<DOM::Element> const& target,
  544. Optional<JS::Handle<JS::Object>> const& keyframes,
  545. Variant<double, KeyframeEffectOptions> options)
  546. {
  547. // 1. Create a new KeyframeEffect object, effect.
  548. auto effect = realm.create<KeyframeEffect>(realm);
  549. // 2. Set the target element of effect to target.
  550. effect->set_target(target);
  551. // 3. Set the target pseudo-selector to the result corresponding to the first matching condition from below.
  552. // If options is a KeyframeEffectOptions object with a pseudoElement property,
  553. if (options.has<KeyframeEffectOptions>()) {
  554. // Set the target pseudo-selector to the value of the pseudoElement property.
  555. //
  556. // When assigning this property, the error-handling defined for the pseudoElement setter on the interface is
  557. // applied. If the setter requires an exception to be thrown, this procedure must throw the same exception and
  558. // abort all further steps.
  559. TRY(effect->set_pseudo_element(options.get<KeyframeEffectOptions>().pseudo_element));
  560. }
  561. // Otherwise,
  562. else {
  563. // Set the target pseudo-selector to null.
  564. // Note: This is the default when constructed
  565. }
  566. // 4. Let timing input be the result corresponding to the first matching condition from below.
  567. KeyframeEffectOptions timing_input;
  568. // If options is a KeyframeEffectOptions object,
  569. if (options.has<KeyframeEffectOptions>()) {
  570. // Let timing input be options.
  571. timing_input = options.get<KeyframeEffectOptions>();
  572. }
  573. // Otherwise (if options is a double),
  574. else {
  575. // Let timing input be a new EffectTiming object with all members set to their default values and duration set
  576. // to options.
  577. timing_input.duration = options.get<double>();
  578. }
  579. // 5. Call the procedure to update the timing properties of an animation effect of effect from timing input.
  580. // If that procedure causes an exception to be thrown, propagate the exception and abort this procedure.
  581. TRY(effect->update_timing(timing_input.to_optional_effect_timing()));
  582. // 6. If options is a KeyframeEffectOptions object, assign the composite property of effect to the corresponding
  583. // value from options.
  584. //
  585. // When assigning this property, the error-handling defined for the corresponding setter on the KeyframeEffect
  586. // interface is applied. If the setter requires an exception to be thrown for the value specified by options,
  587. // this procedure must throw the same exception and abort all further steps.
  588. if (options.has<KeyframeEffectOptions>())
  589. effect->set_composite(options.get<KeyframeEffectOptions>().composite);
  590. // 7. Initialize the set of keyframes by performing the procedure defined for setKeyframes() passing keyframes as
  591. // the input.
  592. TRY(effect->set_keyframes(keyframes));
  593. return effect;
  594. }
  595. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect-source
  596. WebIDL::ExceptionOr<JS::NonnullGCPtr<KeyframeEffect>> KeyframeEffect::construct_impl(JS::Realm& realm, JS::NonnullGCPtr<KeyframeEffect> source)
  597. {
  598. // 1. Create a new KeyframeEffect object, effect.
  599. auto effect = realm.create<KeyframeEffect>(realm);
  600. // 2. Set the following properties of effect using the corresponding values of source:
  601. // - effect target,
  602. effect->m_target_element = source->target();
  603. // - keyframes,
  604. effect->m_keyframes = source->m_keyframes;
  605. // - composite operation, and
  606. effect->set_composite(source->composite());
  607. // - all specified timing properties:
  608. // - start delay,
  609. effect->m_start_delay = source->m_start_delay;
  610. // - end delay,
  611. effect->m_end_delay = source->m_end_delay;
  612. // - fill mode,
  613. effect->m_fill_mode = source->m_fill_mode;
  614. // - iteration start,
  615. effect->m_iteration_start = source->m_iteration_start;
  616. // - iteration count,
  617. effect->m_iteration_count = source->m_iteration_count;
  618. // - iteration duration,
  619. effect->m_iteration_duration = source->m_iteration_duration;
  620. // - playback direction, and
  621. effect->m_playback_direction = source->m_playback_direction;
  622. // - timing function.
  623. effect->m_timing_function = source->m_timing_function;
  624. return effect;
  625. }
  626. void KeyframeEffect::set_target(DOM::Element* target)
  627. {
  628. if (auto animation = this->associated_animation()) {
  629. if (m_target_element)
  630. m_target_element->disassociate_with_animation(*animation);
  631. if (target)
  632. target->associate_with_animation(*animation);
  633. }
  634. m_target_element = target;
  635. }
  636. Optional<String> KeyframeEffect::pseudo_element() const
  637. {
  638. if (!m_target_pseudo_selector.has_value())
  639. return {};
  640. return MUST(String::formatted("::{}", m_target_pseudo_selector->name()));
  641. }
  642. // https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-pseudoelement
  643. WebIDL::ExceptionOr<void> KeyframeEffect::set_pseudo_element(Optional<String> value)
  644. {
  645. // On setting, sets the target pseudo-selector of the animation effect to the result of
  646. // pseudo-element parsing on the provided value, defined as the following:
  647. // NOTE: The actual definition is in pseudo_element_parsing().
  648. m_target_pseudo_selector = TRY(pseudo_element_parsing(realm(), value));
  649. return {};
  650. }
  651. Optional<CSS::Selector::PseudoElement::Type> KeyframeEffect::pseudo_element_type() const
  652. {
  653. if (!m_target_pseudo_selector.has_value())
  654. return {};
  655. return m_target_pseudo_selector->type();
  656. }
  657. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-getkeyframes
  658. WebIDL::ExceptionOr<JS::MarkedVector<JS::Object*>> KeyframeEffect::get_keyframes()
  659. {
  660. if (m_keyframe_objects.size() != m_keyframes.size()) {
  661. auto& vm = this->vm();
  662. auto& realm = this->realm();
  663. // Recalculate the keyframe objects
  664. VERIFY(m_keyframe_objects.size() == 0);
  665. for (auto& keyframe : m_keyframes) {
  666. auto object = JS::Object::create(realm, realm.intrinsics().object_prototype());
  667. TRY(object->set(vm.names.offset, keyframe.offset.has_value() ? JS::Value(keyframe.offset.value()) : JS::js_null(), ShouldThrowExceptions::Yes));
  668. TRY(object->set(vm.names.computedOffset, JS::Value(keyframe.computed_offset.value()), ShouldThrowExceptions::Yes));
  669. auto easing_value = keyframe.easing.get<NonnullRefPtr<CSS::CSSStyleValue const>>();
  670. TRY(object->set(vm.names.easing, JS::PrimitiveString::create(vm, easing_value->to_string()), ShouldThrowExceptions::Yes));
  671. if (keyframe.composite == Bindings::CompositeOperationOrAuto::Replace) {
  672. TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "replace"sv), ShouldThrowExceptions::Yes));
  673. } else if (keyframe.composite == Bindings::CompositeOperationOrAuto::Add) {
  674. TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "add"sv), ShouldThrowExceptions::Yes));
  675. } else if (keyframe.composite == Bindings::CompositeOperationOrAuto::Accumulate) {
  676. TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "accumulate"sv), ShouldThrowExceptions::Yes));
  677. } else {
  678. TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "auto"sv), ShouldThrowExceptions::Yes));
  679. }
  680. for (auto const& [id, value] : keyframe.parsed_properties()) {
  681. auto value_string = JS::PrimitiveString::create(vm, value->to_string());
  682. TRY(object->set(JS::PropertyKey(DeprecatedFlyString(CSS::camel_case_string_from_property_id(id))), value_string, ShouldThrowExceptions::Yes));
  683. }
  684. m_keyframe_objects.append(object);
  685. }
  686. }
  687. JS::MarkedVector<JS::Object*> keyframes { heap() };
  688. for (auto const& keyframe : m_keyframe_objects)
  689. keyframes.append(keyframe);
  690. return keyframes;
  691. }
  692. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-setkeyframes
  693. WebIDL::ExceptionOr<void> KeyframeEffect::set_keyframes(Optional<JS::Handle<JS::Object>> const& keyframe_object)
  694. {
  695. m_keyframe_objects.clear();
  696. m_keyframes = TRY(process_a_keyframes_argument(realm(), keyframe_object.has_value() ? JS::GCPtr { keyframe_object->ptr() } : JS::GCPtr<Object> {}));
  697. // FIXME: After processing the keyframe argument, we need to turn the set of keyframes into a set of computed
  698. // keyframes using the procedure outlined in the second half of
  699. // https://www.w3.org/TR/web-animations-1/#calculating-computed-keyframes. For now, just compute the
  700. // missing keyframe offsets
  701. compute_missing_keyframe_offsets(m_keyframes);
  702. auto keyframe_set = adopt_ref(*new KeyFrameSet);
  703. m_target_properties.clear();
  704. auto target = this->target();
  705. for (auto& keyframe : m_keyframes) {
  706. Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame resolved_keyframe;
  707. auto key = static_cast<u64>(keyframe.computed_offset.value() * 100 * AnimationKeyFrameKeyScaleFactor);
  708. for (auto [property_id, property_value] : keyframe.parsed_properties()) {
  709. if (property_value->is_unresolved() && target)
  710. property_value = CSS::Parser::Parser::resolve_unresolved_style_value(CSS::Parser::ParsingContext { target->document() }, *target, pseudo_element_type(), property_id, property_value->as_unresolved());
  711. CSS::StyleComputer::for_each_property_expanding_shorthands(property_id, property_value, CSS::StyleComputer::AllowUnresolved::Yes, [&](CSS::PropertyID shorthand_id, CSS::CSSStyleValue const& shorthand_value) {
  712. m_target_properties.set(shorthand_id);
  713. resolved_keyframe.properties.set(shorthand_id, NonnullRefPtr<CSS::CSSStyleValue const> { shorthand_value });
  714. });
  715. }
  716. keyframe_set->keyframes_by_key.insert(key, resolved_keyframe);
  717. }
  718. generate_initial_and_final_frames(keyframe_set, m_target_properties);
  719. m_key_frame_set = keyframe_set;
  720. return {};
  721. }
  722. KeyframeEffect::KeyframeEffect(JS::Realm& realm)
  723. : AnimationEffect(realm)
  724. {
  725. }
  726. void KeyframeEffect::initialize(JS::Realm& realm)
  727. {
  728. Base::initialize(realm);
  729. WEB_SET_PROTOTYPE_FOR_INTERFACE(KeyframeEffect);
  730. }
  731. void KeyframeEffect::visit_edges(Cell::Visitor& visitor)
  732. {
  733. Base::visit_edges(visitor);
  734. visitor.visit(m_target_element);
  735. visitor.visit(m_keyframe_objects);
  736. }
  737. static CSS::RequiredInvalidationAfterStyleChange compute_required_invalidation(HashMap<CSS::PropertyID, NonnullRefPtr<CSS::CSSStyleValue const>> const& old_properties, HashMap<CSS::PropertyID, NonnullRefPtr<CSS::CSSStyleValue const>> const& new_properties)
  738. {
  739. CSS::RequiredInvalidationAfterStyleChange invalidation;
  740. auto old_and_new_properties = MUST(Bitmap::create(to_underlying(CSS::last_property_id) + 1, 0));
  741. for (auto const& [property_id, _] : old_properties)
  742. old_and_new_properties.set(to_underlying(property_id), 1);
  743. for (auto const& [property_id, _] : new_properties)
  744. old_and_new_properties.set(to_underlying(property_id), 1);
  745. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  746. if (!old_and_new_properties.get(i))
  747. continue;
  748. auto property_id = static_cast<CSS::PropertyID>(i);
  749. auto const* old_value = old_properties.get(property_id).value_or({});
  750. auto const* new_value = new_properties.get(property_id).value_or({});
  751. if (!old_value && !new_value)
  752. continue;
  753. invalidation |= compute_property_invalidation(property_id, old_value, new_value);
  754. }
  755. return invalidation;
  756. }
  757. void KeyframeEffect::update_style_properties()
  758. {
  759. auto target = this->target();
  760. if (!target)
  761. return;
  762. Optional<CSS::StyleProperties&> style = {};
  763. if (!pseudo_element_type().has_value())
  764. style = target->computed_css_values();
  765. else
  766. style = target->pseudo_element_computed_css_values(pseudo_element_type().value());
  767. if (!style.has_value())
  768. return;
  769. auto animated_properties_before_update = style->animated_property_values();
  770. auto& document = target->document();
  771. document.style_computer().collect_animation_into(*target, pseudo_element_type(), *this, *style, CSS::StyleComputer::AnimationRefresh::Yes);
  772. // Traversal of the subtree is necessary to update the animated properties inherited from the target element.
  773. target->for_each_in_subtree_of_type<DOM::Element>([&](auto& element) {
  774. auto element_style = element.computed_css_values();
  775. if (!element_style.has_value() || !element.layout_node())
  776. return TraversalDecision::Continue;
  777. for (auto i = to_underlying(CSS::first_property_id); i <= to_underlying(CSS::last_property_id); ++i) {
  778. if (element_style->is_property_inherited(static_cast<CSS::PropertyID>(i))) {
  779. auto new_value = CSS::StyleComputer::get_inherit_value(document.realm(), static_cast<CSS::PropertyID>(i), &element);
  780. element_style->set_property(static_cast<CSS::PropertyID>(i), *new_value, CSS::StyleProperties::Inherited::Yes);
  781. }
  782. }
  783. element.layout_node()->apply_style(*element_style);
  784. return TraversalDecision::Continue;
  785. });
  786. auto invalidation = compute_required_invalidation(animated_properties_before_update, style->animated_property_values());
  787. if (!pseudo_element_type().has_value()) {
  788. if (target->layout_node())
  789. target->layout_node()->apply_style(*style);
  790. } else {
  791. auto pseudo_element_node = target->get_pseudo_element_node(pseudo_element_type().value());
  792. if (auto* node_with_style = dynamic_cast<Layout::NodeWithStyle*>(pseudo_element_node.ptr())) {
  793. node_with_style->apply_style(*style);
  794. }
  795. }
  796. if (invalidation.relayout)
  797. document.set_needs_layout();
  798. if (invalidation.rebuild_layout_tree)
  799. document.invalidate_layout_tree();
  800. if (invalidation.repaint)
  801. document.set_needs_to_resolve_paint_only_properties();
  802. if (invalidation.rebuild_stacking_context_tree)
  803. document.invalidate_stacking_context_tree();
  804. }
  805. }