ObservableArray.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. public:
  13. static JS::NonnullGCPtr<ObservableArray> create(JS::Realm& realm);
  14. virtual JS::ThrowCompletionOr<bool> internal_set(JS::PropertyKey const& property_key, JS::Value value, JS::Value receiver, JS::CacheablePropertyMetadata* metadata = nullptr) override;
  15. virtual JS::ThrowCompletionOr<bool> internal_delete(JS::PropertyKey const& property_key) override;
  16. using SetAnIndexedValueCallbackFunction = Function<ExceptionOr<void>(JS::Value&)>;
  17. using DeleteAnIndexedValueCallbackFunction = Function<ExceptionOr<void>()>;
  18. void set_on_set_an_indexed_value_callback(SetAnIndexedValueCallbackFunction&& callback);
  19. void set_on_delete_an_indexed_value_callback(DeleteAnIndexedValueCallbackFunction&& callback);
  20. JS::ThrowCompletionOr<void> append(JS::Value value);
  21. void clear();
  22. template<typename T, typename Callback>
  23. void for_each(Callback callback)
  24. {
  25. for (auto& entry : indexed_properties()) {
  26. auto value_and_attributes = indexed_properties().storage()->get(entry.index());
  27. if (value_and_attributes.has_value()) {
  28. auto& style_sheet = verify_cast<T>(value_and_attributes->value.as_object());
  29. callback(style_sheet);
  30. }
  31. }
  32. }
  33. explicit ObservableArray(Object& prototype);
  34. virtual void visit_edges(JS::Cell::Visitor&) override;
  35. private:
  36. using SetAnIndexedValueCallbackHeapFunction = JS::HeapFunction<SetAnIndexedValueCallbackFunction::FunctionType>;
  37. using DeleteAnIndexedValueCallbackHeapFunction = JS::HeapFunction<DeleteAnIndexedValueCallbackFunction::FunctionType>;
  38. JS::GCPtr<SetAnIndexedValueCallbackHeapFunction> m_on_set_an_indexed_value;
  39. JS::GCPtr<DeleteAnIndexedValueCallbackHeapFunction> m_on_delete_an_indexed_value;
  40. };
  41. }