KeyframeEffect.cpp 41 KB

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