KeyframeEffect.cpp 33 KB

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