StyleSheetList.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibWeb/Bindings/Intrinsics.h>
  8. #include <LibWeb/Bindings/StyleSheetListPrototype.h>
  9. #include <LibWeb/CSS/StyleSheetList.h>
  10. #include <LibWeb/DOM/Document.h>
  11. namespace Web::CSS {
  12. void StyleSheetList::add_sheet(CSSStyleSheet& sheet)
  13. {
  14. sheet.set_style_sheet_list({}, this);
  15. m_sheets.append(sheet);
  16. sort_sheets();
  17. m_document.style_computer().invalidate_rule_cache();
  18. m_document.style_computer().load_fonts_from_sheet(sheet);
  19. m_document.invalidate_style();
  20. }
  21. void StyleSheetList::remove_sheet(CSSStyleSheet& sheet)
  22. {
  23. sheet.set_style_sheet_list({}, nullptr);
  24. m_sheets.remove_first_matching([&](auto& entry) { return entry.ptr() == &sheet; });
  25. sort_sheets();
  26. m_document.style_computer().invalidate_rule_cache();
  27. m_document.invalidate_style();
  28. }
  29. StyleSheetList* StyleSheetList::create(DOM::Document& document)
  30. {
  31. auto& realm = document.realm();
  32. return realm.heap().allocate<StyleSheetList>(realm, document);
  33. }
  34. StyleSheetList::StyleSheetList(DOM::Document& document)
  35. : Bindings::LegacyPlatformObject(Bindings::ensure_web_prototype<Bindings::StyleSheetListPrototype>(document.realm(), "StyleSheetList"))
  36. , m_document(document)
  37. {
  38. }
  39. void StyleSheetList::visit_edges(Cell::Visitor& visitor)
  40. {
  41. Base::visit_edges(visitor);
  42. visitor.visit(m_document);
  43. for (auto sheet : m_sheets)
  44. visitor.visit(sheet.ptr());
  45. }
  46. // https://www.w3.org/TR/cssom/#ref-for-dfn-supported-property-indices%E2%91%A1
  47. bool StyleSheetList::is_supported_property_index(u32 index) const
  48. {
  49. // The object’s supported property indices are the numbers in the range zero to one less than the number of CSS style sheets represented by the collection.
  50. // If there are no such CSS style sheets, then there are no supported property indices.
  51. if (m_sheets.is_empty())
  52. return false;
  53. return index < m_sheets.size();
  54. }
  55. JS::Value StyleSheetList::item_value(size_t index) const
  56. {
  57. if (index >= m_sheets.size())
  58. return JS::js_undefined();
  59. return m_sheets[index].ptr();
  60. }
  61. void StyleSheetList::sort_sheets()
  62. {
  63. quick_sort(m_sheets, [](JS::NonnullGCPtr<StyleSheet> a, JS::NonnullGCPtr<StyleSheet> b) {
  64. return a->owner_node()->is_before(*b->owner_node());
  65. });
  66. }
  67. }