CSSStyleDeclaration.cpp 22 KB

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