ModuleMap.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2022-2023, networkException <networkexception@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibJS/Heap/Cell.h>
  8. #include <LibJS/Heap/HeapFunction.h>
  9. #include <LibURL/URL.h>
  10. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  11. namespace Web::HTML {
  12. class ModuleLocationTuple {
  13. public:
  14. ModuleLocationTuple(URL::URL url, ByteString type)
  15. : m_url(move(url))
  16. , m_type(move(type))
  17. {
  18. }
  19. URL::URL const& url() const { return m_url; }
  20. ByteString const& type() const { return m_type; }
  21. bool operator==(ModuleLocationTuple const& other) const
  22. {
  23. return other.url() == m_url && other.type() == m_type;
  24. }
  25. private:
  26. URL::URL m_url;
  27. ByteString m_type;
  28. };
  29. // https://html.spec.whatwg.org/multipage/webappapis.html#module-map
  30. class ModuleMap final : public JS::Cell {
  31. JS_CELL(ModuleMap, Cell);
  32. JS_DECLARE_ALLOCATOR(ModuleMap);
  33. public:
  34. ModuleMap() = default;
  35. ~ModuleMap() = default;
  36. enum class EntryType {
  37. Fetching,
  38. Failed,
  39. ModuleScript
  40. };
  41. struct Entry {
  42. EntryType type;
  43. JS::GCPtr<JavaScriptModuleScript> module_script;
  44. };
  45. using CallbackFunction = JS::NonnullGCPtr<JS::HeapFunction<void(Entry)>>;
  46. bool is_fetching(URL::URL const& url, ByteString const& type) const;
  47. bool is_failed(URL::URL const& url, ByteString const& type) const;
  48. bool is(URL::URL const& url, ByteString const& type, EntryType) const;
  49. Optional<Entry> get(URL::URL const& url, ByteString const& type) const;
  50. AK::HashSetResult set(URL::URL const& url, ByteString const& type, Entry);
  51. void wait_for_change(JS::Heap&, URL::URL const& url, ByteString const& type, Function<void(Entry)> callback);
  52. private:
  53. virtual void visit_edges(JS::Cell::Visitor&) override;
  54. HashMap<ModuleLocationTuple, Entry> m_values;
  55. HashMap<ModuleLocationTuple, Vector<CallbackFunction>> m_callbacks;
  56. bool m_firing_callbacks { false };
  57. };
  58. }
  59. namespace AK {
  60. template<>
  61. struct Traits<Web::HTML::ModuleLocationTuple> : public DefaultTraits<Web::HTML::ModuleLocationTuple> {
  62. static unsigned hash(Web::HTML::ModuleLocationTuple const& tuple)
  63. {
  64. return pair_int_hash(tuple.url().to_byte_string().hash(), tuple.type().hash());
  65. }
  66. };
  67. }