CSSStyleSheet.cpp 16 KB

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