KeyframeEffect.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. /*
  2. * Copyright (c) 2023-2024, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Bitmap.h>
  7. #include <AK/QuickSort.h>
  8. #include <LibJS/Runtime/Iterator.h>
  9. #include <LibWeb/Animations/Animation.h>
  10. #include <LibWeb/Animations/KeyframeEffect.h>
  11. #include <LibWeb/Animations/PseudoElementParsing.h>
  12. #include <LibWeb/Bindings/KeyframeEffectPrototype.h>
  13. #include <LibWeb/CSS/Parser/Parser.h>
  14. #include <LibWeb/CSS/StyleComputer.h>
  15. #include <LibWeb/Layout/Node.h>
  16. #include <LibWeb/Painting/Paintable.h>
  17. #include <LibWeb/WebIDL/ExceptionOr.h>
  18. namespace Web::Animations {
  19. GC_DEFINE_ALLOCATOR(KeyframeEffect);
  20. template<typename T>
  21. 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)
  22. {
  23. auto& vm = realm.vm();
  24. if (TRY(value.is_array(vm))) {
  25. Vector<T> offsets;
  26. auto iterator = TRY(JS::get_iterator(vm, value, JS::IteratorHint::Sync));
  27. auto values = TRY(JS::iterator_to_list(vm, iterator));
  28. for (auto const& element : values) {
  29. if (element.is_undefined()) {
  30. offsets.append({});
  31. } else {
  32. offsets.append(TRY(value_converter(element)));
  33. }
  34. }
  35. return offsets;
  36. }
  37. return TRY(value_converter(value));
  38. }
  39. enum class AllowLists {
  40. Yes,
  41. No,
  42. };
  43. template<AllowLists AL>
  44. using KeyframeType = Conditional<AL == AllowLists::Yes, BasePropertyIndexedKeyframe, BaseKeyframe>;
  45. // https://www.w3.org/TR/web-animations-1/#process-a-keyframe-like-object
  46. template<AllowLists AL>
  47. static WebIDL::ExceptionOr<KeyframeType<AL>> process_a_keyframe_like_object(JS::Realm& realm, JS::Value keyframe_input)
  48. {
  49. auto& vm = realm.vm();
  50. Function<WebIDL::ExceptionOr<Optional<double>>(JS::Value)> to_offset = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Optional<double>> {
  51. if (value.is_undefined())
  52. return Optional<double> {};
  53. auto double_value = TRY(value.to_double(vm));
  54. if (isnan(double_value) || isinf(double_value))
  55. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Invalid offset value: {}", TRY(value.to_string(vm)))) };
  56. return double_value;
  57. };
  58. Function<WebIDL::ExceptionOr<String>(JS::Value)> to_string = [&vm](JS::Value value) -> WebIDL::ExceptionOr<String> {
  59. return TRY(value.to_string(vm));
  60. };
  61. Function<WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto>(JS::Value)> to_composite_operation = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto> {
  62. if (value.is_undefined())
  63. return Bindings::CompositeOperationOrAuto::Auto;
  64. auto string_value = TRY(value.to_string(vm));
  65. if (string_value == "replace")
  66. return Bindings::CompositeOperationOrAuto::Replace;
  67. if (string_value == "add")
  68. return Bindings::CompositeOperationOrAuto::Add;
  69. if (string_value == "accumulate")
  70. return Bindings::CompositeOperationOrAuto::Accumulate;
  71. if (string_value == "auto")
  72. return Bindings::CompositeOperationOrAuto::Auto;
  73. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid composite value"sv };
  74. };
  75. // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript
  76. // value, and the dictionary type depending on the value of the allow lists flag as follows:
  77. //
  78. // -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.
  79. // -> Otherwise, use the following dictionary type: <BaseKeyframe>.
  80. //
  81. // Store the result of this procedure as keyframe output.
  82. KeyframeType<AL> keyframe_output;
  83. if (keyframe_input.is_nullish())
  84. return keyframe_output;
  85. auto& keyframe_object = keyframe_input.as_object();
  86. auto composite = TRY(keyframe_object.get("composite"));
  87. if (composite.is_undefined())
  88. composite = JS::PrimitiveString::create(vm, "auto"_string);
  89. auto easing = TRY(keyframe_object.get("easing"));
  90. if (easing.is_undefined())
  91. easing = JS::PrimitiveString::create(vm, "linear"_string);
  92. auto offset = TRY(keyframe_object.get("offset"));
  93. if constexpr (AL == AllowLists::Yes) {
  94. keyframe_output.composite = TRY(convert_value_to_maybe_list(realm, composite, to_composite_operation));
  95. auto easing_maybe_list = TRY(convert_value_to_maybe_list(realm, easing, to_string));
  96. easing_maybe_list.visit(
  97. [&](String const& value) {
  98. keyframe_output.easing = EasingValue { value };
  99. },
  100. [&](Vector<String> const& values) {
  101. Vector<EasingValue> easing_values;
  102. for (auto& easing_value : values)
  103. easing_values.append(easing_value);
  104. keyframe_output.easing = move(easing_values);
  105. });
  106. keyframe_output.offset = TRY(convert_value_to_maybe_list(realm, offset, to_offset));
  107. } else {
  108. keyframe_output.composite = TRY(to_composite_operation(composite));
  109. keyframe_output.easing = TRY(to_string(easing));
  110. keyframe_output.offset = TRY(to_offset(offset));
  111. }
  112. // 2. Build up a list of animatable properties as follows:
  113. //
  114. // 1. Let animatable properties be a list of property names (including shorthand properties that have longhand
  115. // sub-properties that are animatable) that can be animated by the implementation.
  116. // 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the
  117. // animation property name to IDL attribute name algorithm.
  118. // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the
  119. // object.
  120. // 4. Make up a new list animation properties that consists of all of the properties that are in both input
  121. // properties and animatable properties, or which are in input properties and conform to the
  122. // <custom-property-name> production.
  123. auto input_properties = TRY(keyframe_object.enumerable_own_property_names(JS::Object::PropertyKind::Key));
  124. Vector<String> animation_properties;
  125. Optional<JS::Value> all_value;
  126. for (auto const& input_property : input_properties) {
  127. if (!input_property.is_string())
  128. continue;
  129. auto name = input_property.as_string().utf8_string();
  130. if (name == "all"sv) {
  131. all_value = TRY(keyframe_object.get(vm.names.all));
  132. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) {
  133. auto property = static_cast<CSS::PropertyID>(i);
  134. if (CSS::is_animatable_property(property))
  135. animation_properties.append(String { CSS::string_from_property_id(property) });
  136. }
  137. } else {
  138. // Handle the two special cases
  139. if (name == "cssFloat"sv || name == "cssOffset"sv) {
  140. animation_properties.append(name);
  141. } else if (name == "float"sv || name == "offset"sv) {
  142. // Ignore these property names
  143. } else if (auto property = CSS::property_id_from_camel_case_string(name); property.has_value()) {
  144. if (CSS::is_animatable_property(property.value()))
  145. animation_properties.append(name);
  146. }
  147. }
  148. }
  149. // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name.
  150. quick_sort(animation_properties);
  151. // 6. For each property name in animation properties,
  152. for (auto const& property_name : animation_properties) {
  153. // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name
  154. // as the property key and keyframe input as the receiver.
  155. // 2. Check the completion record of raw value.
  156. JS::PropertyKey key { property_name.to_byte_string(), JS::PropertyKey::StringMayBeNumber::No };
  157. auto raw_value = TRY(keyframe_object.has_property(key)) ? TRY(keyframe_object.get(key)) : *all_value;
  158. using PropertyValuesType = Conditional<AL == AllowLists::Yes, Vector<String>, String>;
  159. PropertyValuesType property_values;
  160. // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:
  161. // -> If allow lists is true,
  162. if constexpr (AL == AllowLists::Yes) {
  163. // Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>)
  164. // using the procedures defined for converting an ECMAScript value to an IDL value [WEBIDL].
  165. auto intermediate_property_values = TRY(convert_value_to_maybe_list(realm, raw_value, to_string));
  166. // If property values is a single DOMString, replace property values with a sequence of DOMStrings with the
  167. // original value of property values as the only element.
  168. if (intermediate_property_values.has<String>())
  169. property_values = Vector { intermediate_property_values.get<String>() };
  170. else
  171. property_values = intermediate_property_values.get<Vector<String>>();
  172. }
  173. // -> Otherwise,
  174. else {
  175. // Let property values be the result of converting raw value to a DOMString using the procedure for
  176. // converting an ECMAScript value to a DOMString [WEBIDL].
  177. property_values = TRY(raw_value.to_string(vm));
  178. }
  179. // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation
  180. // property name algorithm to property name.
  181. // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL
  182. // attribute name) in the steps above.
  183. // 5. Add a property to keyframe output with normalized property name as the property name, and property values
  184. // as the property value.
  185. if constexpr (AL == AllowLists::Yes) {
  186. keyframe_output.properties.set(property_name, property_values);
  187. } else {
  188. keyframe_output.unparsed_properties().set(property_name, property_values);
  189. }
  190. }
  191. return keyframe_output;
  192. }
  193. // https://www.w3.org/TR/web-animations-1/#compute-missing-keyframe-offsets
  194. static void compute_missing_keyframe_offsets(Vector<BaseKeyframe>& keyframes)
  195. {
  196. // 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe
  197. // offset value.
  198. for (auto& keyframe : keyframes)
  199. keyframe.computed_offset = keyframe.offset;
  200. // 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in
  201. // keyframes is null, set the computed keyframe offset of the first keyframe to 0.
  202. if (keyframes.size() > 1 && !keyframes[0].computed_offset.has_value())
  203. keyframes[0].computed_offset = 0.0;
  204. // 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset
  205. // to 1.
  206. if (!keyframes.is_empty() && !keyframes.last().computed_offset.has_value())
  207. keyframes.last().computed_offset = 1.0;
  208. // 4. For each pair of keyframes A and B where:
  209. // - A appears before B in keyframes, and
  210. // - A and B have a computed keyframe offset that is not null, and
  211. // - all keyframes between A and B have a null computed keyframe offset,
  212. auto find_next_index_of_keyframe_with_computed_offset = [&](size_t starting_index) -> Optional<size_t> {
  213. for (size_t index = starting_index; index < keyframes.size(); index++) {
  214. if (keyframes[index].computed_offset.has_value())
  215. return index;
  216. }
  217. return {};
  218. };
  219. auto maybe_index_a = find_next_index_of_keyframe_with_computed_offset(0);
  220. if (!maybe_index_a.has_value())
  221. return;
  222. auto index_a = maybe_index_a.value();
  223. auto maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_a + 1);
  224. while (maybe_index_b.has_value()) {
  225. auto index_b = maybe_index_b.value();
  226. // calculate the computed keyframe offset of each keyframe between A and B as follows:
  227. for (size_t keyframe_index = index_a + 1; keyframe_index < index_b; keyframe_index++) {
  228. // 1. Let offsetk be the computed keyframe offset of a keyframe k.
  229. auto offset_a = keyframes[index_a].computed_offset.value();
  230. auto offset_b = keyframes[index_b].computed_offset.value();
  231. // 2. Let n be the number of keyframes between and including A and B minus 1.
  232. auto n = static_cast<double>(index_b - index_a);
  233. // 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the
  234. // first keyframe after A has an index of 1.
  235. auto index = static_cast<double>(keyframe_index - index_a);
  236. // 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.
  237. keyframes[keyframe_index].computed_offset = (offset_a + (offset_b - offset_a)) * index / n;
  238. }
  239. index_a = index_b;
  240. maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_b + 1);
  241. }
  242. }
  243. // https://www.w3.org/TR/web-animations-1/#loosely-sorted-by-offset
  244. static bool is_loosely_sorted_by_offset(Vector<BaseKeyframe> const& keyframes)
  245. {
  246. // The list of keyframes for a keyframe effect must be loosely sorted by offset which means that for each keyframe
  247. // in the list that has a keyframe offset that is not null, the offset is greater than or equal to the offset of the
  248. // previous keyframe in the list with a keyframe offset that is not null, if any.
  249. Optional<double> last_offset;
  250. for (auto const& keyframe : keyframes) {
  251. if (!keyframe.offset.has_value())
  252. continue;
  253. if (last_offset.has_value() && keyframe.offset.value() < last_offset.value())
  254. return false;
  255. last_offset = keyframe.offset;
  256. }
  257. return true;
  258. }
  259. // https://www.w3.org/TR/web-animations-1/#process-a-keyframes-argument
  260. static WebIDL::ExceptionOr<Vector<BaseKeyframe>> process_a_keyframes_argument(JS::Realm& realm, GC::Ptr<JS::Object> object)
  261. {
  262. auto& vm = realm.vm();
  263. // 1. If object is null, return an empty sequence of keyframes.
  264. if (!object)
  265. return Vector<BaseKeyframe> {};
  266. // 2. Let processed keyframes be an empty sequence of keyframes.
  267. Vector<BaseKeyframe> processed_keyframes;
  268. Vector<EasingValue> unused_easings;
  269. // 3. Let method be the result of GetMethod(object, @@iterator).
  270. // 4. Check the completion record of method.
  271. auto method = TRY(JS::Value(object).get_method(vm, vm.well_known_symbol_iterator()));
  272. // 5. Perform the steps corresponding to the first matching condition from below,
  273. // -> If method is not undefined,
  274. if (method) {
  275. // 1. Let iter be GetIterator(object, method).
  276. // 2. Check the completion record of iter.
  277. auto iter = TRY(JS::get_iterator_from_method(vm, object, *method));
  278. // 3. Repeat:
  279. while (true) {
  280. // 1. Let next be IteratorStep(iter).
  281. // 2. Check the completion record of next.
  282. auto next = TRY(JS::iterator_step(vm, iter));
  283. // 3. If next is false abort this loop.
  284. if (!next)
  285. break;
  286. // 4. Let nextItem be IteratorValue(next).
  287. // 5. Check the completion record of nextItem.
  288. auto next_item = TRY(JS::iterator_value(vm, *next));
  289. // 6. If Type(nextItem) is not Undefined, Null or Object, then throw a TypeError and abort these steps.
  290. if (!next_item.is_nullish() && !next_item.is_object())
  291. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOrNull, next_item.to_string_without_side_effects());
  292. // 7. Append to processed keyframes the result of running the procedure to process a keyframe-like object
  293. // passing nextItem as the keyframe input and with the allow lists flag set to false.
  294. processed_keyframes.append(TRY(process_a_keyframe_like_object<AllowLists::No>(realm, next_item)));
  295. }
  296. }
  297. // -> Otherwise,
  298. else {
  299. // 1. Let property-indexed keyframe be the result of running the procedure to process a keyframe-like object
  300. // passing object as the keyframe input and with the allow lists flag set to true.
  301. auto property_indexed_keyframe = TRY(process_a_keyframe_like_object<AllowLists::Yes>(realm, object));
  302. // 2. For each member, m, in property-indexed keyframe, perform the following steps:
  303. for (auto const& [property_name, property_values] : property_indexed_keyframe.properties) {
  304. // 1. Let property name be the key for m.
  305. // 2. If property name is "composite", or "easing", or "offset", skip the remaining steps in this loop and
  306. // continue from the next member in property-indexed keyframe after m.
  307. // Note: This will never happen, since these fields have dedicated members on BasePropertyIndexedKeyframe
  308. // 3. Let property values be the value for m.
  309. // 4. Let property keyframes be an empty sequence of keyframes.
  310. Vector<BaseKeyframe> property_keyframes;
  311. // 5. For each value, v, in property values perform the following steps:
  312. for (auto const& value : property_values) {
  313. // 1. Let k be a new keyframe with a null keyframe offset.
  314. BaseKeyframe keyframe;
  315. // 2. Add the property-value pair, property name → v, to k.
  316. keyframe.unparsed_properties().set(property_name, value);
  317. // 3. Append k to property keyframes.
  318. property_keyframes.append(keyframe);
  319. }
  320. // 6. Apply the procedure to compute missing keyframe offsets to property keyframes.
  321. compute_missing_keyframe_offsets(property_keyframes);
  322. // 7. Add keyframes in property keyframes to processed keyframes.
  323. processed_keyframes.extend(move(property_keyframes));
  324. }
  325. // 3. Sort processed keyframes by the computed keyframe offset of each keyframe in increasing order.
  326. quick_sort(processed_keyframes, [](auto const& a, auto const& b) {
  327. return a.computed_offset.value() < b.computed_offset.value();
  328. });
  329. // 4. Merge adjacent keyframes in processed keyframes when they have equal computed keyframe offsets.
  330. // Note: The spec doesn't specify how to merge them, but WebKit seems to just override the properties of the
  331. // earlier keyframe with the properties of the later keyframe.
  332. for (int i = 0; i < static_cast<int>(processed_keyframes.size() - 1); i++) {
  333. auto& keyframe_a = processed_keyframes[i];
  334. auto& keyframe_b = processed_keyframes[i + 1];
  335. if (keyframe_a.computed_offset.value() == keyframe_b.computed_offset.value()) {
  336. keyframe_a.easing = keyframe_b.easing;
  337. keyframe_a.composite = keyframe_b.composite;
  338. for (auto const& [property_name, property_value] : keyframe_b.unparsed_properties())
  339. keyframe_a.unparsed_properties().set(property_name, property_value);
  340. processed_keyframes.remove(i + 1);
  341. i--;
  342. }
  343. }
  344. // 5. Let offsets be a sequence of nullable double values assigned based on the type of the "offset" member
  345. // of the property-indexed keyframe as follows:
  346. //
  347. // -> sequence<double?>,
  348. // The value of "offset" as-is.
  349. // -> double?,
  350. // A sequence of length one with the value of "offset" as its single item, i.e. « offset »,
  351. auto offsets = property_indexed_keyframe.offset.has<Optional<double>>()
  352. ? Vector { property_indexed_keyframe.offset.get<Optional<double>>() }
  353. : property_indexed_keyframe.offset.get<Vector<Optional<double>>>();
  354. // 6. Assign each value in offsets to the keyframe offset of the keyframe with corresponding position in
  355. // processed keyframes until the end of either sequence is reached.
  356. for (size_t i = 0; i < offsets.size() && i < processed_keyframes.size(); i++)
  357. processed_keyframes[i].offset = offsets[i];
  358. // 7. Let easings be a sequence of DOMString values assigned based on the type of the "easing" member of the
  359. // property-indexed keyframe as follows:
  360. //
  361. // -> sequence<DOMString>,
  362. // The value of "easing" as-is.
  363. // -> DOMString,
  364. // A sequence of length one with the value of "easing" as its single item, i.e. « easing »,
  365. auto easings = property_indexed_keyframe.easing.has<EasingValue>()
  366. ? Vector { property_indexed_keyframe.easing.get<EasingValue>() }
  367. : property_indexed_keyframe.easing.get<Vector<EasingValue>>();
  368. // 8. If easings is an empty sequence, let it be a sequence of length one containing the single value "linear",
  369. // i.e. « "linear" ».
  370. if (easings.is_empty())
  371. easings.append("linear"_string);
  372. // 9. If easings has fewer items than processed keyframes, repeat the elements in easings successively starting
  373. // from the beginning of the list until easings has as many items as processed keyframes.
  374. //
  375. // For example, if processed keyframes has five items, and easings is the sequence « "ease-in", "ease-out" »,
  376. // easings would be repeated to become « "ease-in", "ease-out", "ease-in", "ease-out", "ease-in" ».
  377. size_t num_easings = easings.size();
  378. size_t index = 0;
  379. while (easings.size() < processed_keyframes.size())
  380. easings.append(easings[index++ % num_easings]);
  381. // 10. If easings has more items than processed keyframes, store the excess items as unused easings.
  382. while (easings.size() > processed_keyframes.size())
  383. unused_easings.append(easings.take_last());
  384. // 11. Assign each value in easings to a property named "easing" on the keyframe with the corresponding position
  385. // in processed keyframes until the end of processed keyframes is reached.
  386. for (size_t i = 0; i < processed_keyframes.size(); i++)
  387. processed_keyframes[i].easing = easings[i];
  388. // 12. If the "composite" member of the property-indexed keyframe is not an empty sequence:
  389. auto composite_value = property_indexed_keyframe.composite;
  390. if (!composite_value.has<Vector<Bindings::CompositeOperationOrAuto>>() || !composite_value.get<Vector<Bindings::CompositeOperationOrAuto>>().is_empty()) {
  391. // 1. Let composite modes be a sequence of CompositeOperationOrAuto values assigned from the "composite"
  392. // member of property-indexed keyframe. If that member is a single CompositeOperationOrAuto value
  393. // operation, let composite modes be a sequence of length one, with the value of the "composite" as its
  394. // single item.
  395. auto composite_modes = composite_value.has<Bindings::CompositeOperationOrAuto>()
  396. ? Vector { composite_value.get<Bindings::CompositeOperationOrAuto>() }
  397. : composite_value.get<Vector<Bindings::CompositeOperationOrAuto>>();
  398. // 2. As with easings, if composite modes has fewer items than processed keyframes, repeat the elements in
  399. // composite modes successively starting from the beginning of the list until composite modes has as
  400. // many items as processed keyframes.
  401. size_t num_composite_modes = composite_modes.size();
  402. index = 0;
  403. while (composite_modes.size() < processed_keyframes.size())
  404. composite_modes.append(composite_modes[index++ % num_composite_modes]);
  405. // 3. Assign each value in composite modes that is not auto to the keyframe-specific composite operation on
  406. // the keyframe with the corresponding position in processed keyframes until the end of processed
  407. // keyframes is reached.
  408. for (size_t i = 0; i < processed_keyframes.size(); i++) {
  409. if (composite_modes[i] != Bindings::CompositeOperationOrAuto::Auto)
  410. processed_keyframes[i].composite = composite_modes[i];
  411. }
  412. }
  413. }
  414. // 6. If processed keyframes is not loosely sorted by offset, throw a TypeError and abort these steps.
  415. if (!is_loosely_sorted_by_offset(processed_keyframes))
  416. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Keyframes are not in ascending order based on offset"sv };
  417. // 7. If there exist any keyframe in processed keyframes whose keyframe offset is non-null and less than zero or
  418. // greater than one, throw a TypeError and abort these steps.
  419. for (size_t i = 0; i < processed_keyframes.size(); i++) {
  420. auto const& keyframe = processed_keyframes[i];
  421. if (!keyframe.offset.has_value())
  422. continue;
  423. auto offset = keyframe.offset.value();
  424. if (offset < 0.0 || offset > 1.0)
  425. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Keyframe {} has invalid offset value {}"sv, i, offset)) };
  426. }
  427. // 8. For each frame in processed keyframes, perform the following steps:
  428. for (auto& keyframe : processed_keyframes) {
  429. // 1. For each property-value pair in frame, parse the property value using the syntax specified for that
  430. // property.
  431. //
  432. // If the property value is invalid according to the syntax for the property, discard the property-value pair.
  433. // User agents that provide support for diagnosing errors in content SHOULD produce an appropriate warning
  434. // highlight
  435. BaseKeyframe::ParsedProperties parsed_properties;
  436. for (auto& [property_string, value_string] : keyframe.unparsed_properties()) {
  437. Optional<CSS::PropertyID> property_id;
  438. // Handle some special cases
  439. if (property_string == "cssFloat"sv) {
  440. property_id = CSS::PropertyID::Float;
  441. } else if (property_string == "cssOffset"sv) {
  442. // FIXME: Support CSS offset property
  443. } else if (property_string == "float"sv || property_string == "offset"sv) {
  444. // Ignore these properties
  445. } else if (auto property = CSS::property_id_from_camel_case_string(property_string); property.has_value()) {
  446. property_id = *property;
  447. }
  448. if (!property_id.has_value())
  449. continue;
  450. if (auto style_value = parse_css_value(CSS::Parser::ParsingContext(), value_string, *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(*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(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(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(GC::Ref<KeyframeEffect> a, GC::Ref<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. GC::Ref<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<GC::Ref<KeyframeEffect>> KeyframeEffect::construct_impl(
  542. JS::Realm& realm,
  543. GC::Root<DOM::Element> const& target,
  544. Optional<GC::Root<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<GC::Ref<KeyframeEffect>> KeyframeEffect::construct_impl(JS::Realm& realm, GC::Ref<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<GC::RootVector<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(CSS::CSSStyleValue::SerializationMode::Normal)), 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(CSS::CSSStyleValue::SerializationMode::Normal));
  682. TRY(object->set(JS::PropertyKey { DeprecatedFlyString(CSS::camel_case_string_from_property_id(id)), JS::PropertyKey::StringMayBeNumber::No }, value_string, ShouldThrowExceptions::Yes));
  683. }
  684. m_keyframe_objects.append(object);
  685. }
  686. }
  687. GC::RootVector<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<GC::Root<JS::Object>> const& keyframe_object)
  694. {
  695. m_keyframe_objects.clear();
  696. m_keyframes = TRY(process_a_keyframes_argument(realm(), keyframe_object.has_value() ? GC::Ptr { keyframe_object->ptr() } : GC::Ptr<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_computed_properties()
  758. {
  759. auto target = this->target();
  760. if (!target)
  761. return;
  762. GC::Ptr<CSS::ComputedProperties> style = {};
  763. if (!pseudo_element_type().has_value())
  764. style = target->computed_properties();
  765. else
  766. style = target->pseudo_element_computed_properties(pseudo_element_type().value());
  767. if (!style)
  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. auto invalidation = compute_required_invalidation(animated_properties_before_update, style->animated_property_values());
  773. // Traversal of the subtree is necessary to update the animated properties inherited from the target element.
  774. target->for_each_in_subtree_of_type<DOM::Element>([&](auto& element) {
  775. invalidation |= element.recompute_inherited_style();
  776. return TraversalDecision::Continue;
  777. });
  778. if (!pseudo_element_type().has_value()) {
  779. if (target->layout_node())
  780. target->layout_node()->apply_style(*style);
  781. } else {
  782. auto pseudo_element_node = target->get_pseudo_element_node(pseudo_element_type().value());
  783. if (auto* node_with_style = dynamic_cast<Layout::NodeWithStyle*>(pseudo_element_node.ptr())) {
  784. node_with_style->apply_style(*style);
  785. }
  786. }
  787. if (invalidation.relayout)
  788. document.set_needs_layout();
  789. if (invalidation.rebuild_layout_tree)
  790. document.invalidate_layout_tree();
  791. if (invalidation.repaint)
  792. document.set_needs_to_resolve_paint_only_properties();
  793. if (invalidation.rebuild_stacking_context_tree)
  794. document.invalidate_stacking_context_tree();
  795. }
  796. }