KeyframeEffect.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. JS::NonnullGCPtr<KeyframeEffect> KeyframeEffect::create(JS::Realm& realm)
  164. {
  165. return realm.heap().allocate<KeyframeEffect>(realm, realm);
  166. }
  167. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect
  168. WebIDL::ExceptionOr<JS::NonnullGCPtr<KeyframeEffect>> KeyframeEffect::construct_impl(
  169. JS::Realm& realm,
  170. JS::Handle<DOM::Element> const& target,
  171. Optional<JS::Handle<JS::Object>> const& keyframes,
  172. Variant<double, KeyframeEffectOptions> options)
  173. {
  174. auto& vm = realm.vm();
  175. // 1. Create a new KeyframeEffect object, effect.
  176. auto effect = vm.heap().allocate<KeyframeEffect>(realm, realm);
  177. // 2. Set the target element of effect to target.
  178. effect->set_target(target);
  179. // 3. Set the target pseudo-selector to the result corresponding to the first matching condition from below.
  180. // If options is a KeyframeEffectOptions object with a pseudoElement property,
  181. if (options.has<KeyframeEffectOptions>()) {
  182. // Set the target pseudo-selector to the value of the pseudoElement property.
  183. //
  184. // When assigning this property, the error-handling defined for the pseudoElement setter on the interface is
  185. // applied. If the setter requires an exception to be thrown, this procedure must throw the same exception and
  186. // abort all further steps.
  187. effect->set_pseudo_element(options.get<KeyframeEffectOptions>().pseudo_element);
  188. }
  189. // Otherwise,
  190. else {
  191. // Set the target pseudo-selector to null.
  192. // Note: This is the default when constructed
  193. }
  194. // 4. Let timing input be the result corresponding to the first matching condition from below.
  195. KeyframeEffectOptions timing_input;
  196. // If options is a KeyframeEffectOptions object,
  197. if (options.has<KeyframeEffectOptions>()) {
  198. // Let timing input be options.
  199. timing_input = options.get<KeyframeEffectOptions>();
  200. }
  201. // Otherwise (if options is a double),
  202. else {
  203. // Let timing input be a new EffectTiming object with all members set to their default values and duration set
  204. // to options.
  205. timing_input.duration = options.get<double>();
  206. }
  207. // 5. Call the procedure to update the timing properties of an animation effect of effect from timing input.
  208. // If that procedure causes an exception to be thrown, propagate the exception and abort this procedure.
  209. TRY(effect->update_timing(timing_input.to_optional_effect_timing()));
  210. // 6. If options is a KeyframeEffectOptions object, assign the composite property of effect to the corresponding
  211. // value from options.
  212. //
  213. // When assigning this property, the error-handling defined for the corresponding setter on the KeyframeEffect
  214. // interface is applied. If the setter requires an exception to be thrown for the value specified by options,
  215. // this procedure must throw the same exception and abort all further steps.
  216. if (options.has<KeyframeEffectOptions>())
  217. effect->set_composite(options.get<KeyframeEffectOptions>().composite);
  218. // 7. Initialize the set of keyframes by performing the procedure defined for setKeyframes() passing keyframes as
  219. // the input.
  220. TRY(effect->set_keyframes(keyframes));
  221. return effect;
  222. }
  223. WebIDL::ExceptionOr<JS::NonnullGCPtr<KeyframeEffect>> KeyframeEffect::construct_impl(JS::Realm& realm, JS::NonnullGCPtr<KeyframeEffect> source)
  224. {
  225. auto& vm = realm.vm();
  226. // 1. Create a new KeyframeEffect object, effect.
  227. auto effect = vm.heap().allocate<KeyframeEffect>(realm, realm);
  228. // 2. Set the following properties of effect using the corresponding values of source:
  229. // - effect target,
  230. effect->m_target_element = source->target();
  231. // FIXME:
  232. // - keyframes,
  233. // - composite operation, and
  234. effect->set_composite(source->composite());
  235. // - all specified timing properties:
  236. // - start delay,
  237. effect->m_start_delay = source->m_start_delay;
  238. // - end delay,
  239. effect->m_end_delay = source->m_end_delay;
  240. // - fill mode,
  241. effect->m_fill_mode = source->m_fill_mode;
  242. // - iteration start,
  243. effect->m_iteration_start = source->m_iteration_start;
  244. // - iteration count,
  245. effect->m_iteration_count = source->m_iteration_count;
  246. // - iteration duration,
  247. effect->m_iteration_duration = source->m_iteration_duration;
  248. // - playback direction, and
  249. effect->m_playback_direction = source->m_playback_direction;
  250. // - timing function.
  251. effect->m_easing_function = source->m_easing_function;
  252. return effect;
  253. }
  254. void KeyframeEffect::set_pseudo_element(Optional<String> pseudo_element)
  255. {
  256. // On setting, sets the target pseudo-selector of the animation effect to the provided value after applying the
  257. // following exceptions:
  258. // FIXME:
  259. // - If the provided value is not null and is an invalid <pseudo-element-selector>, the user agent must throw a
  260. // DOMException with error name SyntaxError and leave the target pseudo-selector of this animation effect
  261. // unchanged.
  262. // - If one of the legacy Selectors Level 2 single-colon selectors (':before', ':after', ':first-letter', or
  263. // ':first-line') is specified, the target pseudo-selector must be set to the equivalent two-colon selector
  264. // (e.g. '::before').
  265. if (pseudo_element.has_value()) {
  266. auto value = pseudo_element.value();
  267. if (value == ":before" || value == ":after" || value == ":first-letter" || value == ":first-line") {
  268. m_target_pseudo_selector = MUST(String::formatted(":{}", value));
  269. return;
  270. }
  271. }
  272. m_target_pseudo_selector = pseudo_element;
  273. }
  274. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-getkeyframes
  275. WebIDL::ExceptionOr<Vector<JS::Object*>> KeyframeEffect::get_keyframes() const
  276. {
  277. // FIXME: Implement this
  278. return Vector<JS::Object*> {};
  279. }
  280. // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-setkeyframes
  281. WebIDL::ExceptionOr<void> KeyframeEffect::set_keyframes(Optional<JS::Handle<JS::Object>> const&)
  282. {
  283. // FIXME: Implement this
  284. return {};
  285. }
  286. KeyframeEffect::KeyframeEffect(JS::Realm& realm)
  287. : AnimationEffect(realm)
  288. {
  289. }
  290. void KeyframeEffect::initialize(JS::Realm& realm)
  291. {
  292. Base::initialize(realm);
  293. set_prototype(&Bindings::ensure_web_prototype<Bindings::KeyframeEffectPrototype>(realm, "KeyframeEffect"_fly_string));
  294. }
  295. void KeyframeEffect::visit_edges(Cell::Visitor& visitor)
  296. {
  297. Base::visit_edges(visitor);
  298. visitor.visit(m_target_element);
  299. }
  300. }