CSSStyleDeclaration.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/CSSStyleDeclarationPrototype.h>
  7. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/CSS/CSSStyleDeclaration.h>
  10. #include <LibWeb/CSS/Parser/Parser.h>
  11. #include <LibWeb/DOM/Document.h>
  12. #include <LibWeb/DOM/Element.h>
  13. #include <LibWeb/Infra/Strings.h>
  14. namespace Web::CSS {
  15. CSSStyleDeclaration::CSSStyleDeclaration(JS::Realm& realm)
  16. : PlatformObject(realm)
  17. {
  18. }
  19. void CSSStyleDeclaration::initialize(JS::Realm& realm)
  20. {
  21. Base::initialize(realm);
  22. set_prototype(&Bindings::ensure_web_prototype<Bindings::CSSStyleDeclarationPrototype>(realm, "CSSStyleDeclaration"));
  23. }
  24. JS::NonnullGCPtr<PropertyOwningCSSStyleDeclaration> PropertyOwningCSSStyleDeclaration::create(JS::Realm& realm, Vector<StyleProperty> properties, HashMap<DeprecatedString, StyleProperty> custom_properties)
  25. {
  26. return realm.heap().allocate<PropertyOwningCSSStyleDeclaration>(realm, realm, move(properties), move(custom_properties));
  27. }
  28. PropertyOwningCSSStyleDeclaration::PropertyOwningCSSStyleDeclaration(JS::Realm& realm, Vector<StyleProperty> properties, HashMap<DeprecatedString, StyleProperty> custom_properties)
  29. : CSSStyleDeclaration(realm)
  30. , m_properties(move(properties))
  31. , m_custom_properties(move(custom_properties))
  32. {
  33. }
  34. DeprecatedString PropertyOwningCSSStyleDeclaration::item(size_t index) const
  35. {
  36. if (index >= m_properties.size())
  37. return {};
  38. return CSS::string_from_property_id(m_properties[index].property_id);
  39. }
  40. JS::NonnullGCPtr<ElementInlineCSSStyleDeclaration> ElementInlineCSSStyleDeclaration::create(DOM::Element& element, Vector<StyleProperty> properties, HashMap<DeprecatedString, StyleProperty> custom_properties)
  41. {
  42. auto& realm = element.realm();
  43. return realm.heap().allocate<ElementInlineCSSStyleDeclaration>(realm, element, move(properties), move(custom_properties));
  44. }
  45. ElementInlineCSSStyleDeclaration::ElementInlineCSSStyleDeclaration(DOM::Element& element, Vector<StyleProperty> properties, HashMap<DeprecatedString, StyleProperty> custom_properties)
  46. : PropertyOwningCSSStyleDeclaration(element.realm(), move(properties), move(custom_properties))
  47. , m_element(element.make_weak_ptr<DOM::Element>())
  48. {
  49. }
  50. void ElementInlineCSSStyleDeclaration::visit_edges(Cell::Visitor& visitor)
  51. {
  52. Base::visit_edges(visitor);
  53. visitor.visit(m_element.ptr());
  54. }
  55. size_t PropertyOwningCSSStyleDeclaration::length() const
  56. {
  57. return m_properties.size();
  58. }
  59. Optional<StyleProperty> PropertyOwningCSSStyleDeclaration::property(PropertyID property_id) const
  60. {
  61. for (auto& property : m_properties) {
  62. if (property.property_id == property_id)
  63. return property;
  64. }
  65. return {};
  66. }
  67. // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-setproperty
  68. WebIDL::ExceptionOr<void> PropertyOwningCSSStyleDeclaration::set_property(PropertyID property_id, StringView value, StringView priority)
  69. {
  70. // 1. If the computed flag is set, then throw a NoModificationAllowedError exception.
  71. // NOTE: This is handled by the virtual override in ResolvedCSSStyleDeclaration.
  72. // FIXME: 2. If property is not a custom property, follow these substeps:
  73. // FIXME: 1. Let property be property converted to ASCII lowercase.
  74. // FIXME: 2. If property is not a case-sensitive match for a supported CSS property, then return.
  75. // NOTE: This must be handled before we've turned the property string into a PropertyID.
  76. // 3. If value is the empty string, invoke removeProperty() with property as argument and return.
  77. if (value.is_empty()) {
  78. MUST(remove_property(property_id));
  79. return {};
  80. }
  81. // 4. If priority is not the empty string and is not an ASCII case-insensitive match for the string "important", then return.
  82. if (!priority.is_empty() && !Infra::is_ascii_case_insensitive_match(priority, "important"sv))
  83. return {};
  84. // 5. Let component value list be the result of parsing value for property property.
  85. auto component_value_list = is<ElementInlineCSSStyleDeclaration>(this)
  86. ? parse_css_value(CSS::Parser::ParsingContext { static_cast<ElementInlineCSSStyleDeclaration&>(*this).element()->document() }, value, property_id)
  87. : parse_css_value(CSS::Parser::ParsingContext { realm() }, value, property_id);
  88. // 6. If component value list is null, then return.
  89. if (!component_value_list)
  90. return {};
  91. // 7. Let updated be false.
  92. bool updated = false;
  93. // FIXME: 8. If property is a shorthand property, then for each longhand property longhand that property maps to, in canonical order, follow these substeps:
  94. // FIXME: 1. Let longhand result be the result of set the CSS declaration longhand with the appropriate value(s) from component value list,
  95. // with the important flag set if priority is not the empty string, and unset otherwise, and with the list of declarations being the declarations.
  96. // FIXME: 2. If longhand result is true, let updated be true.
  97. // 9. Otherwise, let updated be the result of set the CSS declaration property with value component value list,
  98. // with the important flag set if priority is not the empty string, and unset otherwise,
  99. // and with the list of declarations being the declarations.
  100. updated = set_a_css_declaration(property_id, component_value_list.release_nonnull(), !priority.is_empty() ? Important::Yes : Important::No);
  101. // 10. If updated is true, update style attribute for the CSS declaration block.
  102. if (updated)
  103. update_style_attribute();
  104. return {};
  105. }
  106. // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-removeproperty
  107. WebIDL::ExceptionOr<DeprecatedString> PropertyOwningCSSStyleDeclaration::remove_property(PropertyID property_id)
  108. {
  109. // 1. If the computed flag is set, then throw a NoModificationAllowedError exception.
  110. // NOTE: This is handled by the virtual override in ResolvedCSSStyleDeclaration.
  111. // 2. If property is not a custom property, let property be property converted to ASCII lowercase.
  112. // NOTE: We've already converted it to a PropertyID enum value.
  113. // 3. Let value be the return value of invoking getPropertyValue() with property as argument.
  114. // FIXME: The trip through string_from_property_id() here is silly.
  115. auto value = get_property_value(string_from_property_id(property_id));
  116. // 4. Let removed be false.
  117. bool removed = false;
  118. // FIXME: 5. If property is a shorthand property, for each longhand property longhand that property maps to:
  119. // 1. If longhand is not a property name of a CSS declaration in the declarations, continue.
  120. // 2. Remove that CSS declaration and let removed be true.
  121. // 6. Otherwise, if property is a case-sensitive match for a property name of a CSS declaration in the declarations, remove that CSS declaration and let removed be true.
  122. removed = m_properties.remove_first_matching([&](auto& entry) { return entry.property_id == property_id; });
  123. // 7. If removed is true, Update style attribute for the CSS declaration block.
  124. if (removed)
  125. update_style_attribute();
  126. // 8. Return value.
  127. return value;
  128. }
  129. // https://drafts.csswg.org/cssom/#update-style-attribute-for
  130. void ElementInlineCSSStyleDeclaration::update_style_attribute()
  131. {
  132. // 1. Assert: declaration block’s computed flag is unset.
  133. // NOTE: Unnecessary, only relevant for ResolvedCSSStyleDeclaration.
  134. // 2. Let owner node be declaration block’s owner node.
  135. // 3. If owner node is null, then return.
  136. if (!m_element)
  137. return;
  138. // 4. Set declaration block’s updating flag.
  139. m_updating = true;
  140. // 5. Set an attribute value for owner node using "style" and the result of serializing declaration block.
  141. MUST(m_element->set_attribute(HTML::AttributeNames::style, serialized()));
  142. // 6. Unset declaration block’s updating flag.
  143. m_updating = false;
  144. }
  145. // https://drafts.csswg.org/cssom/#set-a-css-declaration
  146. bool PropertyOwningCSSStyleDeclaration::set_a_css_declaration(PropertyID property_id, NonnullRefPtr<StyleValue const> value, Important important)
  147. {
  148. // FIXME: Handle logical property groups.
  149. for (auto& property : m_properties) {
  150. if (property.property_id == property_id) {
  151. if (property.important == important && *property.value == *value)
  152. return false;
  153. property.value = move(value);
  154. property.important = important;
  155. return true;
  156. }
  157. }
  158. m_properties.append(CSS::StyleProperty {
  159. .important = important,
  160. .property_id = property_id,
  161. .value = move(value),
  162. });
  163. return true;
  164. }
  165. DeprecatedString CSSStyleDeclaration::get_property_value(StringView property_name) const
  166. {
  167. auto property_id = property_id_from_string(property_name);
  168. if (!property_id.has_value())
  169. return {};
  170. auto maybe_property = property(property_id.value());
  171. if (!maybe_property.has_value())
  172. return {};
  173. return maybe_property->value->to_string().release_value_but_fixme_should_propagate_errors().to_deprecated_string();
  174. }
  175. // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-getpropertypriority
  176. DeprecatedString CSSStyleDeclaration::get_property_priority(StringView property_name) const
  177. {
  178. auto property_id = property_id_from_string(property_name);
  179. if (!property_id.has_value())
  180. return {};
  181. auto maybe_property = property(property_id.value());
  182. if (!maybe_property.has_value())
  183. return {};
  184. return maybe_property->important == Important::Yes ? "important" : "";
  185. }
  186. WebIDL::ExceptionOr<void> CSSStyleDeclaration::set_property(StringView property_name, StringView css_text, StringView priority)
  187. {
  188. auto property_id = property_id_from_string(property_name);
  189. if (!property_id.has_value())
  190. return {};
  191. return set_property(property_id.value(), css_text, priority);
  192. }
  193. WebIDL::ExceptionOr<DeprecatedString> CSSStyleDeclaration::remove_property(StringView property_name)
  194. {
  195. auto property_id = property_id_from_string(property_name);
  196. if (!property_id.has_value())
  197. return DeprecatedString::empty();
  198. return remove_property(property_id.value());
  199. }
  200. // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-csstext
  201. DeprecatedString CSSStyleDeclaration::css_text() const
  202. {
  203. // 1. If the computed flag is set, then return the empty string.
  204. // NOTE: See ResolvedCSSStyleDeclaration::serialized()
  205. // 2. Return the result of serializing the declarations.
  206. return serialized();
  207. }
  208. // https://www.w3.org/TR/cssom/#serialize-a-css-declaration
  209. static DeprecatedString serialize_a_css_declaration(CSS::PropertyID property, DeprecatedString value, Important important)
  210. {
  211. StringBuilder builder;
  212. // 1. Let s be the empty string.
  213. // 2. Append property to s.
  214. builder.append(string_from_property_id(property));
  215. // 3. Append ": " (U+003A U+0020) to s.
  216. builder.append(": "sv);
  217. // 4. Append value to s.
  218. builder.append(value);
  219. // 5. If the important flag is set, append " !important" (U+0020 U+0021 U+0069 U+006D U+0070 U+006F U+0072 U+0074 U+0061 U+006E U+0074) to s.
  220. if (important == Important::Yes)
  221. builder.append(" !important"sv);
  222. // 6. Append ";" (U+003B) to s.
  223. builder.append(';');
  224. // 7. Return s.
  225. return builder.to_deprecated_string();
  226. }
  227. // https://www.w3.org/TR/cssom/#serialize-a-css-declaration-block
  228. DeprecatedString PropertyOwningCSSStyleDeclaration::serialized() const
  229. {
  230. // 1. Let list be an empty array.
  231. Vector<DeprecatedString> list;
  232. // 2. Let already serialized be an empty array.
  233. HashTable<PropertyID> already_serialized;
  234. // NOTE: The spec treats custom properties the same as any other property, and expects the above loop to handle them.
  235. // However, our implementation separates them from regular properties, so we need to handle them separately here.
  236. // FIXME: Is the relative order of custom properties and regular properties supposed to be preserved?
  237. for (auto& declaration : m_custom_properties) {
  238. // 1. Let property be declaration’s property name.
  239. auto const& property = declaration.key;
  240. // 2. If property is in already serialized, continue with the steps labeled declaration loop.
  241. // NOTE: It is never in already serialized, as there are no shorthands for custom properties.
  242. // 3. If property maps to one or more shorthand properties, let shorthands be an array of those shorthand properties, in preferred order.
  243. // NOTE: There are no shorthands for custom properties.
  244. // 4. Shorthand loop: For each shorthand in shorthands, follow these substeps: ...
  245. // NOTE: There are no shorthands for custom properties.
  246. // 5. Let value be the result of invoking serialize a CSS value of declaration.
  247. auto value = declaration.value.value->to_string().release_value_but_fixme_should_propagate_errors().to_deprecated_string();
  248. // 6. Let serialized declaration be the result of invoking serialize a CSS declaration with property name property, value value,
  249. // and the important flag set if declaration has its important flag set.
  250. // NOTE: We have to inline this here as the actual implementation does not accept custom properties.
  251. DeprecatedString serialized_declaration = [&] {
  252. // https://www.w3.org/TR/cssom/#serialize-a-css-declaration
  253. StringBuilder builder;
  254. // 1. Let s be the empty string.
  255. // 2. Append property to s.
  256. builder.append(property);
  257. // 3. Append ": " (U+003A U+0020) to s.
  258. builder.append(": "sv);
  259. // 4. Append value to s.
  260. builder.append(value);
  261. // 5. If the important flag is set, append " !important" (U+0020 U+0021 U+0069 U+006D U+0070 U+006F U+0072 U+0074 U+0061 U+006E U+0074) to s.
  262. if (declaration.value.important == Important::Yes)
  263. builder.append(" !important"sv);
  264. // 6. Append ";" (U+003B) to s.
  265. builder.append(';');
  266. // 7. Return s.
  267. return builder.to_deprecated_string();
  268. }();
  269. // 7. Append serialized declaration to list.
  270. list.append(move(serialized_declaration));
  271. // 8. Append property to already serialized.
  272. // NOTE: We don't need to do this, as we don't have shorthands for custom properties.
  273. }
  274. // 3. Declaration loop: For each CSS declaration declaration in declaration block’s declarations, follow these substeps:
  275. for (auto& declaration : m_properties) {
  276. // 1. Let property be declaration’s property name.
  277. auto property = declaration.property_id;
  278. // 2. If property is in already serialized, continue with the steps labeled declaration loop.
  279. if (already_serialized.contains(property))
  280. continue;
  281. // FIXME: 3. If property maps to one or more shorthand properties, let shorthands be an array of those shorthand properties, in preferred order.
  282. // FIXME: 4. Shorthand loop: For each shorthand in shorthands, follow these substeps: ...
  283. // 5. Let value be the result of invoking serialize a CSS value of declaration.
  284. auto value = declaration.value->to_string().release_value_but_fixme_should_propagate_errors().to_deprecated_string();
  285. // 6. Let serialized declaration be the result of invoking serialize a CSS declaration with property name property, value value,
  286. // and the important flag set if declaration has its important flag set.
  287. auto serialized_declaration = serialize_a_css_declaration(property, move(value), declaration.important);
  288. // 7. Append serialized declaration to list.
  289. list.append(move(serialized_declaration));
  290. // 8. Append property to already serialized.
  291. already_serialized.set(property);
  292. }
  293. // 4. Return list joined with " " (U+0020).
  294. StringBuilder builder;
  295. builder.join(' ', list);
  296. return builder.to_deprecated_string();
  297. }
  298. static CSS::PropertyID property_id_from_name(StringView name)
  299. {
  300. // FIXME: Perhaps this should go in the code generator.
  301. if (name == "cssFloat"sv)
  302. return CSS::PropertyID::Float;
  303. if (auto property_id = CSS::property_id_from_camel_case_string(name); property_id.has_value())
  304. return property_id.value();
  305. if (auto property_id = CSS::property_id_from_string(name); property_id.has_value())
  306. return property_id.value();
  307. return CSS::PropertyID::Invalid;
  308. }
  309. JS::ThrowCompletionOr<bool> CSSStyleDeclaration::internal_has_property(JS::PropertyKey const& name) const
  310. {
  311. if (!name.is_string())
  312. return Base::internal_has_property(name);
  313. return property_id_from_name(name.to_string()) != CSS::PropertyID::Invalid;
  314. }
  315. JS::ThrowCompletionOr<JS::Value> CSSStyleDeclaration::internal_get(JS::PropertyKey const& name, JS::Value receiver, JS::CacheablePropertyMetadata* cacheable_metadata) const
  316. {
  317. if (!name.is_string())
  318. return Base::internal_get(name, receiver, cacheable_metadata);
  319. auto property_id = property_id_from_name(name.to_string());
  320. if (property_id == CSS::PropertyID::Invalid)
  321. return Base::internal_get(name, receiver, cacheable_metadata);
  322. if (auto maybe_property = property(property_id); maybe_property.has_value())
  323. return { JS::PrimitiveString::create(vm(), maybe_property->value->to_string().release_value_but_fixme_should_propagate_errors().to_deprecated_string()) };
  324. return { JS::PrimitiveString::create(vm(), String {}) };
  325. }
  326. JS::ThrowCompletionOr<bool> CSSStyleDeclaration::internal_set(JS::PropertyKey const& name, JS::Value value, JS::Value receiver)
  327. {
  328. auto& vm = this->vm();
  329. if (!name.is_string())
  330. return Base::internal_set(name, value, receiver);
  331. auto property_id = property_id_from_name(name.to_string());
  332. if (property_id == CSS::PropertyID::Invalid)
  333. return Base::internal_set(name, value, receiver);
  334. auto css_text = TRY(value.to_deprecated_string(vm));
  335. TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return set_property(property_id, css_text); }));
  336. return true;
  337. }
  338. WebIDL::ExceptionOr<void> PropertyOwningCSSStyleDeclaration::set_css_text(StringView css_text)
  339. {
  340. dbgln("(STUBBED) PropertyOwningCSSStyleDeclaration::set_css_text(css_text='{}')", css_text);
  341. return {};
  342. }
  343. void PropertyOwningCSSStyleDeclaration::empty_the_declarations()
  344. {
  345. m_properties.clear();
  346. m_custom_properties.clear();
  347. }
  348. void PropertyOwningCSSStyleDeclaration::set_the_declarations(Vector<StyleProperty> properties, HashMap<DeprecatedString, StyleProperty> custom_properties)
  349. {
  350. m_properties = move(properties);
  351. m_custom_properties = move(custom_properties);
  352. }
  353. // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-csstext
  354. WebIDL::ExceptionOr<void> ElementInlineCSSStyleDeclaration::set_css_text(StringView css_text)
  355. {
  356. // FIXME: What do we do if the element is null?
  357. if (!m_element) {
  358. dbgln("FIXME: Returning from ElementInlineCSSStyleDeclaration::set_css_text as m_element is null.");
  359. return {};
  360. }
  361. // 1. If the computed flag is set, then throw a NoModificationAllowedError exception.
  362. // NOTE: See ResolvedCSSStyleDeclaration.
  363. // 2. Empty the declarations.
  364. empty_the_declarations();
  365. // 3. Parse the given value and, if the return value is not the empty list, insert the items in the list into the declarations, in specified order.
  366. auto style = parse_css_style_attribute(CSS::Parser::ParsingContext(m_element->document()), css_text, *m_element.ptr());
  367. auto custom_properties = TRY_OR_THROW_OOM(vm(), style->custom_properties().clone());
  368. set_the_declarations(style->properties(), move(custom_properties));
  369. // 4. Update style attribute for the CSS declaration block.
  370. update_style_attribute();
  371. return {};
  372. }
  373. }