CSSMediaRule.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  3. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/Realm.h>
  8. #include <LibWeb/Bindings/CSSMediaRulePrototype.h>
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/CSS/CSSMediaRule.h>
  11. namespace Web::CSS {
  12. JS_DEFINE_ALLOCATOR(CSSMediaRule);
  13. JS::NonnullGCPtr<CSSMediaRule> CSSMediaRule::create(JS::Realm& realm, MediaList& media_queries, CSSRuleList& rules)
  14. {
  15. return realm.heap().allocate<CSSMediaRule>(realm, realm, media_queries, rules);
  16. }
  17. CSSMediaRule::CSSMediaRule(JS::Realm& realm, MediaList& media, CSSRuleList& rules)
  18. : CSSConditionRule(realm, rules)
  19. , m_media(media)
  20. {
  21. }
  22. void CSSMediaRule::initialize(JS::Realm& realm)
  23. {
  24. Base::initialize(realm);
  25. WEB_SET_PROTOTYPE_FOR_INTERFACE(CSSMediaRule);
  26. }
  27. void CSSMediaRule::visit_edges(Cell::Visitor& visitor)
  28. {
  29. Base::visit_edges(visitor);
  30. visitor.visit(m_media);
  31. }
  32. String CSSMediaRule::condition_text() const
  33. {
  34. return m_media->media_text();
  35. }
  36. // https://www.w3.org/TR/cssom-1/#serialize-a-css-rule
  37. String CSSMediaRule::serialized() const
  38. {
  39. // The result of concatenating the following:
  40. StringBuilder builder;
  41. // 1. The string "@media", followed by a single SPACE (U+0020).
  42. builder.append("@media "sv);
  43. // 2. The result of performing serialize a media query list on rule’s media query list.
  44. builder.append(condition_text());
  45. // 3. A single SPACE (U+0020), followed by the string "{", i.e., LEFT CURLY BRACKET (U+007B), followed by a newline.
  46. builder.append(" {\n"sv);
  47. // AD-HOC: All modern browsers omit the ending newline if there are no CSS rules, so let's do the same.
  48. if (css_rules().length() == 0) {
  49. builder.append('}');
  50. return MUST(builder.to_string());
  51. }
  52. // 4. The result of performing serialize a CSS rule on each rule in the rule’s cssRules list, separated by a newline and indented by two spaces.
  53. for (size_t i = 0; i < css_rules().length(); i++) {
  54. auto rule = css_rules().item(i);
  55. if (i != 0)
  56. builder.append("\n"sv);
  57. builder.append(" "sv);
  58. builder.append(rule->css_text());
  59. }
  60. // 5. A newline, followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D)
  61. builder.append("\n}"sv);
  62. return MUST(builder.to_string());
  63. }
  64. }