IntersectionObserver.cpp 9.3 KB

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