StyleSheetList.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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/StyleSheetListPrototype.h>
  8. #include <LibWeb/CSS/StyleSheetList.h>
  9. #include <LibWeb/DOM/Document.h>
  10. namespace Web::CSS {
  11. void StyleSheetList::add_sheet(CSSStyleSheet& sheet)
  12. {
  13. sheet.set_style_sheet_list({}, this);
  14. m_sheets.append(sheet);
  15. sort_sheets();
  16. m_document.style_computer().invalidate_rule_cache();
  17. m_document.style_computer().load_fonts_from_sheet(sheet);
  18. m_document.invalidate_style();
  19. }
  20. void StyleSheetList::remove_sheet(CSSStyleSheet& sheet)
  21. {
  22. sheet.set_style_sheet_list({}, nullptr);
  23. m_sheets.remove_first_matching([&](auto& entry) { return entry.ptr() == &sheet; });
  24. sort_sheets();
  25. m_document.style_computer().invalidate_rule_cache();
  26. m_document.invalidate_style();
  27. }
  28. StyleSheetList* StyleSheetList::create(DOM::Document& document)
  29. {
  30. auto& realm = document.window().realm();
  31. return realm.heap().allocate<StyleSheetList>(realm, document);
  32. }
  33. StyleSheetList::StyleSheetList(DOM::Document& document)
  34. : Bindings::LegacyPlatformObject(document.window().cached_web_prototype("StyleSheetList"))
  35. , m_document(document)
  36. {
  37. }
  38. void StyleSheetList::visit_edges(Cell::Visitor& visitor)
  39. {
  40. Base::visit_edges(visitor);
  41. visitor.visit(m_document);
  42. for (auto sheet : m_sheets)
  43. visitor.visit(sheet.ptr());
  44. }
  45. // https://www.w3.org/TR/cssom/#ref-for-dfn-supported-property-indices%E2%91%A1
  46. bool StyleSheetList::is_supported_property_index(u32 index) const
  47. {
  48. // 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.
  49. // If there are no such CSS style sheets, then there are no supported property indices.
  50. if (m_sheets.is_empty())
  51. return false;
  52. return index < m_sheets.size();
  53. }
  54. JS::Value StyleSheetList::item_value(size_t index) const
  55. {
  56. if (index >= m_sheets.size())
  57. return JS::js_undefined();
  58. return m_sheets[index].ptr();
  59. }
  60. void StyleSheetList::sort_sheets()
  61. {
  62. quick_sort(m_sheets, [](JS::NonnullGCPtr<StyleSheet> a, JS::NonnullGCPtr<StyleSheet> b) {
  63. return a->owner_node()->is_before(*b->owner_node());
  64. });
  65. }
  66. }