IntersectionObserver.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /*
  2. * Copyright (c) 2021, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibWeb/Bindings/Intrinsics.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/DOM/Element.h>
  10. #include <LibWeb/IntersectionObserver/IntersectionObserver.h>
  11. namespace Web::IntersectionObserver {
  12. // https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-intersectionobserver
  13. WebIDL::ExceptionOr<JS::NonnullGCPtr<IntersectionObserver>> IntersectionObserver::construct_impl(JS::Realm& realm, JS::GCPtr<WebIDL::CallbackType> callback, IntersectionObserverInit const& options)
  14. {
  15. // 4. Let thresholds be a list equal to options.threshold.
  16. Vector<double> thresholds;
  17. if (options.threshold.has<double>()) {
  18. thresholds.append(options.threshold.get<double>());
  19. } else {
  20. VERIFY(options.threshold.has<Vector<double>>());
  21. thresholds = options.threshold.get<Vector<double>>();
  22. }
  23. // 5. If any value in thresholds is less than 0.0 or greater than 1.0, throw a RangeError exception.
  24. for (auto value : thresholds) {
  25. if (value < 0.0 || value > 1.0)
  26. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Threshold values must be between 0.0 and 1.0 inclusive"sv };
  27. }
  28. // 6. Sort thresholds in ascending order.
  29. quick_sort(thresholds, [](double left, double right) {
  30. return left < right;
  31. });
  32. // 1. Let this be a new IntersectionObserver object
  33. // 2. Set this’s internal [[callback]] slot to callback.
  34. // 8. The thresholds attribute getter will return this sorted thresholds list.
  35. // 9. Return this.
  36. return realm.heap().allocate<IntersectionObserver>(realm, realm, callback, options.root, move(thresholds));
  37. }
  38. IntersectionObserver::IntersectionObserver(JS::Realm& realm, JS::GCPtr<WebIDL::CallbackType> callback, Optional<Variant<JS::Handle<DOM::Element>, JS::Handle<DOM::Document>>> const& root, Vector<double>&& thresholds)
  39. : PlatformObject(realm)
  40. , m_callback(callback)
  41. , m_root(root)
  42. , m_thresholds(move(thresholds))
  43. {
  44. intersection_root().visit([this](auto& node) {
  45. node->document().register_intersection_observer({}, *this);
  46. });
  47. }
  48. IntersectionObserver::~IntersectionObserver() = default;
  49. void IntersectionObserver::finalize()
  50. {
  51. intersection_root().visit([this](auto& node) {
  52. node->document().unregister_intersection_observer({}, *this);
  53. });
  54. }
  55. void IntersectionObserver::initialize(JS::Realm& realm)
  56. {
  57. Base::initialize(realm);
  58. set_prototype(&Bindings::ensure_web_prototype<Bindings::IntersectionObserverPrototype>(realm, "IntersectionObserver"));
  59. }
  60. void IntersectionObserver::visit_edges(JS::Cell::Visitor& visitor)
  61. {
  62. Base::visit_edges(visitor);
  63. visitor.visit(m_callback);
  64. for (auto& entry : m_queued_entries)
  65. visitor.visit(entry);
  66. for (auto& target : m_observation_targets)
  67. visitor.visit(target);
  68. }
  69. // https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-observe
  70. void IntersectionObserver::observe(DOM::Element& target)
  71. {
  72. // Run the observe a target Element algorithm, providing this and target.
  73. // https://www.w3.org/TR/intersection-observer/#observe-a-target-element
  74. // 1. If target is in observer’s internal [[ObservationTargets]] slot, return.
  75. if (m_observation_targets.contains_slow(JS::NonnullGCPtr { target }))
  76. return;
  77. // 2. Let intersectionObserverRegistration be an IntersectionObserverRegistration record with an observer
  78. // property set to observer, a previousThresholdIndex property set to -1, and a previousIsIntersecting
  79. // property set to false.
  80. auto intersection_observer_registration = IntersectionObserverRegistration {
  81. .observer = JS::make_handle(*this),
  82. .previous_threshold_index = OptionalNone {},
  83. .previous_is_intersecting = false,
  84. };
  85. // 3. Append intersectionObserverRegistration to target’s internal [[RegisteredIntersectionObservers]] slot.
  86. target.register_intersection_observer({}, move(intersection_observer_registration));
  87. // 4. Add target to observer’s internal [[ObservationTargets]] slot.
  88. m_observation_targets.append(target);
  89. }
  90. // https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-unobserve
  91. void IntersectionObserver::unobserve(DOM::Element& target)
  92. {
  93. // Run the unobserve a target Element algorithm, providing this and target.
  94. // https://www.w3.org/TR/intersection-observer/#unobserve-a-target-element
  95. // 1. Remove the IntersectionObserverRegistration record whose observer property is equal to this from target’s internal [[RegisteredIntersectionObservers]] slot, if present.
  96. target.unregister_intersection_observer({}, *this);
  97. // 2. Remove target from this’s internal [[ObservationTargets]] slot, if present
  98. m_observation_targets.remove_first_matching([&target](JS::NonnullGCPtr<DOM::Element> const& entry) {
  99. return entry.ptr() == &target;
  100. });
  101. }
  102. // https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-disconnect
  103. void IntersectionObserver::disconnect()
  104. {
  105. // For each target in this’s internal [[ObservationTargets]] slot:
  106. // 1. Remove the IntersectionObserverRegistration record whose observer property is equal to this from target’s internal
  107. // [[RegisteredIntersectionObservers]] slot.
  108. // 2. Remove target from this’s internal [[ObservationTargets]] slot.
  109. for (auto& target : m_observation_targets) {
  110. target->unregister_intersection_observer({}, *this);
  111. }
  112. m_observation_targets.clear();
  113. }
  114. // https://www.w3.org/TR/intersection-observer/#dom-intersectionobserver-takerecords
  115. Vector<JS::Handle<IntersectionObserverEntry>> IntersectionObserver::take_records()
  116. {
  117. // 1. Let queue be a copy of this’s internal [[QueuedEntries]] slot.
  118. Vector<JS::Handle<IntersectionObserverEntry>> queue;
  119. for (auto& entry : m_queued_entries)
  120. queue.append(*entry);
  121. // 2. Clear this’s internal [[QueuedEntries]] slot.
  122. m_queued_entries.clear();
  123. // 3. Return queue.
  124. return queue;
  125. }
  126. Variant<JS::Handle<DOM::Element>, JS::Handle<DOM::Document>, Empty> IntersectionObserver::root() const
  127. {
  128. if (!m_root.has_value())
  129. return Empty {};
  130. return m_root.value();
  131. }
  132. Variant<JS::Handle<DOM::Element>, JS::Handle<DOM::Document>> IntersectionObserver::intersection_root() const
  133. {
  134. if (!m_root.has_value())
  135. return JS::make_handle(global_object().browsing_context()->top_level_browsing_context().active_document());
  136. return m_root.value();
  137. }
  138. // https://www.w3.org/TR/intersection-observer/#intersectionobserver-root-intersection-rectangle
  139. CSSPixelRect IntersectionObserver::root_intersection_rectangle() const
  140. {
  141. // If the IntersectionObserver is an implicit root observer,
  142. // it’s treated as if the root were the top-level browsing context’s document, according to the following rule for document.
  143. auto intersection_root = this->intersection_root();
  144. CSSPixelRect rect;
  145. // If the intersection root is a document,
  146. // it’s the size of the document's viewport (note that this processing step can only be reached if the document is fully active).
  147. if (intersection_root.has<JS::Handle<DOM::Document>>()) {
  148. auto document = intersection_root.get<JS::Handle<DOM::Document>>();
  149. // Since the spec says that this is only reach if the document is fully active, that means it must have a navigable.
  150. VERIFY(document->navigable());
  151. // NOTE: This rect is the *size* of the viewport. The viewport *offset* is not relevant,
  152. // as intersections are computed using viewport-relative element rects.
  153. rect = CSSPixelRect { CSSPixelPoint { 0, 0 }, document->viewport_rect().size() };
  154. } else {
  155. VERIFY(intersection_root.has<JS::Handle<DOM::Element>>());
  156. auto element = intersection_root.get<JS::Handle<DOM::Element>>();
  157. // FIXME: Otherwise, if the intersection root has a content clip,
  158. // it’s the element’s content area.
  159. // Otherwise,
  160. // it’s the result of getting the bounding box for the intersection root.
  161. auto bounding_client_rect = element->get_bounding_client_rect();
  162. rect = CSSPixelRect(bounding_client_rect->x(), bounding_client_rect->y(), bounding_client_rect->width(), bounding_client_rect->height());
  163. }
  164. // FIXME: When calculating the root intersection rectangle for a same-origin-domain target, the rectangle is then
  165. // expanded according to the offsets in the IntersectionObserver’s [[rootMargin]] slot in a manner similar
  166. // to CSS’s margin property, with the four values indicating the amount the top, right, bottom, and left
  167. // edges, respectively, are offset by, with positive lengths indicating an outward offset. Percentages
  168. // are resolved relative to the width of the undilated rectangle.
  169. return rect;
  170. }
  171. void IntersectionObserver::queue_entry(Badge<DOM::Document>, JS::NonnullGCPtr<IntersectionObserverEntry> entry)
  172. {
  173. m_queued_entries.append(entry);
  174. }
  175. }