CSSStyleDeclaration.cpp 20 KB

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