CSSStyleDeclaration.cpp 20 KB

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