CSSStyleDeclaration.cpp 20 KB

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