ObservableArray.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2024, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibJS/Runtime/Array.h>
  8. #include <LibWeb/WebIDL/ExceptionOr.h>
  9. namespace Web::WebIDL {
  10. // https://webidl.spec.whatwg.org/#idl-observable-array
  11. class ObservableArray final : public JS::Array {
  12. JS_OBJECT(ObservableArray, JS::Array);
  13. GC_DECLARE_ALLOCATOR(ObservableArray);
  14. public:
  15. static GC::Ref<ObservableArray> create(JS::Realm& realm);
  16. virtual JS::ThrowCompletionOr<bool> internal_set(JS::PropertyKey const& property_key, JS::Value value, JS::Value receiver, JS::CacheablePropertyMetadata* metadata = nullptr) override;
  17. virtual JS::ThrowCompletionOr<bool> internal_delete(JS::PropertyKey const& property_key) override;
  18. using SetAnIndexedValueCallbackFunction = Function<ExceptionOr<void>(JS::Value&)>;
  19. using DeleteAnIndexedValueCallbackFunction = Function<ExceptionOr<void>()>;
  20. void set_on_set_an_indexed_value_callback(SetAnIndexedValueCallbackFunction&& callback);
  21. void set_on_delete_an_indexed_value_callback(DeleteAnIndexedValueCallbackFunction&& callback);
  22. JS::ThrowCompletionOr<void> append(JS::Value value);
  23. void clear();
  24. template<typename T, typename Callback>
  25. void for_each(Callback callback)
  26. {
  27. for (auto& entry : indexed_properties()) {
  28. auto value_and_attributes = indexed_properties().storage()->get(entry.index());
  29. if (value_and_attributes.has_value()) {
  30. auto& style_sheet = verify_cast<T>(value_and_attributes->value.as_object());
  31. callback(style_sheet);
  32. }
  33. }
  34. }
  35. explicit ObservableArray(Object& prototype);
  36. virtual void visit_edges(JS::Cell::Visitor&) override;
  37. private:
  38. using SetAnIndexedValueCallbackHeapFunction = GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>;
  39. using DeleteAnIndexedValueCallbackHeapFunction = GC::Function<DeleteAnIndexedValueCallbackFunction::FunctionType>;
  40. GC::Ptr<SetAnIndexedValueCallbackHeapFunction> m_on_set_an_indexed_value;
  41. GC::Ptr<DeleteAnIndexedValueCallbackHeapFunction> m_on_delete_an_indexed_value;
  42. };
  43. }