CSSStyleSheet.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * Copyright (c) 2019-2022, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2022-2024, Sam Atkins <sam@ladybird.org>
  4. * Copyright (c) 2024, Tim Ledbetter <timledbetter@gmail.com>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibWeb/Bindings/CSSStyleSheetPrototype.h>
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/CSS/CSSImportRule.h>
  11. #include <LibWeb/CSS/CSSStyleSheet.h>
  12. #include <LibWeb/CSS/Parser/Parser.h>
  13. #include <LibWeb/CSS/StyleComputer.h>
  14. #include <LibWeb/CSS/StyleSheetList.h>
  15. #include <LibWeb/DOM/Document.h>
  16. #include <LibWeb/HTML/Window.h>
  17. #include <LibWeb/Platform/EventLoopPlugin.h>
  18. #include <LibWeb/WebIDL/ExceptionOr.h>
  19. namespace Web::CSS {
  20. JS_DEFINE_ALLOCATOR(CSSStyleSheet);
  21. JS::NonnullGCPtr<CSSStyleSheet> CSSStyleSheet::create(JS::Realm& realm, CSSRuleList& rules, MediaList& media, Optional<URL::URL> location)
  22. {
  23. return realm.heap().allocate<CSSStyleSheet>(realm, realm, rules, media, move(location));
  24. }
  25. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssstylesheet
  26. WebIDL::ExceptionOr<JS::NonnullGCPtr<CSSStyleSheet>> CSSStyleSheet::construct_impl(JS::Realm& realm, Optional<CSSStyleSheetInit> const& options)
  27. {
  28. // 1. Construct a new CSSStyleSheet object sheet.
  29. auto sheet = create(realm, CSSRuleList::create_empty(realm), CSS::MediaList::create(realm, {}), {});
  30. // 2. Set sheet’s location to the base URL of the associated Document for the current global object.
  31. auto associated_document = verify_cast<HTML::Window>(HTML::current_global_object()).document();
  32. sheet->set_location(MUST(associated_document->base_url().to_string()));
  33. // 3. Set sheet’s stylesheet base URL to the baseURL attribute value from options.
  34. if (options.has_value() && options->base_url.has_value()) {
  35. Optional<URL::URL> sheet_location_url;
  36. if (sheet->location().has_value())
  37. sheet_location_url = sheet->location().release_value();
  38. // AD-HOC: This isn't explicitly mentioned in the specification, but multiple modern browsers do this.
  39. URL::URL url = sheet->location().has_value() ? sheet_location_url->complete_url(options->base_url.value()) : options->base_url.value();
  40. if (!url.is_valid())
  41. return WebIDL::NotAllowedError::create(realm, "Constructed style sheets must have a valid base URL"_string);
  42. sheet->set_base_url(url);
  43. }
  44. // 4. Set sheet’s parent CSS style sheet to null.
  45. sheet->set_parent_css_style_sheet(nullptr);
  46. // 5. Set sheet’s owner node to null.
  47. sheet->set_owner_node(nullptr);
  48. // 6. Set sheet’s owner CSS rule to null.
  49. sheet->set_owner_css_rule(nullptr);
  50. // 7. Set sheet’s title to the the empty string.
  51. sheet->set_title(String {});
  52. // 8. Unset sheet’s alternate flag.
  53. sheet->set_alternate(false);
  54. // 9. Set sheet’s origin-clean flag.
  55. sheet->set_origin_clean(true);
  56. // 10. Set sheet’s constructed flag.
  57. sheet->set_constructed(true);
  58. // 11. Set sheet’s Constructor document to the associated Document for the current global object.
  59. sheet->set_constructor_document(associated_document);
  60. // 12. If the media attribute of options is a string, create a MediaList object from the string and assign it as sheet’s media.
  61. // Otherwise, serialize a media query list from the attribute and then create a MediaList object from the resulting string and set it as sheet’s media.
  62. if (options.has_value()) {
  63. if (options->media.has<String>()) {
  64. sheet->set_media(options->media.get<String>());
  65. } else {
  66. sheet->m_media = *options->media.get<JS::Handle<MediaList>>();
  67. }
  68. }
  69. // 13. If the disabled attribute of options is true, set sheet’s disabled flag.
  70. if (options.has_value() && options->disabled)
  71. sheet->set_disabled(true);
  72. // 14. Return sheet
  73. return sheet;
  74. }
  75. CSSStyleSheet::CSSStyleSheet(JS::Realm& realm, CSSRuleList& rules, MediaList& media, Optional<URL::URL> location)
  76. : StyleSheet(realm, media)
  77. , m_rules(&rules)
  78. {
  79. if (location.has_value())
  80. set_location(MUST(location->to_string()));
  81. for (auto& rule : *m_rules)
  82. rule->set_parent_style_sheet(this);
  83. recalculate_rule_caches();
  84. m_rules->on_change = [this]() {
  85. recalculate_rule_caches();
  86. };
  87. }
  88. void CSSStyleSheet::initialize(JS::Realm& realm)
  89. {
  90. Base::initialize(realm);
  91. WEB_SET_PROTOTYPE_FOR_INTERFACE(CSSStyleSheet);
  92. }
  93. void CSSStyleSheet::visit_edges(Cell::Visitor& visitor)
  94. {
  95. Base::visit_edges(visitor);
  96. visitor.visit(m_style_sheet_list);
  97. visitor.visit(m_rules);
  98. visitor.visit(m_owner_css_rule);
  99. visitor.visit(m_default_namespace_rule);
  100. visitor.visit(m_constructor_document);
  101. visitor.visit(m_namespace_rules);
  102. visitor.visit(m_import_rules);
  103. }
  104. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-insertrule
  105. WebIDL::ExceptionOr<unsigned> CSSStyleSheet::insert_rule(StringView rule, unsigned index)
  106. {
  107. // FIXME: 1. If the origin-clean flag is unset, throw a SecurityError exception.
  108. // If the disallow modification flag is set, throw a NotAllowedError DOMException.
  109. if (disallow_modification())
  110. return WebIDL::NotAllowedError::create(realm(), "Can't call insert_rule() on non-modifiable stylesheets."_string);
  111. // 3. Let parsed rule be the return value of invoking parse a rule with rule.
  112. auto context = m_style_sheet_list ? CSS::Parser::ParsingContext { m_style_sheet_list->document() } : CSS::Parser::ParsingContext { realm() };
  113. auto parsed_rule = parse_css_rule(context, rule);
  114. // 4. If parsed rule is a syntax error, return parsed rule.
  115. if (!parsed_rule)
  116. return WebIDL::SyntaxError::create(realm(), "Unable to parse CSS rule."_string);
  117. // 5. If parsed rule is an @import rule, and the constructed flag is set, throw a SyntaxError DOMException.
  118. if (constructed() && parsed_rule->type() == CSSRule::Type::Import)
  119. return WebIDL::SyntaxError::create(realm(), "Can't insert @import rules into a constructed stylesheet."_string);
  120. // 6. Return the result of invoking insert a CSS rule rule in the CSS rules at index.
  121. auto result = m_rules->insert_a_css_rule(parsed_rule, index);
  122. if (!result.is_exception()) {
  123. // NOTE: The spec doesn't say where to set the parent style sheet, so we'll do it here.
  124. parsed_rule->set_parent_style_sheet(this);
  125. if (m_style_sheet_list) {
  126. m_style_sheet_list->document().style_computer().invalidate_rule_cache();
  127. m_style_sheet_list->document_or_shadow_root().invalidate_style(DOM::StyleInvalidationReason::StyleSheetInsertRule);
  128. }
  129. }
  130. return result;
  131. }
  132. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-deleterule
  133. WebIDL::ExceptionOr<void> CSSStyleSheet::delete_rule(unsigned index)
  134. {
  135. // FIXME: 1. If the origin-clean flag is unset, throw a SecurityError exception.
  136. // 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
  137. if (disallow_modification())
  138. return WebIDL::NotAllowedError::create(realm(), "Can't call delete_rule() on non-modifiable stylesheets."_string);
  139. // 3. Remove a CSS rule in the CSS rules at index.
  140. auto result = m_rules->remove_a_css_rule(index);
  141. if (!result.is_exception()) {
  142. if (m_style_sheet_list) {
  143. m_style_sheet_list->document().style_computer().invalidate_rule_cache();
  144. m_style_sheet_list->document_or_shadow_root().invalidate_style(DOM::StyleInvalidationReason::StyleSheetDeleteRule);
  145. }
  146. }
  147. return result;
  148. }
  149. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-replace
  150. JS::NonnullGCPtr<JS::Promise> CSSStyleSheet::replace(String text)
  151. {
  152. // 1. Let promise be a promise
  153. auto promise = JS::Promise::create(realm());
  154. // 2. If the constructed flag is not set, or the disallow modification flag is set, reject promise with a NotAllowedError DOMException and return promise.
  155. if (!constructed()) {
  156. promise->reject(WebIDL::NotAllowedError::create(realm(), "Can't call replace() on non-constructed stylesheets"_string));
  157. return promise;
  158. }
  159. if (disallow_modification()) {
  160. promise->reject(WebIDL::NotAllowedError::create(realm(), "Can't call replace() on non-modifiable stylesheets"_string));
  161. return promise;
  162. }
  163. // 3. Set the disallow modification flag.
  164. set_disallow_modification(true);
  165. // 4. In parallel, do these steps:
  166. Platform::EventLoopPlugin::the().deferred_invoke([this, text = move(text), promise] {
  167. // 1. Let rules be the result of running parse a stylesheet’s contents from text.
  168. auto context = m_style_sheet_list ? CSS::Parser::ParsingContext { m_style_sheet_list->document() } : CSS::Parser::ParsingContext { realm() };
  169. auto* parsed_stylesheet = parse_css_stylesheet(context, text);
  170. auto& rules = parsed_stylesheet->rules();
  171. // 2. If rules contains one or more @import rules, remove those rules from rules.
  172. JS::MarkedVector<JS::NonnullGCPtr<CSSRule>> rules_without_import(realm().heap());
  173. for (auto rule : rules) {
  174. if (rule->type() != CSSRule::Type::Import)
  175. rules_without_import.append(rule);
  176. }
  177. // 3. Set sheet’s CSS rules to rules.
  178. m_rules->set_rules({}, rules_without_import);
  179. // 4. Unset sheet’s disallow modification flag.
  180. set_disallow_modification(false);
  181. // 5. Resolve promise with sheet.
  182. promise->fulfill(this);
  183. });
  184. return promise;
  185. }
  186. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync
  187. WebIDL::ExceptionOr<void> CSSStyleSheet::replace_sync(StringView text)
  188. {
  189. // 1. If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException.
  190. if (!constructed())
  191. return WebIDL::NotAllowedError::create(realm(), "Can't call replaceSync() on non-constructed stylesheets"_string);
  192. if (disallow_modification())
  193. return WebIDL::NotAllowedError::create(realm(), "Can't call replaceSync() on non-modifiable stylesheets"_string);
  194. // 2. Let rules be the result of running parse a stylesheet’s contents from text.
  195. auto context = m_style_sheet_list ? CSS::Parser::ParsingContext { m_style_sheet_list->document() } : CSS::Parser::ParsingContext { realm() };
  196. auto* parsed_stylesheet = parse_css_stylesheet(context, text);
  197. auto& rules = parsed_stylesheet->rules();
  198. // 3. If rules contains one or more @import rules, remove those rules from rules.
  199. JS::MarkedVector<JS::NonnullGCPtr<CSSRule>> rules_without_import(realm().heap());
  200. for (auto rule : rules) {
  201. if (rule->type() != CSSRule::Type::Import)
  202. rules_without_import.append(rule);
  203. }
  204. // 4.Set sheet’s CSS rules to rules.
  205. m_rules->set_rules({}, rules_without_import);
  206. return {};
  207. }
  208. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-addrule
  209. WebIDL::ExceptionOr<WebIDL::Long> CSSStyleSheet::add_rule(Optional<String> selector, Optional<String> style, Optional<WebIDL::UnsignedLong> index)
  210. {
  211. // 1. Let rule be an empty string.
  212. StringBuilder rule;
  213. // 2. Append selector to rule.
  214. if (selector.has_value())
  215. rule.append(selector.release_value());
  216. // 3. Append " { " to rule.
  217. rule.append('{');
  218. // 4. If block is not empty, append block, followed by a space, to rule.
  219. if (style.has_value() && !style->is_empty())
  220. rule.appendff("{} ", style.release_value());
  221. // 5. Append "}" to rule.
  222. rule.append('}');
  223. // 6. Let index be optionalIndex if provided, or the number of CSS rules in the stylesheet otherwise.
  224. // 7. Call insertRule(), with rule and index as arguments.
  225. TRY(insert_rule(rule.string_view(), index.value_or(rules().length())));
  226. // 8. Return -1.
  227. return -1;
  228. }
  229. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-removerule
  230. WebIDL::ExceptionOr<void> CSSStyleSheet::remove_rule(Optional<WebIDL::UnsignedLong> index)
  231. {
  232. // The removeRule(index) method must run the same steps as deleteRule().
  233. return delete_rule(index.value_or(0));
  234. }
  235. void CSSStyleSheet::for_each_effective_rule(TraversalOrder order, Function<void(Web::CSS::CSSRule const&)> const& callback) const
  236. {
  237. if (m_media->matches())
  238. m_rules->for_each_effective_rule(order, callback);
  239. }
  240. void CSSStyleSheet::for_each_effective_style_rule(Function<void(CSSStyleRule const&)> const& callback) const
  241. {
  242. for_each_effective_rule(TraversalOrder::Preorder, [&](CSSRule const& rule) {
  243. if (rule.type() == CSSRule::Type::Style)
  244. callback(static_cast<CSSStyleRule const&>(rule));
  245. });
  246. }
  247. void CSSStyleSheet::for_each_effective_keyframes_at_rule(Function<void(CSSKeyframesRule const&)> const& callback) const
  248. {
  249. for_each_effective_rule(TraversalOrder::Preorder, [&](CSSRule const& rule) {
  250. if (rule.type() == CSSRule::Type::Keyframes)
  251. callback(static_cast<CSSKeyframesRule const&>(rule));
  252. });
  253. }
  254. bool CSSStyleSheet::evaluate_media_queries(HTML::Window const& window)
  255. {
  256. bool any_media_queries_changed_match_state = false;
  257. bool now_matches = m_media->evaluate(window);
  258. if (!m_did_match.has_value() || m_did_match.value() != now_matches)
  259. any_media_queries_changed_match_state = true;
  260. if (now_matches && m_rules->evaluate_media_queries(window))
  261. any_media_queries_changed_match_state = true;
  262. m_did_match = now_matches;
  263. return any_media_queries_changed_match_state;
  264. }
  265. void CSSStyleSheet::set_style_sheet_list(Badge<StyleSheetList>, StyleSheetList* list)
  266. {
  267. m_style_sheet_list = list;
  268. }
  269. Optional<FlyString> CSSStyleSheet::default_namespace() const
  270. {
  271. if (m_default_namespace_rule)
  272. return m_default_namespace_rule->namespace_uri();
  273. return {};
  274. }
  275. Optional<FlyString> CSSStyleSheet::namespace_uri(StringView namespace_prefix) const
  276. {
  277. return m_namespace_rules.get(namespace_prefix)
  278. .map([](JS::GCPtr<CSSNamespaceRule> namespace_) {
  279. return namespace_->namespace_uri();
  280. });
  281. }
  282. void CSSStyleSheet::recalculate_rule_caches()
  283. {
  284. m_default_namespace_rule = nullptr;
  285. m_namespace_rules.clear();
  286. m_import_rules.clear();
  287. for (auto const& rule : *m_rules) {
  288. // "Any @import rules must precede all other valid at-rules and style rules in a style sheet
  289. // (ignoring @charset and @layer statement rules) and must not have any other valid at-rules
  290. // or style rules between it and previous @import rules, or else the @import rule is invalid."
  291. // https://drafts.csswg.org/css-cascade-5/#at-import
  292. //
  293. // "Any @namespace rules must follow all @charset and @import rules and precede all other
  294. // non-ignored at-rules and style rules in a style sheet.
  295. // ...
  296. // A syntactically invalid @namespace rule (whether malformed or misplaced) must be ignored."
  297. // https://drafts.csswg.org/css-namespaces/#syntax
  298. switch (rule->type()) {
  299. case CSSRule::Type::Import: {
  300. // @import rules must appear before @namespace rules, so skip this if we've seen @namespace.
  301. if (!m_namespace_rules.is_empty())
  302. continue;
  303. m_import_rules.append(verify_cast<CSSImportRule>(*rule));
  304. break;
  305. }
  306. case CSSRule::Type::Namespace: {
  307. auto& namespace_rule = verify_cast<CSSNamespaceRule>(*rule);
  308. if (!namespace_rule.namespace_uri().is_empty() && namespace_rule.prefix().is_empty())
  309. m_default_namespace_rule = namespace_rule;
  310. m_namespace_rules.set(namespace_rule.prefix(), namespace_rule);
  311. break;
  312. }
  313. default:
  314. // Any other types mean that further @namespace rules are invalid, so we can stop here.
  315. return;
  316. }
  317. }
  318. }
  319. void CSSStyleSheet::set_source_text(String source)
  320. {
  321. m_source_text = move(source);
  322. }
  323. Optional<String> CSSStyleSheet::source_text(Badge<DOM::Document>) const
  324. {
  325. return m_source_text;
  326. }
  327. bool CSSStyleSheet::has_associated_font_loader(FontLoader& font_loader) const
  328. {
  329. for (auto& loader : m_associated_font_loaders) {
  330. if (loader.ptr() == &font_loader)
  331. return true;
  332. }
  333. return false;
  334. }
  335. }