CSSStyleSheet.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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::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::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 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::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. visitor.visit(m_namespace_rules);
  100. }
  101. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-insertrule
  102. WebIDL::ExceptionOr<unsigned> CSSStyleSheet::insert_rule(StringView rule, unsigned index)
  103. {
  104. // FIXME: 1. If the origin-clean flag is unset, throw a SecurityError exception.
  105. // If the disallow modification flag is set, throw a NotAllowedError DOMException.
  106. if (disallow_modification())
  107. return WebIDL::NotAllowedError::create(realm(), "Can't call insert_rule() on non-modifiable stylesheets."_fly_string);
  108. // 3. Let parsed rule be the return value of invoking parse a rule with rule.
  109. auto context = m_style_sheet_list ? CSS::Parser::ParsingContext { m_style_sheet_list->document() } : CSS::Parser::ParsingContext { realm() };
  110. auto parsed_rule = parse_css_rule(context, rule);
  111. // 4. If parsed rule is a syntax error, return parsed rule.
  112. if (!parsed_rule)
  113. return WebIDL::SyntaxError::create(realm(), "Unable to parse CSS rule."_fly_string);
  114. // 5. If parsed rule is an @import rule, and the constructed flag is set, throw a SyntaxError DOMException.
  115. if (constructed() && parsed_rule->type() == CSSRule::Type::Import)
  116. return WebIDL::SyntaxError::create(realm(), "Can't insert @import rules into a constructed stylesheet."_fly_string);
  117. // 6. Return the result of invoking insert a CSS rule rule in the CSS rules at index.
  118. auto result = m_rules->insert_a_css_rule(parsed_rule, index);
  119. if (!result.is_exception()) {
  120. // NOTE: The spec doesn't say where to set the parent style sheet, so we'll do it here.
  121. parsed_rule->set_parent_style_sheet(this);
  122. if (m_style_sheet_list) {
  123. m_style_sheet_list->document().style_computer().invalidate_rule_cache();
  124. m_style_sheet_list->document().invalidate_style();
  125. }
  126. }
  127. return result;
  128. }
  129. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-deleterule
  130. WebIDL::ExceptionOr<void> CSSStyleSheet::delete_rule(unsigned index)
  131. {
  132. // FIXME: 1. If the origin-clean flag is unset, throw a SecurityError exception.
  133. // 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
  134. if (disallow_modification())
  135. return WebIDL::NotAllowedError::create(realm(), "Can't call delete_rule() on non-modifiable stylesheets."_fly_string);
  136. // 3. Remove a CSS rule in the CSS rules at index.
  137. auto result = m_rules->remove_a_css_rule(index);
  138. if (!result.is_exception()) {
  139. if (m_style_sheet_list) {
  140. m_style_sheet_list->document().style_computer().invalidate_rule_cache();
  141. m_style_sheet_list->document().invalidate_style();
  142. }
  143. }
  144. return result;
  145. }
  146. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-replace
  147. JS::NonnullGCPtr<JS::Promise> CSSStyleSheet::replace(String text)
  148. {
  149. // 1. Let promise be a promise
  150. auto promise = JS::Promise::create(realm());
  151. // 2. If the constructed flag is not set, or the disallow modification flag is set, reject promise with a NotAllowedError DOMException and return promise.
  152. if (!constructed()) {
  153. promise->reject(WebIDL::NotAllowedError::create(realm(), "Can't call replace() on non-constructed stylesheets"_fly_string));
  154. return promise;
  155. }
  156. if (disallow_modification()) {
  157. promise->reject(WebIDL::NotAllowedError::create(realm(), "Can't call replace() on non-modifiable stylesheets"_fly_string));
  158. return promise;
  159. }
  160. // 3. Set the disallow modification flag.
  161. set_disallow_modification(true);
  162. // 4. In parallel, do these steps:
  163. Platform::EventLoopPlugin::the().deferred_invoke([this, text = move(text), promise] {
  164. // 1. Let rules be the result of running parse a stylesheet’s contents from text.
  165. auto context = m_style_sheet_list ? CSS::Parser::ParsingContext { m_style_sheet_list->document() } : CSS::Parser::ParsingContext { realm() };
  166. auto* parsed_stylesheet = parse_css_stylesheet(context, text);
  167. auto& rules = parsed_stylesheet->rules();
  168. // 2. If rules contains one or more @import rules, remove those rules from rules.
  169. JS::MarkedVector<JS::NonnullGCPtr<CSSRule>> rules_without_import(realm().heap());
  170. for (auto rule : rules) {
  171. if (rule->type() != CSSRule::Type::Import)
  172. rules_without_import.append(rule);
  173. }
  174. // 3. Set sheet’s CSS rules to rules.
  175. m_rules->set_rules({}, rules_without_import);
  176. // 4. Unset sheet’s disallow modification flag.
  177. set_disallow_modification(false);
  178. // 5. Resolve promise with sheet.
  179. promise->fulfill(this);
  180. });
  181. return promise;
  182. }
  183. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync
  184. WebIDL::ExceptionOr<void> CSSStyleSheet::replace_sync(StringView text)
  185. {
  186. // 1. If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException.
  187. if (!constructed())
  188. return WebIDL::NotAllowedError::create(realm(), "Can't call replaceSync() on non-constructed stylesheets"_fly_string);
  189. if (disallow_modification())
  190. return WebIDL::NotAllowedError::create(realm(), "Can't call replaceSync() on non-modifiable stylesheets"_fly_string);
  191. // 2. Let rules be the result of running parse a stylesheet’s contents from text.
  192. auto context = m_style_sheet_list ? CSS::Parser::ParsingContext { m_style_sheet_list->document() } : CSS::Parser::ParsingContext { realm() };
  193. auto* parsed_stylesheet = parse_css_stylesheet(context, text);
  194. auto& rules = parsed_stylesheet->rules();
  195. // 3. If rules contains one or more @import rules, remove those rules from rules.
  196. JS::MarkedVector<JS::NonnullGCPtr<CSSRule>> rules_without_import(realm().heap());
  197. for (auto rule : rules) {
  198. if (rule->type() != CSSRule::Type::Import)
  199. rules_without_import.append(rule);
  200. }
  201. // 4.Set sheet’s CSS rules to rules.
  202. m_rules->set_rules({}, rules_without_import);
  203. return {};
  204. }
  205. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-addrule
  206. WebIDL::ExceptionOr<WebIDL::Long> CSSStyleSheet::add_rule(Optional<String> selector, Optional<String> style, Optional<WebIDL::UnsignedLong> index)
  207. {
  208. // 1. Let rule be an empty string.
  209. StringBuilder rule;
  210. // 2. Append selector to rule.
  211. if (selector.has_value())
  212. rule.append(selector.release_value());
  213. // 3. Append " { " to rule.
  214. rule.append('{');
  215. // 4. If block is not empty, append block, followed by a space, to rule.
  216. if (style.has_value() && !style->is_empty())
  217. rule.appendff("{} ", style.release_value());
  218. // 5. Append "}" to rule.
  219. rule.append('}');
  220. // 6. Let index be optionalIndex if provided, or the number of CSS rules in the stylesheet otherwise.
  221. // 7. Call insertRule(), with rule and index as arguments.
  222. TRY(insert_rule(rule.string_view(), index.value_or(rules().length())));
  223. // 8. Return -1.
  224. return -1;
  225. }
  226. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-removerule
  227. WebIDL::ExceptionOr<void> CSSStyleSheet::remove_rule(Optional<WebIDL::UnsignedLong> index)
  228. {
  229. // The removeRule(index) method must run the same steps as deleteRule().
  230. return delete_rule(index.value_or(0));
  231. }
  232. void CSSStyleSheet::for_each_effective_style_rule(Function<void(CSSStyleRule const&)> const& callback) const
  233. {
  234. if (m_media->matches()) {
  235. m_rules->for_each_effective_style_rule(callback);
  236. }
  237. }
  238. void CSSStyleSheet::for_each_effective_keyframes_at_rule(Function<void(CSSKeyframesRule const&)> const& callback) const
  239. {
  240. if (m_media->matches())
  241. m_rules->for_each_effective_keyframes_at_rule(callback);
  242. }
  243. bool CSSStyleSheet::evaluate_media_queries(HTML::Window const& window)
  244. {
  245. bool any_media_queries_changed_match_state = false;
  246. bool did_match = m_media->matches();
  247. bool now_matches = m_media->evaluate(window);
  248. if (did_match != now_matches)
  249. any_media_queries_changed_match_state = true;
  250. if (now_matches && m_rules->evaluate_media_queries(window))
  251. any_media_queries_changed_match_state = true;
  252. return any_media_queries_changed_match_state;
  253. }
  254. void CSSStyleSheet::set_style_sheet_list(Badge<StyleSheetList>, StyleSheetList* list)
  255. {
  256. m_style_sheet_list = list;
  257. }
  258. Optional<FlyString> CSSStyleSheet::default_namespace() const
  259. {
  260. if (m_default_namespace_rule)
  261. return m_default_namespace_rule->namespace_uri();
  262. return {};
  263. }
  264. Optional<FlyString> CSSStyleSheet::namespace_uri(StringView namespace_prefix) const
  265. {
  266. return m_namespace_rules.get(namespace_prefix)
  267. .map([](JS::GCPtr<CSSNamespaceRule> namespace_) {
  268. return namespace_->namespace_uri();
  269. });
  270. }
  271. void CSSStyleSheet::recalculate_namespaces()
  272. {
  273. m_default_namespace_rule = nullptr;
  274. m_namespace_rules.clear();
  275. for (JS::NonnullGCPtr<CSSRule> rule : *m_rules) {
  276. // "Any @namespace rules must follow all @charset and @import rules and precede all other
  277. // non-ignored at-rules and style rules in a style sheet.
  278. // ...
  279. // A syntactically invalid @namespace rule (whether malformed or misplaced) must be ignored."
  280. // https://drafts.csswg.org/css-namespaces/#syntax
  281. switch (rule->type()) {
  282. case CSSRule::Type::Import:
  283. continue;
  284. case CSSRule::Type::Namespace:
  285. break;
  286. default:
  287. // Any other types mean that further @namespace rules are invalid, so we can stop here.
  288. return;
  289. }
  290. auto& namespace_rule = verify_cast<CSSNamespaceRule>(*rule);
  291. if (!namespace_rule.namespace_uri().is_empty() && namespace_rule.prefix().is_empty())
  292. m_default_namespace_rule = namespace_rule;
  293. m_namespace_rules.set(namespace_rule.prefix(), namespace_rule);
  294. }
  295. }
  296. }