CSSStyleSheet.cpp 14 KB

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