CSSStyleSheet.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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/WebIDL/ExceptionOr.h>
  16. namespace Web::CSS {
  17. JS_DEFINE_ALLOCATOR(CSSStyleSheet);
  18. JS::NonnullGCPtr<CSSStyleSheet> CSSStyleSheet::create(JS::Realm& realm, CSSRuleList& rules, MediaList& media, Optional<AK::URL> location)
  19. {
  20. return realm.heap().allocate<CSSStyleSheet>(realm, realm, rules, media, move(location));
  21. }
  22. // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssstylesheet
  23. WebIDL::ExceptionOr<JS::NonnullGCPtr<CSSStyleSheet>> CSSStyleSheet::construct_impl(JS::Realm& realm, Optional<CSSStyleSheetInit> const& options)
  24. {
  25. // 1. Construct a new CSSStyleSheet object sheet.
  26. auto sheet = create(realm, CSSRuleList::create_empty(realm), CSS::MediaList::create(realm, {}), {});
  27. // 2. Set sheet’s location to the base URL of the associated Document for the current global object.
  28. auto associated_document = sheet->global_object().document();
  29. sheet->set_location(MUST(associated_document->base_url().to_string()));
  30. // 3. Set sheet’s stylesheet base URL to the baseURL attribute value from options.
  31. if (options.has_value() && options->base_url.has_value()) {
  32. Optional<AK::URL> sheet_location_url;
  33. if (sheet->location().has_value())
  34. sheet_location_url = sheet->location().release_value();
  35. // AD-HOC: This isn't explicitly mentioned in the specification, but multiple modern browsers do this.
  36. AK::URL url = sheet->location().has_value() ? sheet_location_url->complete_url(options->base_url.value()) : options->base_url.value();
  37. if (!url.is_valid())
  38. return WebIDL::NotAllowedError::create(realm, "Constructed style sheets must have a valid base URL"_fly_string);
  39. sheet->set_base_url(url);
  40. }
  41. // 4. Set sheet’s parent CSS style sheet to null.
  42. sheet->set_parent_css_style_sheet(nullptr);
  43. // 5. Set sheet’s owner node to null.
  44. sheet->set_owner_node(nullptr);
  45. // 6. Set sheet’s owner CSS rule to null.
  46. sheet->set_owner_css_rule(nullptr);
  47. // 7. Set sheet’s title to the the empty string.
  48. sheet->set_title(String {});
  49. // 8. Unset sheet’s alternate flag.
  50. sheet->set_alternate(false);
  51. // 9. Set sheet’s origin-clean flag.
  52. sheet->set_origin_clean(true);
  53. // 10. Set sheet’s constructed flag.
  54. sheet->set_constructed(true);
  55. // 11. Set sheet’s Constructor document to the associated Document for the current global object.
  56. sheet->set_constructor_document(associated_document);
  57. // 12. If the media attribute of options is a string, create a MediaList object from the string and assign it as sheet’s media.
  58. // 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.
  59. if (options.has_value()) {
  60. if (options->media.has<String>()) {
  61. sheet->set_media(options->media.get<String>());
  62. } else {
  63. sheet->m_media = *options->media.get<JS::Handle<MediaList>>();
  64. }
  65. }
  66. // 13. If the disabled attribute of options is true, set sheet’s disabled flag.
  67. if (options.has_value() && options->disabled)
  68. sheet->set_disabled(true);
  69. // 14. Return sheet
  70. return sheet;
  71. }
  72. CSSStyleSheet::CSSStyleSheet(JS::Realm& realm, CSSRuleList& rules, MediaList& media, Optional<AK::URL> location)
  73. : StyleSheet(realm, media)
  74. , m_rules(&rules)
  75. {
  76. if (location.has_value())
  77. set_location(MUST(location->to_string()));
  78. for (auto& rule : *m_rules)
  79. rule->set_parent_style_sheet(this);
  80. recalculate_namespaces();
  81. m_rules->on_change = [this]() {
  82. recalculate_namespaces();
  83. };
  84. }
  85. void CSSStyleSheet::initialize(JS::Realm& realm)
  86. {
  87. Base::initialize(realm);
  88. set_prototype(&Bindings::ensure_web_prototype<Bindings::CSSStyleSheetPrototype>(realm, "CSSStyleSheet"_fly_string));
  89. }
  90. void CSSStyleSheet::visit_edges(Cell::Visitor& visitor)
  91. {
  92. Base::visit_edges(visitor);
  93. visitor.visit(m_style_sheet_list);
  94. visitor.visit(m_rules);
  95. visitor.visit(m_owner_css_rule);
  96. visitor.visit(m_default_namespace_rule);
  97. visitor.visit(m_constructor_document);
  98. for (auto& [key, namespace_rule] : m_namespace_rules)
  99. visitor.visit(namespace_rule);
  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. // FIXME: 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
  106. // 3. Let parsed rule be the return value of invoking parse a rule with rule.
  107. auto context = m_style_sheet_list ? CSS::Parser::ParsingContext { m_style_sheet_list->document() } : CSS::Parser::ParsingContext { realm() };
  108. auto parsed_rule = parse_css_rule(context, rule);
  109. // 4. If parsed rule is a syntax error, return parsed rule.
  110. if (!parsed_rule)
  111. return WebIDL::SyntaxError::create(realm(), "Unable to parse CSS rule."_fly_string);
  112. // FIXME: 5. If parsed rule is an @import rule, and the constructed flag is set, throw a SyntaxError DOMException.
  113. // 6. Return the result of invoking insert a CSS rule rule in the CSS rules at index.
  114. auto result = m_rules->insert_a_css_rule(parsed_rule, index);
  115. if (!result.is_exception()) {
  116. // NOTE: The spec doesn't say where to set the parent style sheet, so we'll do it here.
  117. parsed_rule->set_parent_style_sheet(this);
  118. if (m_style_sheet_list) {
  119. m_style_sheet_list->document().style_computer().invalidate_rule_cache();
  120. m_style_sheet_list->document().invalidate_style();
  121. }
  122. }
  123. return result;
  124. }
  125. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-deleterule
  126. WebIDL::ExceptionOr<void> CSSStyleSheet::delete_rule(unsigned index)
  127. {
  128. // FIXME: 1. If the origin-clean flag is unset, throw a SecurityError exception.
  129. // FIXME: 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
  130. // 3. Remove a CSS rule in the CSS rules at index.
  131. auto result = m_rules->remove_a_css_rule(index);
  132. if (!result.is_exception()) {
  133. if (m_style_sheet_list) {
  134. m_style_sheet_list->document().style_computer().invalidate_rule_cache();
  135. m_style_sheet_list->document().invalidate_style();
  136. }
  137. }
  138. return result;
  139. }
  140. // https://www.w3.org/TR/cssom/#dom-cssstylesheet-removerule
  141. WebIDL::ExceptionOr<void> CSSStyleSheet::remove_rule(unsigned index)
  142. {
  143. // The removeRule(index) method must run the same steps as deleteRule().
  144. return delete_rule(index);
  145. }
  146. void CSSStyleSheet::for_each_effective_style_rule(Function<void(CSSStyleRule const&)> const& callback) const
  147. {
  148. if (m_media->matches()) {
  149. m_rules->for_each_effective_style_rule(callback);
  150. }
  151. }
  152. void CSSStyleSheet::for_each_effective_keyframes_at_rule(Function<void(CSSKeyframesRule const&)> const& callback) const
  153. {
  154. if (m_media->matches())
  155. m_rules->for_each_effective_keyframes_at_rule(callback);
  156. }
  157. bool CSSStyleSheet::evaluate_media_queries(HTML::Window const& window)
  158. {
  159. bool any_media_queries_changed_match_state = false;
  160. bool did_match = m_media->matches();
  161. bool now_matches = m_media->evaluate(window);
  162. if (did_match != now_matches)
  163. any_media_queries_changed_match_state = true;
  164. if (now_matches && m_rules->evaluate_media_queries(window))
  165. any_media_queries_changed_match_state = true;
  166. return any_media_queries_changed_match_state;
  167. }
  168. void CSSStyleSheet::set_style_sheet_list(Badge<StyleSheetList>, StyleSheetList* list)
  169. {
  170. m_style_sheet_list = list;
  171. }
  172. Optional<FlyString> CSSStyleSheet::default_namespace() const
  173. {
  174. if (m_default_namespace_rule)
  175. return m_default_namespace_rule->namespace_uri();
  176. return {};
  177. }
  178. Optional<FlyString> CSSStyleSheet::namespace_uri(StringView namespace_prefix) const
  179. {
  180. return m_namespace_rules.get(namespace_prefix)
  181. .map([](JS::GCPtr<CSSNamespaceRule> namespace_) {
  182. return namespace_->namespace_uri();
  183. });
  184. }
  185. void CSSStyleSheet::recalculate_namespaces()
  186. {
  187. m_default_namespace_rule = nullptr;
  188. m_namespace_rules.clear();
  189. for (JS::NonnullGCPtr<CSSRule> rule : *m_rules) {
  190. // "Any @namespace rules must follow all @charset and @import rules and precede all other
  191. // non-ignored at-rules and style rules in a style sheet.
  192. // ...
  193. // A syntactically invalid @namespace rule (whether malformed or misplaced) must be ignored."
  194. // https://drafts.csswg.org/css-namespaces/#syntax
  195. switch (rule->type()) {
  196. case CSSRule::Type::Import:
  197. continue;
  198. case CSSRule::Type::Namespace:
  199. break;
  200. default:
  201. // Any other types mean that further @namespace rules are invalid, so we can stop here.
  202. return;
  203. }
  204. auto& namespace_rule = verify_cast<CSSNamespaceRule>(*rule);
  205. if (!namespace_rule.namespace_uri().is_empty() && namespace_rule.prefix().is_empty())
  206. m_default_namespace_rule = namespace_rule;
  207. m_namespace_rules.set(namespace_rule.prefix(), namespace_rule);
  208. }
  209. }
  210. }