KeyframeEffect.cpp 45 KB

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