HTMLCollection.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2021-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Function.h>
  9. #include <LibJS/Heap/GCPtr.h>
  10. #include <LibWeb/Bindings/PlatformObject.h>
  11. #include <LibWeb/Forward.h>
  12. namespace Web::DOM {
  13. // NOTE: HTMLCollection is in the DOM namespace because it's part of the DOM specification.
  14. // This class implements a live, filtered view of a DOM subtree.
  15. // When constructing an HTMLCollection, you provide a root node + a filter.
  16. // The filter is a simple Function object that answers the question
  17. // "is this Element part of the collection?"
  18. // FIXME: HTMLCollection currently does no caching. It will re-filter on every access!
  19. // We should teach it how to cache results. The main challenge is invalidating
  20. // these caches, since this needs to happen on various kinds of DOM mutation.
  21. class HTMLCollection : public Bindings::PlatformObject {
  22. WEB_PLATFORM_OBJECT(HTMLCollection, Bindings::PlatformObject);
  23. JS_DECLARE_ALLOCATOR(HTMLCollection);
  24. public:
  25. enum class Scope {
  26. Children,
  27. Descendants,
  28. };
  29. [[nodiscard]] static JS::NonnullGCPtr<HTMLCollection> create(ParentNode& root, Scope, Function<bool(Element const&)> filter);
  30. virtual ~HTMLCollection() override;
  31. size_t length() const;
  32. Element* item(size_t index) const;
  33. Element* named_item(FlyString const& name) const;
  34. JS::MarkedVector<Element*> collect_matching_elements() const;
  35. virtual WebIDL::ExceptionOr<JS::Value> item_value(size_t index) const override;
  36. virtual WebIDL::ExceptionOr<JS::Value> named_item_value(FlyString const& name) const override;
  37. virtual Vector<FlyString> supported_property_names() const override;
  38. virtual bool is_supported_property_index(u32) const override;
  39. protected:
  40. HTMLCollection(ParentNode& root, Scope, Function<bool(Element const&)> filter);
  41. virtual void initialize(JS::Realm&) override;
  42. JS::NonnullGCPtr<ParentNode> root() { return *m_root; }
  43. JS::NonnullGCPtr<ParentNode const> root() const { return *m_root; }
  44. private:
  45. virtual void visit_edges(Cell::Visitor&) override;
  46. JS::NonnullGCPtr<ParentNode> m_root;
  47. Function<bool(Element const&)> m_filter;
  48. Scope m_scope { Scope::Descendants };
  49. };
  50. }