KeyframeEffect.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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/WebIDL/ExceptionOr.h>
  10. namespace Web::Animations {
  11. JS_DEFINE_ALLOCATOR(KeyframeEffect);
  12. template<typename T>
  13. 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)
  14. {
  15. auto& vm = realm.vm();
  16. if (TRY(value.is_array(vm))) {
  17. Vector<T> offsets;
  18. auto iterator = TRY(JS::get_iterator(vm, value, JS::IteratorHint::Sync));
  19. auto values = TRY(JS::iterator_to_list(vm, iterator));
  20. for (auto const& element : values) {
  21. if (element.is_undefined()) {
  22. offsets.append({});
  23. } else {
  24. offsets.append(TRY(value_converter(element)));
  25. }
  26. }
  27. return offsets;
  28. }
  29. return TRY(value_converter(value));
  30. }
  31. enum AllowLists {
  32. Yes,
  33. No,
  34. };
  35. template<AllowLists AL>
  36. using KeyframeType = Conditional<AL == AllowLists::Yes, BasePropertyIndexedKeyframe, BaseKeyframe>;
  37. // https://www.w3.org/TR/web-animations-1/#process-a-keyframe-like-object
  38. template<AllowLists AL>
  39. static WebIDL::ExceptionOr<KeyframeType<AL>> process_a_keyframe_like_object(JS::Realm& realm, JS::GCPtr<JS::Object> keyframe_input)
  40. {
  41. auto& vm = realm.vm();
  42. Function<WebIDL::ExceptionOr<Optional<double>>(JS::Value)> to_nullable_double = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Optional<double>> {
  43. if (value.is_undefined())
  44. return Optional<double> {};
  45. return TRY(value.to_double(vm));
  46. };
  47. Function<WebIDL::ExceptionOr<String>(JS::Value)> to_string = [&vm](JS::Value value) -> WebIDL::ExceptionOr<String> {
  48. return TRY(value.to_string(vm));
  49. };
  50. Function<WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto>(JS::Value)> to_composite_operation = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto> {
  51. if (value.is_undefined())
  52. return Bindings::CompositeOperationOrAuto::Auto;
  53. auto string_value = TRY(value.to_string(vm));
  54. if (string_value == "replace")
  55. return Bindings::CompositeOperationOrAuto::Replace;
  56. if (string_value == "add")
  57. return Bindings::CompositeOperationOrAuto::Add;
  58. if (string_value == "accumulate")
  59. return Bindings::CompositeOperationOrAuto::Accumulate;
  60. if (string_value == "auto")
  61. return Bindings::CompositeOperationOrAuto::Auto;
  62. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid composite value"sv };
  63. };
  64. // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript
  65. // value, and the dictionary type depending on the value of the allow lists flag as follows:
  66. //
  67. // -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.
  68. // -> Otherwise, use the following dictionary type: <BaseKeyframe>.
  69. //
  70. // Store the result of this procedure as keyframe output.
  71. KeyframeType<AL> keyframe_output;
  72. auto offset = TRY(keyframe_input->get("offset"));
  73. auto easing = TRY(keyframe_input->get("easing"));
  74. if (easing.is_undefined())
  75. easing = JS::PrimitiveString::create(vm, "linear"_string);
  76. auto composite = TRY(keyframe_input->get("composite"));
  77. if (composite.is_undefined())
  78. composite = JS::PrimitiveString::create(vm, "auto"_string);
  79. if constexpr (AL == AllowLists::Yes) {
  80. keyframe_output.offset = TRY(convert_value_to_maybe_list(realm, offset, to_nullable_double));
  81. keyframe_output.composite = TRY(convert_value_to_maybe_list(realm, composite, to_composite_operation));
  82. auto easing_maybe_list = TRY(convert_value_to_maybe_list(realm, easing, to_string));
  83. easing_maybe_list.visit(
  84. [&](String const& value) {
  85. keyframe_output.easing = EasingValue { value };
  86. },
  87. [&](Vector<String> const& values) {
  88. Vector<EasingValue> easing_values;
  89. for (auto& easing_value : values)
  90. easing_values.append(easing_value);
  91. keyframe_output.easing = move(easing_values);
  92. });
  93. } else {
  94. keyframe_output.offset = TRY(to_nullable_double(offset));
  95. keyframe_output.easing = TRY(to_string(easing));
  96. keyframe_output.composite = TRY(to_composite_operation(composite));
  97. }
  98. // 2. Build up a list of animatable properties as follows:
  99. //
  100. // 1. Let animatable properties be a list of property names (including shorthand properties that have longhand
  101. // sub-properties that are animatable) that can be animated by the implementation.
  102. // 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the
  103. // animation property name to IDL attribute name algorithm.
  104. // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the
  105. // object.
  106. // 4. Make up a new list animation properties that consists of all of the properties that are in both input
  107. // properties and animatable properties, or which are in input properties and conform to the
  108. // <custom-property-name> production.
  109. auto input_properties = TRY(keyframe_input->internal_own_property_keys());
  110. Vector<String> animation_properties;
  111. for (auto const& input_property : input_properties) {
  112. if (!input_property.is_string())
  113. continue;
  114. auto name = input_property.as_string().utf8_string();
  115. if (auto property = CSS::property_id_from_camel_case_string(name); property.has_value()) {
  116. if (CSS::is_animatable_property(property.value()))
  117. animation_properties.append(name);
  118. }
  119. }
  120. // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name.
  121. quick_sort(animation_properties);
  122. // 6. For each property name in animation properties,
  123. for (auto const& property_name : animation_properties) {
  124. // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name
  125. // as the property key and keyframe input as the receiver.
  126. // 2. Check the completion record of raw value.
  127. auto raw_value = TRY(keyframe_input->get(ByteString { property_name }));
  128. using PropertyValuesType = Conditional<AL == AllowLists::Yes, Vector<String>, String>;
  129. PropertyValuesType property_values;
  130. // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:
  131. // -> If allow lists is true,
  132. if constexpr (AL == AllowLists::Yes) {
  133. // Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>)
  134. // using the procedures defined for converting an ECMAScript value to an IDL value [WEBIDL].
  135. auto intermediate_property_values = TRY(convert_value_to_maybe_list(realm, raw_value, to_string));
  136. // If property values is a single DOMString, replace property values with a sequence of DOMStrings with the
  137. // original value of property values as the only element.
  138. if (intermediate_property_values.has<String>())
  139. property_values = Vector { intermediate_property_values.get<String>() };
  140. else
  141. property_values = intermediate_property_values.get<Vector<String>>();
  142. }
  143. // -> Otherwise,
  144. else {
  145. // Let property values be the result of converting raw value to a DOMString using the procedure for
  146. // converting an ECMAScript value to a DOMString [WEBIDL].
  147. property_values = TRY(raw_value.to_string(vm));
  148. }
  149. // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation
  150. // property name algorithm to property name.
  151. // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL
  152. // attribute name) in the steps above.
  153. // 5. Add a property to keyframe output with normalized property name as the property name, and property values
  154. // as the property value.
  155. if constexpr (AL == AllowLists::Yes) {
  156. keyframe_output.properties.set(property_name, property_values);
  157. } else {
  158. keyframe_output.unparsed_properties().set(property_name, property_values);
  159. }
  160. }
  161. return keyframe_output;
  162. }
  163. // https://www.w3.org/TR/web-animations-1/#compute-missing-keyframe-offsets
  164. [[maybe_unused]] static void compute_missing_keyframe_offsets(Vector<BaseKeyframe>& keyframes)
  165. {
  166. // 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe
  167. // offset value.
  168. for (auto& keyframe : keyframes)
  169. keyframe.computed_offset = keyframe.offset;
  170. // 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in
  171. // keyframes is null, set the computed keyframe offset of the first keyframe to 0.
  172. if (keyframes.size() > 1 && !keyframes[0].computed_offset.has_value())
  173. keyframes[0].computed_offset = 0.0;
  174. // 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset
  175. // to 1.
  176. if (!keyframes.is_empty() && !keyframes.last().computed_offset.has_value())
  177. keyframes.last().computed_offset = 1.0;
  178. // 4. For each pair of keyframes A and B where:
  179. // - A appears before B in keyframes, and
  180. // - A and B have a computed keyframe offset that is not null, and
  181. // - all keyframes between A and B have a null computed keyframe offset,
  182. auto find_next_index_of_keyframe_with_computed_offset = [&](size_t starting_index) -> Optional<size_t> {
  183. for (size_t index = starting_index; index < keyframes.size(); index++) {
  184. if (keyframes[index].computed_offset.has_value())
  185. return index;
  186. }
  187. return {};
  188. };
  189. auto maybe_index_a = find_next_index_of_keyframe_with_computed_offset(0);
  190. if (!maybe_index_a.has_value())
  191. return;
  192. auto index_a = maybe_index_a.value();
  193. auto maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_a + 1);
  194. while (maybe_index_b.has_value()) {
  195. auto index_b = maybe_index_b.value();
  196. // calculate the computed keyframe offset of each keyframe between A and B as follows:
  197. for (size_t keyframe_index = index_a + 1; keyframe_index < index_b; keyframe_index++) {
  198. // 1. Let offsetk be the computed keyframe offset of a keyframe k.
  199. auto offset_a = keyframes[index_a].computed_offset.value();
  200. auto offset_b = keyframes[index_b].computed_offset.value();
  201. // 2. Let n be the number of keyframes between and including A and B minus 1.
  202. auto n = static_cast<double>(index_b - index_a);
  203. // 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the
  204. // first keyframe after A has an index of 1.
  205. auto index = static_cast<double>(keyframe_index - index_a);
  206. // 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.
  207. keyframes[keyframe_index].computed_offset = (offset_a + (offset_b - offset_a)) * index / n;
  208. }
  209. index_a = index_b;
  210. maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_b + 1);
  211. }
  212. }
  213. JS::NonnullGCPtr<KeyframeEffect> KeyframeEffect::create(JS::Realm& realm)
  214. {
  215. return realm.heap().allocate<KeyframeEffect>(realm, realm);
  216. }
  217. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect
  218. WebIDL::ExceptionOr<JS::NonnullGCPtr<KeyframeEffect>> KeyframeEffect::construct_impl(
  219. JS::Realm& realm,
  220. JS::Handle<DOM::Element> const& target,
  221. Optional<JS::Handle<JS::Object>> const& keyframes,
  222. Variant<double, KeyframeEffectOptions> options)
  223. {
  224. auto& vm = realm.vm();
  225. // 1. Create a new KeyframeEffect object, effect.
  226. auto effect = vm.heap().allocate<KeyframeEffect>(realm, realm);
  227. // 2. Set the target element of effect to target.
  228. effect->set_target(target);
  229. // 3. Set the target pseudo-selector to the result corresponding to the first matching condition from below.
  230. // If options is a KeyframeEffectOptions object with a pseudoElement property,
  231. if (options.has<KeyframeEffectOptions>()) {
  232. // Set the target pseudo-selector to the value of the pseudoElement property.
  233. //
  234. // When assigning this property, the error-handling defined for the pseudoElement setter on the interface is
  235. // applied. If the setter requires an exception to be thrown, this procedure must throw the same exception and
  236. // abort all further steps.
  237. effect->set_pseudo_element(options.get<KeyframeEffectOptions>().pseudo_element);
  238. }
  239. // Otherwise,
  240. else {
  241. // Set the target pseudo-selector to null.
  242. // Note: This is the default when constructed
  243. }
  244. // 4. Let timing input be the result corresponding to the first matching condition from below.
  245. KeyframeEffectOptions timing_input;
  246. // If options is a KeyframeEffectOptions object,
  247. if (options.has<KeyframeEffectOptions>()) {
  248. // Let timing input be options.
  249. timing_input = options.get<KeyframeEffectOptions>();
  250. }
  251. // Otherwise (if options is a double),
  252. else {
  253. // Let timing input be a new EffectTiming object with all members set to their default values and duration set
  254. // to options.
  255. timing_input.duration = options.get<double>();
  256. }
  257. // 5. Call the procedure to update the timing properties of an animation effect of effect from timing input.
  258. // If that procedure causes an exception to be thrown, propagate the exception and abort this procedure.
  259. TRY(effect->update_timing(timing_input.to_optional_effect_timing()));
  260. // 6. If options is a KeyframeEffectOptions object, assign the composite property of effect to the corresponding
  261. // value from options.
  262. //
  263. // When assigning this property, the error-handling defined for the corresponding setter on the KeyframeEffect
  264. // interface is applied. If the setter requires an exception to be thrown for the value specified by options,
  265. // this procedure must throw the same exception and abort all further steps.
  266. if (options.has<KeyframeEffectOptions>())
  267. effect->set_composite(options.get<KeyframeEffectOptions>().composite);
  268. // 7. Initialize the set of keyframes by performing the procedure defined for setKeyframes() passing keyframes as
  269. // the input.
  270. TRY(effect->set_keyframes(keyframes));
  271. return effect;
  272. }
  273. WebIDL::ExceptionOr<JS::NonnullGCPtr<KeyframeEffect>> KeyframeEffect::construct_impl(JS::Realm& realm, JS::NonnullGCPtr<KeyframeEffect> source)
  274. {
  275. auto& vm = realm.vm();
  276. // 1. Create a new KeyframeEffect object, effect.
  277. auto effect = vm.heap().allocate<KeyframeEffect>(realm, realm);
  278. // 2. Set the following properties of effect using the corresponding values of source:
  279. // - effect target,
  280. effect->m_target_element = source->target();
  281. // FIXME:
  282. // - keyframes,
  283. // - composite operation, and
  284. effect->set_composite(source->composite());
  285. // - all specified timing properties:
  286. // - start delay,
  287. effect->m_start_delay = source->m_start_delay;
  288. // - end delay,
  289. effect->m_end_delay = source->m_end_delay;
  290. // - fill mode,
  291. effect->m_fill_mode = source->m_fill_mode;
  292. // - iteration start,
  293. effect->m_iteration_start = source->m_iteration_start;
  294. // - iteration count,
  295. effect->m_iteration_count = source->m_iteration_count;
  296. // - iteration duration,
  297. effect->m_iteration_duration = source->m_iteration_duration;
  298. // - playback direction, and
  299. effect->m_playback_direction = source->m_playback_direction;
  300. // - timing function.
  301. effect->m_easing_function = source->m_easing_function;
  302. return effect;
  303. }
  304. void KeyframeEffect::set_pseudo_element(Optional<String> pseudo_element)
  305. {
  306. // On setting, sets the target pseudo-selector of the animation effect to the provided value after applying the
  307. // following exceptions:
  308. // FIXME:
  309. // - If the provided value is not null and is an invalid <pseudo-element-selector>, the user agent must throw a
  310. // DOMException with error name SyntaxError and leave the target pseudo-selector of this animation effect
  311. // unchanged.
  312. // - If one of the legacy Selectors Level 2 single-colon selectors (':before', ':after', ':first-letter', or
  313. // ':first-line') is specified, the target pseudo-selector must be set to the equivalent two-colon selector
  314. // (e.g. '::before').
  315. if (pseudo_element.has_value()) {
  316. auto value = pseudo_element.value();
  317. if (value == ":before" || value == ":after" || value == ":first-letter" || value == ":first-line") {
  318. m_target_pseudo_selector = MUST(String::formatted(":{}", value));
  319. return;
  320. }
  321. }
  322. m_target_pseudo_selector = pseudo_element;
  323. }
  324. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-getkeyframes
  325. WebIDL::ExceptionOr<Vector<JS::Object*>> KeyframeEffect::get_keyframes() const
  326. {
  327. // FIXME: Implement this
  328. return Vector<JS::Object*> {};
  329. }
  330. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-setkeyframes
  331. WebIDL::ExceptionOr<void> KeyframeEffect::set_keyframes(Optional<JS::Handle<JS::Object>> const&)
  332. {
  333. // FIXME: Implement this
  334. return {};
  335. }
  336. KeyframeEffect::KeyframeEffect(JS::Realm& realm)
  337. : AnimationEffect(realm)
  338. {
  339. }
  340. void KeyframeEffect::initialize(JS::Realm& realm)
  341. {
  342. Base::initialize(realm);
  343. set_prototype(&Bindings::ensure_web_prototype<Bindings::KeyframeEffectPrototype>(realm, "KeyframeEffect"_fly_string));
  344. }
  345. void KeyframeEffect::visit_edges(Cell::Visitor& visitor)
  346. {
  347. Base::visit_edges(visitor);
  348. visitor.visit(m_target_element);
  349. }
  350. }