AdoptedStyleSheets.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * Copyright (c) 2024, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/CSS/StyleComputer.h>
  7. #include <LibWeb/DOM/AdoptedStyleSheets.h>
  8. #include <LibWeb/DOM/Document.h>
  9. namespace Web::DOM {
  10. JS::NonnullGCPtr<WebIDL::ObservableArray> create_adopted_style_sheets_list(Document& document)
  11. {
  12. auto adopted_style_sheets = WebIDL::ObservableArray::create(document.realm());
  13. adopted_style_sheets->set_on_set_an_indexed_value_callback([&document](JS::Value& value) -> WebIDL::ExceptionOr<void> {
  14. auto& vm = document.vm();
  15. if (!value.is_object())
  16. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "CSSStyleSheet");
  17. auto& object = value.as_object();
  18. if (!is<CSS::CSSStyleSheet>(object))
  19. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "CSSStyleSheet");
  20. auto& style_sheet = static_cast<CSS::CSSStyleSheet&>(object);
  21. // The set an indexed value algorithm for adoptedStyleSheets, given value and index, is the following:
  22. // 1. If value’s constructed flag is not set, or its constructor document is not equal to this
  23. // DocumentOrShadowRoot's node document, throw a "NotAllowedError" DOMException.
  24. if (!style_sheet.constructed())
  25. return WebIDL::NotAllowedError::create(document.realm(), "StyleSheet's constructed flag is not set."_fly_string);
  26. if (!style_sheet.constructed() || style_sheet.constructor_document().ptr() != &document)
  27. return WebIDL::NotAllowedError::create(document.realm(), "Sharing a StyleSheet between documents is not allowed."_fly_string);
  28. document.style_computer().load_fonts_from_sheet(style_sheet);
  29. document.style_computer().invalidate_rule_cache();
  30. document.invalidate_style();
  31. return {};
  32. });
  33. adopted_style_sheets->set_on_delete_an_indexed_value_callback([&document]() -> WebIDL::ExceptionOr<void> {
  34. document.style_computer().invalidate_rule_cache();
  35. document.invalidate_style();
  36. return {};
  37. });
  38. return adopted_style_sheets;
  39. }
  40. }