Skip to main content

script/dom/intersectionobserver/
intersectionobserver.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Cell, RefCell};
6use std::rc::Rc;
7use std::time::Duration;
8
9use app_units::Au;
10use cssparser::{Parser, ParserInput};
11use dom_struct::dom_struct;
12use euclid::{Rect, SideOffsets2D, Size2D, Vector2D};
13use js::context::{JSContext, NoGC};
14use js::rust::{HandleObject, MutableHandleValue};
15use script_bindings::cell::DomRefCell;
16use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
17use servo_base::cross_process_instant::CrossProcessInstant;
18use servo_geometry::f32_rect_to_au_rect;
19use style::parser::Parse;
20use style::stylesheets::CssRuleType;
21use style::values::computed::Overflow;
22use style::values::specified::intersection_observer::IntersectionObserverMargin;
23use style_traits::{CSSPixel, ParsingMode, ToCss};
24
25use crate::css::{ANONYMOUS_CONTENT_URL_DATA, parser_context_for_anonymous_content};
26use crate::dom::bindings::callback::ExceptionHandling;
27use crate::dom::bindings::codegen::Bindings::IntersectionObserverBinding::{
28    IntersectionObserverCallback, IntersectionObserverInit, IntersectionObserverMethods,
29};
30use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
31use crate::dom::bindings::codegen::UnionTypes::{DoubleOrDoubleSequence, ElementOrDocument};
32use crate::dom::bindings::error::{Error, Fallible};
33use crate::dom::bindings::inheritance::Castable;
34use crate::dom::bindings::num::Finite;
35use crate::dom::bindings::root::{Dom, DomRoot};
36use crate::dom::bindings::str::DOMString;
37use crate::dom::bindings::utils::to_frozen_array;
38use crate::dom::document::{Document, RenderingUpdateReason};
39use crate::dom::domrectreadonly::DOMRectReadOnly;
40use crate::dom::element::Element;
41use crate::dom::intersectionobserverentry::IntersectionObserverEntry;
42use crate::dom::node::{Node, NodeTraits};
43use crate::dom::window::Window;
44
45#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
46#[derive(JSTraceable, MallocSizeOf)]
47pub(crate) enum UnrootedElementOrDocument {
48    Element(Dom<Element>),
49    Document(Dom<Document>),
50}
51
52impl From<&ElementOrDocument> for UnrootedElementOrDocument {
53    fn from(value: &ElementOrDocument) -> Self {
54        match value {
55            ElementOrDocument::Document(document) => {
56                UnrootedElementOrDocument::Document(document.as_traced())
57            },
58            ElementOrDocument::Element(element) => {
59                UnrootedElementOrDocument::Element(element.as_traced())
60            },
61        }
62    }
63}
64
65impl From<&UnrootedElementOrDocument> for ElementOrDocument {
66    fn from(value: &UnrootedElementOrDocument) -> Self {
67        match value {
68            UnrootedElementOrDocument::Document(document) => {
69                ElementOrDocument::Document(document.as_rooted())
70            },
71            UnrootedElementOrDocument::Element(element) => {
72                ElementOrDocument::Element(element.as_rooted())
73            },
74        }
75    }
76}
77
78/// > The intersection root for an IntersectionObserver is the value of its root attribute if the attribute is non-null;
79/// > otherwise, it is the top-level browsing context’s document node, referred to as the implicit root.
80///
81/// <https://w3c.github.io/IntersectionObserver/#intersectionobserver-intersection-root>
82pub type IntersectionRoot = Option<UnrootedElementOrDocument>;
83
84/// The Intersection Observer interface
85///
86/// > The IntersectionObserver interface can be used to observe changes in the intersection
87/// > of an intersection root and one or more target Elements.
88///
89/// <https://w3c.github.io/IntersectionObserver/#intersection-observer-interface>
90#[dom_struct]
91pub(crate) struct IntersectionObserver {
92    reflector_: Reflector,
93
94    /// [`Document`] that should process this observer's observation steps.
95    /// Following Chrome and Firefox, it is the current document on construction.
96    /// <https://github.com/w3c/IntersectionObserver/issues/525>
97    owner_doc: Dom<Document>,
98
99    /// > The root provided to the IntersectionObserver constructor, or null if none was provided.
100    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-root>
101    root: IntersectionRoot,
102
103    /// > This callback will be invoked when there are changes to a target’s intersection
104    /// > with the intersection root, as per the processing model.
105    ///
106    /// <https://w3c.github.io/IntersectionObserver/#intersection-observer-callback>
107    #[conditional_malloc_size_of]
108    callback: Rc<IntersectionObserverCallback>,
109
110    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-queuedentries-slot>
111    queued_entries: DomRefCell<Vec<Dom<IntersectionObserverEntry>>>,
112
113    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-observationtargets-slot>
114    observation_targets: DomRefCell<Vec<Dom<Element>>>,
115
116    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin-slot>
117    #[no_trace]
118    #[ignore_malloc_size_of = "Defined in style"]
119    root_margin: RefCell<IntersectionObserverMargin>,
120
121    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-scrollmargin-slot>
122    #[no_trace]
123    #[ignore_malloc_size_of = "Defined in style"]
124    scroll_margin: RefCell<IntersectionObserverMargin>,
125
126    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-thresholds-slot>
127    thresholds: RefCell<Vec<Finite<f64>>>,
128
129    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-delay-slot>
130    delay: Cell<i32>,
131
132    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-trackvisibility-slot>
133    track_visibility: Cell<bool>,
134
135    /// Whether or not this [`IntersectionObserver`] is connected to its owning [`Document`].
136    connected_to_document: Cell<bool>,
137}
138
139impl IntersectionObserver {
140    fn new_inherited(
141        window: &Window,
142        callback: Rc<IntersectionObserverCallback>,
143        root: &Option<ElementOrDocument>,
144        root_margin: IntersectionObserverMargin,
145        scroll_margin: IntersectionObserverMargin,
146    ) -> Self {
147        Self {
148            reflector_: Reflector::new(),
149            owner_doc: window.Document().as_traced(),
150            root: root.as_ref().map(|root| root.into()),
151            callback,
152            queued_entries: Default::default(),
153            observation_targets: Default::default(),
154            root_margin: RefCell::new(root_margin),
155            scroll_margin: RefCell::new(scroll_margin),
156            thresholds: Default::default(),
157            delay: Default::default(),
158            track_visibility: Default::default(),
159            connected_to_document: Cell::new(false),
160        }
161    }
162
163    /// <https://w3c.github.io/IntersectionObserver/#initialize-new-intersection-observer>
164    fn new(
165        cx: &mut JSContext,
166        window: &Window,
167        proto: Option<HandleObject>,
168        callback: Rc<IntersectionObserverCallback>,
169        init: &IntersectionObserverInit,
170    ) -> Fallible<DomRoot<Self>> {
171        // Step 3.
172        // > Attempt to parse a margin from options.rootMargin. If a list is returned,
173        // > set this’s internal [[rootMargin]] slot to that. Otherwise, throw a SyntaxError exception.
174        let root_margin = if let Ok(margin) = parse_a_margin(init.rootMargin.as_ref()) {
175            margin
176        } else {
177            return Err(Error::Syntax(None));
178        };
179
180        // Step 4.
181        // > Attempt to parse a margin from options.scrollMargin. If a list is returned,
182        // > set this’s internal [[scrollMargin]] slot to that. Otherwise, throw a SyntaxError exception.
183        let scroll_margin = if let Ok(margin) = parse_a_margin(init.scrollMargin.as_ref()) {
184            margin
185        } else {
186            return Err(Error::Syntax(None));
187        };
188
189        // Step 1 and step 2, 3, 4 setter
190        // > 1. Let this be a new IntersectionObserver object
191        // > 2. Set this’s internal [[callback]] slot to callback.
192        // > 3. ... set this’s internal [[rootMargin]] slot to that.
193        // > 4. ... set this’s internal [[scrollMargin]] slot to that.
194        let observer = reflect_dom_object_with_proto(
195            cx,
196            Box::new(Self::new_inherited(
197                window,
198                callback,
199                &init.root,
200                root_margin,
201                scroll_margin,
202            )),
203            window,
204            proto,
205        );
206
207        // Step 5-13
208        observer.init_observer(init)?;
209
210        Ok(observer)
211    }
212
213    /// Step 5-13 of <https://w3c.github.io/IntersectionObserver/#initialize-new-intersection-observer>
214    fn init_observer(&self, init: &IntersectionObserverInit) -> Fallible<()> {
215        // Step 5
216        // > Let thresholds be a list equal to options.threshold.
217        //
218        // Non-sequence value should be converted into Vec.
219        // Default value of thresholds is [0].
220        let mut thresholds = match &init.threshold {
221            Some(DoubleOrDoubleSequence::Double(num)) => vec![*num],
222            Some(DoubleOrDoubleSequence::DoubleSequence(sequence)) => sequence.clone(),
223            None => vec![Finite::wrap(0.)],
224        };
225
226        // Step 6
227        // > If any value in thresholds is less than 0.0 or greater than 1.0, throw a RangeError exception.
228        for num in &thresholds {
229            if **num < 0.0 || **num > 1.0 {
230                return Err(Error::Range(
231                    c"Value in thresholds should not be less than 0.0 or greater than 1.0"
232                        .to_owned(),
233                ));
234            }
235        }
236
237        // Step 7
238        // > Sort thresholds in ascending order.
239        thresholds.sort_by(|lhs, rhs| lhs.partial_cmp(&**rhs).unwrap());
240
241        // Step 8
242        // > If thresholds is empty, append 0 to thresholds.
243        if thresholds.is_empty() {
244            thresholds.push(Finite::wrap(0.));
245        }
246
247        // Step 9
248        // > The thresholds attribute getter will return this sorted thresholds list.
249        //
250        // Set this internal [[thresholds]] slot to the sorted thresholds list
251        // and getter will return the internal [[thresholds]] slot.
252        self.thresholds.replace(thresholds);
253
254        // Step 10
255        // > Let delay be the value of options.delay.
256        //
257        // Default value of delay is 0.
258        let mut delay = init.delay.unwrap_or(0);
259
260        // Step 11
261        // > If options.trackVisibility is true and delay is less than 100, set delay to 100.
262        //
263        // In Chromium, the minimum delay required is 100 milliseconds for observation that consider trackVisibilty.
264        // Currently, visibility is not implemented.
265        if init.trackVisibility {
266            delay = delay.max(100);
267        }
268
269        // Step 12
270        // > Set this’s internal [[delay]] slot to options.delay to delay.
271        self.delay.set(delay);
272
273        // Step 13
274        // > Set this’s internal [[trackVisibility]] slot to options.trackVisibility.
275        self.track_visibility.set(init.trackVisibility);
276
277        Ok(())
278    }
279
280    /// <https://w3c.github.io/IntersectionObserver/#observe-target-element>
281    fn observe_target_element(&self, target: &Element, no_gc: &NoGC) {
282        // Step 1
283        // > If target is in observer’s internal [[ObservationTargets]] slot, return.
284        let is_present = self
285            .observation_targets
286            .borrow()
287            .iter()
288            .any(|element| &**element == target);
289        if is_present {
290            return;
291        }
292
293        // Step 2
294        // > Let intersectionObserverRegistration be an IntersectionObserverRegistration record with
295        // > an observer property set to observer, a previousThresholdIndex property set to -1,
296        // > a previousIsIntersecting property set to false, and a previousIsVisible property set to false.
297        // Step 3
298        // > Append intersectionObserverRegistration to target’s internal [[RegisteredIntersectionObservers]] slot.
299        target.add_initial_intersection_observer_registration(self, no_gc);
300
301        if self.observation_targets.borrow().is_empty() {
302            self.connect_to_owner();
303        }
304
305        // Step 4
306        // > Add target to observer’s internal [[ObservationTargets]] slot.
307        self.observation_targets
308            .borrow_mut()
309            .push(Dom::from_ref(target));
310
311        target
312            .owner_window()
313            .Document()
314            .add_rendering_update_reason(
315                RenderingUpdateReason::IntersectionObserverStartedObservingTarget,
316            );
317    }
318
319    /// <https://w3c.github.io/IntersectionObserver/#unobserve-target-element>
320    fn unobserve_target_element(&self, target: &Element, no_gc: &NoGC) {
321        // Step 1
322        // > Remove the IntersectionObserverRegistration record whose observer property is equal to
323        // > this from target’s internal [[RegisteredIntersectionObservers]] slot, if present.
324        target
325            .registered_intersection_observers_mut(no_gc)
326            .retain(|registration| &*registration.observer != self);
327
328        // Step 2
329        // > Remove target from this’s internal [[ObservationTargets]] slot, if present
330        self.observation_targets
331            .borrow_mut()
332            .retain(|element| &**element != target);
333
334        // Should disconnect from owner if it is not observing anything.
335        if self.observation_targets.borrow().is_empty() {
336            self.disconnect_from_owner();
337        }
338    }
339
340    /// <https://w3c.github.io/IntersectionObserver/#queue-an-intersectionobserverentry>
341    #[allow(clippy::too_many_arguments)]
342    fn queue_an_intersectionobserverentry(
343        &self,
344        cx: &mut JSContext,
345        document: &Document,
346        time: CrossProcessInstant,
347        root_bounds: Rect<Au, CSSPixel>,
348        bounding_client_rect: Rect<Au, CSSPixel>,
349        intersection_rect: Rect<Au, CSSPixel>,
350        is_intersecting: bool,
351        is_visible: bool,
352        intersection_ratio: f64,
353        target: &Element,
354    ) {
355        let mut rect_to_domrectreadonly = |rect: Rect<Au, CSSPixel>| {
356            DOMRectReadOnly::new(
357                cx,
358                self.owner_doc.window().as_global_scope(),
359                None,
360                rect.origin.x.to_f64_px(),
361                rect.origin.y.to_f64_px(),
362                rect.size.width.to_f64_px(),
363                rect.size.height.to_f64_px(),
364            )
365        };
366
367        let root_bounds = rect_to_domrectreadonly(root_bounds);
368        let bounding_client_rect = rect_to_domrectreadonly(bounding_client_rect);
369        let intersection_rect = rect_to_domrectreadonly(intersection_rect);
370
371        // Step 1. Construct an IntersectionObserverEntry, passing in time, rootBounds,
372        // >    boundingClientRect, intersectionRect, isIntersecting, and target.
373        let time = document
374            .owner_global()
375            .performance(cx)
376            .to_dom_high_res_time_stamp(time);
377        let entry = IntersectionObserverEntry::new(
378            cx,
379            self.owner_doc.window(),
380            None,
381            time,
382            Some(&root_bounds),
383            &bounding_client_rect,
384            &intersection_rect,
385            is_intersecting,
386            is_visible,
387            Finite::wrap(intersection_ratio),
388            target,
389        );
390
391        // Step 2. Append it to observer's internal [[QueuedEntries]] slot.
392        self.queued_entries.borrow_mut().push(entry.as_traced());
393
394        // Step 3. Queue an intersection observer task for document.
395        document.queue_an_intersection_observer_task();
396    }
397
398    /// Step 3.1-3.5 of <https://w3c.github.io/IntersectionObserver/#notify-intersection-observers-algo>
399    pub(crate) fn invoke_callback_if_necessary(&self, cx: &mut js::context::JSContext) {
400        // Step 1
401        // > If observer’s internal [[QueuedEntries]] slot is empty, continue.
402        if self.queued_entries.borrow().is_empty() {
403            return;
404        }
405
406        // Step 2-3
407        // We trivially moved the entries and root them.
408        let queued_entries = self
409            .queued_entries
410            .take()
411            .iter_mut()
412            .map(|entry| entry.as_rooted())
413            .collect();
414
415        // Step 4-5
416        let _ = self
417            .callback
418            .Call_(cx, self, queued_entries, self, ExceptionHandling::Report);
419    }
420
421    /// Connect the observer itself into owner doc if it is unconnected.
422    /// If the [`IntersectionObserver`] is already connected, do nothing.
423    fn connect_to_owner(&self) {
424        if !self.connected_to_document.get() {
425            self.owner_doc.add_intersection_observer(self);
426            self.connected_to_document.set(true);
427        }
428    }
429
430    /// Disconnect the observer itself from owner doc.
431    /// If not connected to a [`Document`], do nothing.
432    fn disconnect_from_owner(&self) {
433        if self.connected_to_document.get() {
434            self.owner_doc.remove_intersection_observer(self);
435        }
436    }
437
438    /// <https://w3c.github.io/IntersectionObserver/#ref-for-intersectionobserver-content-clip>
439    /// An Element is defined as having a content clip if its computed style has overflow properties
440    /// that cause its content to be clipped to the element’s padding edge.
441    // TODO: this is not clear for `overflow: clip` since it is clipped based on overflow clip rect.
442    fn has_content_clip(element: &Element) -> bool {
443        element
444            .upcast::<Node>()
445            .effective_overflow_without_reflow()
446            .is_some_and(|overflow_axes| {
447                overflow_axes.x != Overflow::Visible || overflow_axes.y != Overflow::Visible
448            })
449    }
450
451    /// > The root intersection rectangle for an IntersectionObserver is
452    /// > the rectangle we’ll use to check against the targets.
453    ///
454    /// <https://w3c.github.io/IntersectionObserver/#intersectionobserver-root-intersection-rectangle>
455    pub(crate) fn root_intersection_rectangle(&self) -> Option<Rect<Au, CSSPixel>> {
456        let intersection_rectangle = match self.concrete_root() {
457            // Handle if root is an element.
458            Some(ElementOrDocument::Element(element)) => {
459                // TODO: recheck scrollbar approach and clip-path clipping from Chromium implementation.
460                if IntersectionObserver::has_content_clip(&element) {
461                    // > Otherwise, if the intersection root has a content clip, it’s the element’s padding area.
462                    element.upcast::<Node>().padding_box_without_reflow()
463                } else {
464                    // > Otherwise, it’s the result of getting the bounding box for the intersection root.
465                    element.upcast::<Node>().border_box_without_reflow()
466                }
467            },
468            // Handle if root is a Document, which includes implicit root and explicit Document root.
469            Some(ElementOrDocument::Document(document)) => {
470                // > If the intersection root is a document, it’s the size of the document's viewport
471                // > (note that this processing step can only be reached if the document is fully active).
472                // TODO: viewport should consider native scrollbar if exist. Recheck Servo's scrollbar approach.
473                let viewport = document.window().viewport_details().size;
474                Some(Rect::from_size(Size2D::new(
475                    Au::from_f32_px(viewport.width),
476                    Au::from_f32_px(viewport.height),
477                )))
478            },
479            None => None,
480        };
481
482        // > When calculating the root intersection rectangle for a same-origin-domain target,
483        // > the rectangle is then expanded according to the offsets in the IntersectionObserver’s
484        // > [[rootMargin]] slot in a manner similar to CSS’s margin property, with the four values
485        // > indicating the amount the top, right, bottom, and left edges, respectively, are offset by,
486        // > with positive lengths indicating an outward offset. Percentages are resolved relative to
487        // > the width of the undilated rectangle.
488        // TODO(stevennovaryo): add check for same-origin-domain
489        intersection_rectangle.map(|intersection_rectangle| {
490            let margin = Self::resolve_percentages_with_basis(
491                &self.root_margin.borrow(),
492                intersection_rectangle,
493            );
494            intersection_rectangle.outer_rect(margin)
495        })
496    }
497
498    /// Return root or try to get the top-level browsing context document in case if this is a implicit root.
499    /// <https://w3c.github.io/IntersectionObserver/#intersectionobserver-intersection-root>
500    // TODO: Currently we are unable to get the cross `ScriptThread` document.
501    fn concrete_root(&self) -> Option<ElementOrDocument> {
502        match &self.root {
503            Some(root) => Some(root.into()),
504            None => self
505                .owner_doc
506                .window()
507                .top_level_document_if_local()
508                .map(ElementOrDocument::Document),
509        }
510    }
511
512    /// Step 2.2.4-2.2.21 of <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>
513    ///
514    /// If some conditions require to skips "processing further", we will skips those steps and
515    /// return default values conformant to step 2.2.4. See [`IntersectionObservationOutput::default_skipped`].
516    ///
517    /// Note that current draft specs skipped wrong steps, as it should skip computing fields that
518    /// would result in different intersection entry other than the default entry per published spec.
519    /// <https://www.w3.org/TR/intersection-observer/>
520    fn maybe_compute_intersection_output(
521        &self,
522        target: &Element,
523        maybe_root_bounds: Option<Rect<Au, CSSPixel>>,
524    ) -> IntersectionObservationOutput {
525        // Step 5
526        // > If the intersection root is not the implicit root, and target is not in
527        // > the same document as the intersection root, skip to step 11.
528        // Step 6
529        // > If the intersection root is an Element, and target is not a descendant of
530        // > the intersection root in the containing block chain, skip to step 11.
531        match &self.root {
532            Some(UnrootedElementOrDocument::Document(document))
533                if document.as_rooted() != target.owner_document() =>
534            {
535                return IntersectionObservationOutput::default_skipped();
536            },
537            Some(UnrootedElementOrDocument::Element(element)) => {
538                // To ensure consistency, we also check for elements right now, but we can depend on the
539                // layout query later.
540                if element.owner_document() != target.owner_document() {
541                    return IntersectionObservationOutput::default_skipped();
542                }
543                if !element
544                    .owner_window()
545                    .is_containing_block_descendant_query_without_reflow(
546                        element.upcast(),
547                        target.upcast(),
548                    )
549                {
550                    return IntersectionObservationOutput::default_skipped();
551                }
552            },
553            _ => {},
554        }
555
556        // Step 7
557        // > Set targetRect to the DOMRectReadOnly obtained by getting the bounding box for target.
558        let maybe_target_rect = target.upcast::<Node>().border_box_without_reflow();
559
560        // Following the implementation of Gecko, we will skip further processing if these
561        // information not available. This would also handle display none element.
562        let (Some(root_bounds), Some(target_rect), Some(root_intersection)) =
563            (maybe_root_bounds, maybe_target_rect, self.concrete_root())
564        else {
565            return IntersectionObservationOutput::default_skipped();
566        };
567
568        // TODO(stevennovaryo): we should probably also consider adding visibity check, ideally
569        //                      it would require new query from LayoutThread.
570
571        // Step 8
572        // > Let intersectionRect be the result of running the compute the intersection algorithm on
573        // > target and observer’s intersection root.
574        let maybe_intersection_rect = compute_the_intersection(
575            target,
576            &root_intersection,
577            root_bounds,
578            target_rect,
579            &self.scroll_margin.borrow(),
580        );
581        let intersection_rect = maybe_intersection_rect.unwrap_or_default();
582
583        // Step 9
584        // > Let targetArea be targetRect’s area.
585        // Step 10
586        // > Let intersectionArea be intersectionRect’s area.
587        // These steps are folded in Step 12, rewriting (w1 * h1) / (w2 * h2) as (w1 / w2) * (h1 / h2)
588        // to avoid multiplication overflows.
589
590        // Step 11
591        // > Let isIntersecting be true if targetRect and rootBounds intersect or are edge-adjacent,
592        // > even if the intersection has zero area (because rootBounds or targetRect have zero area).
593        // Because we are considering edge-adjacent, instead of checking whether the rectangle is empty,
594        // we are checking whether the rectangle is negative or not.
595        let is_intersecting = maybe_intersection_rect.is_some();
596
597        // Step 12
598        // > If targetArea is non-zero, let intersectionRatio be intersectionArea divided by targetArea.
599        // > Otherwise, let intersectionRatio be 1 if isIntersecting is true, or 0 if isIntersecting is false.
600        let intersection_ratio = if target_rect.size.width.0 == 0 || target_rect.size.height.0 == 0
601        {
602            is_intersecting.into()
603        } else {
604            (intersection_rect.size.width.0 as f64 / target_rect.size.width.0 as f64) *
605                (intersection_rect.size.height.0 as f64 / target_rect.size.height.0 as f64)
606        };
607
608        // Step 13
609        // > Set thresholdIndex to the index of the first entry in observer.thresholds whose value is
610        // > greater than intersectionRatio, or the length of observer.thresholds if intersectionRatio is
611        // > greater than or equal to the last entry in observer.thresholds.
612        let threshold_index = self
613            .thresholds
614            .borrow()
615            .iter()
616            .position(|threshold| **threshold > intersection_ratio)
617            .unwrap_or(self.thresholds.borrow().len());
618
619        // If the index is 0, the first threshold value is greater
620        // than the observed ratio, so we're not actually matching yet.
621        // The spec differentiates between this case and the case where
622        // there is no intersection, but other browser engines do not.
623        let threshold_index = if is_intersecting && threshold_index > 0 {
624            ThresholdIndex::Matching(threshold_index)
625        } else {
626            ThresholdIndex::NotMatching
627        };
628
629        // Step 14
630        // > Let isVisible be the result of running the visibility algorithm on target.
631        // TODO: Implement visibility algorithm
632        let is_visible = false;
633
634        // We never report isIntersecting as true unless we have exceeded a threshold,
635        // which matches other browser eengines.
636        // See https://github.com/w3c/IntersectionObserver/issues/432 for background.
637        let is_intersecting = matches!(threshold_index, ThresholdIndex::Matching(..));
638
639        IntersectionObservationOutput::new_computed(
640            threshold_index,
641            is_intersecting,
642            target_rect,
643            intersection_rect,
644            intersection_ratio,
645            is_visible,
646            root_bounds,
647        )
648    }
649
650    /// Step 2.2.1-2.2.21 of <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>
651    pub(crate) fn update_intersection_observations_steps(
652        &self,
653        cx: &mut JSContext,
654        document: &Document,
655        time: CrossProcessInstant,
656        root_bounds: Option<Rect<Au, CSSPixel>>,
657    ) {
658        for target in &*self.observation_targets.borrow() {
659            // Step 1
660            // > Let registration be the IntersectionObserverRegistration record in target’s internal
661            // > [[RegisteredIntersectionObservers]] slot whose observer property is equal to observer.
662            let registration = target.get_intersection_observer_registration(self).unwrap();
663
664            // Step 2
665            // > If (time - registration.lastUpdateTime < observer.delay), skip further processing for target.
666            if time - registration.last_update_time.get() <
667                Duration::from_millis(self.delay.get().max(0) as u64)
668            {
669                return;
670            }
671
672            // Step 3
673            // > Set registration.lastUpdateTime to time.
674            registration.last_update_time.set(time);
675
676            // step 4-14
677            let intersection_output = self.maybe_compute_intersection_output(target, root_bounds);
678
679            // Step 15-17
680            // > 15. Let previousThresholdIndex be the registration’s previousThresholdIndex property.
681            // > 16. Let previousIsIntersecting be the registration’s previousIsIntersecting property.
682            // > 17. Let previousIsVisible be the registration’s previousIsVisible property.
683            let previous_threshold_index = registration.previous_threshold_index.get();
684            let previous_is_intersecting = registration.previous_is_intersecting.get();
685            let previous_is_visible = registration.previous_is_visible.get();
686
687            // Step 18
688            // > If thresholdIndex does not equal previousThresholdIndex, or
689            // > if isIntersecting does not equal previousIsIntersecting, or
690            // > if isVisible does not equal previousIsVisible,
691            // > queue an IntersectionObserverEntry, passing in observer, time, rootBounds,
692            // > targetRect, intersectionRect, isIntersecting, isVisible, and target.
693            if Some(intersection_output.threshold_index) != previous_threshold_index ||
694                intersection_output.is_intersecting != previous_is_intersecting ||
695                intersection_output.is_visible != previous_is_visible
696            {
697                // TODO(stevennovaryo): Per IntersectionObserverEntry interface, the rootBounds
698                //                      should be null for cross-origin-domain target.
699                self.queue_an_intersectionobserverentry(
700                    cx,
701                    document,
702                    time,
703                    intersection_output.root_bounds,
704                    intersection_output.target_rect,
705                    intersection_output.intersection_rect,
706                    intersection_output.is_intersecting,
707                    intersection_output.is_visible,
708                    intersection_output.intersection_ratio,
709                    target,
710                );
711            }
712
713            // Step 19-21
714            // > 19. Assign thresholdIndex to registration’s previousThresholdIndex property.
715            // > 20. Assign isIntersecting to registration’s previousIsIntersecting property.
716            // > 21. Assign isVisible to registration’s previousIsVisible property.
717            registration
718                .previous_threshold_index
719                .set(Some(intersection_output.threshold_index));
720            registration
721                .previous_is_intersecting
722                .set(intersection_output.is_intersecting);
723            registration
724                .previous_is_visible
725                .set(intersection_output.is_visible);
726        }
727    }
728
729    fn resolve_percentages_with_basis(
730        margin: &IntersectionObserverMargin,
731        containing_block: Rect<Au, CSSPixel>,
732    ) -> SideOffsets2D<Au, CSSPixel> {
733        let inner = &margin.0;
734        SideOffsets2D::new(
735            inner.0.to_used_value(containing_block.height()),
736            inner.1.to_used_value(containing_block.width()),
737            inner.2.to_used_value(containing_block.height()),
738            inner.3.to_used_value(containing_block.width()),
739        )
740    }
741}
742
743impl IntersectionObserverMethods<crate::DomTypeHolder> for IntersectionObserver {
744    /// > The root provided to the IntersectionObserver constructor, or null if none was provided.
745    ///
746    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-root>
747    fn GetRoot(&self) -> Option<ElementOrDocument> {
748        self.root.as_ref().map(|root| root.into())
749    }
750
751    /// > Offsets applied to the root intersection rectangle, effectively growing or
752    /// > shrinking the box that is used to calculate intersections. These offsets are only
753    /// > applied when handling same-origin-domain targets; for cross-origin-domain targets
754    /// > they are ignored.
755    ///
756    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin>
757    fn RootMargin(&self) -> DOMString {
758        self.root_margin.borrow().to_css_string().into()
759    }
760
761    /// > Offsets are applied to scrollports on the path from intersection root to target,
762    /// > effectively growing or shrinking the clip rects used to calculate intersections.
763    ///
764    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-scrollmargin>
765    fn ScrollMargin(&self) -> DOMString {
766        self.scroll_margin.borrow().to_css_string().into()
767    }
768
769    /// > A list of thresholds, sorted in increasing numeric order, where each threshold
770    /// > is a ratio of intersection area to bounding box area of an observed target.
771    /// > Notifications for a target are generated when any of the thresholds are crossed
772    /// > for that target. If no options.threshold was provided to the IntersectionObserver
773    /// > constructor, or the sequence is empty, the value of this attribute will be `[0]`.
774    ///
775    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-thresholds>
776    fn Thresholds(&self, cx: &mut JSContext, retval: MutableHandleValue) {
777        to_frozen_array(cx, &self.thresholds.borrow(), retval);
778    }
779
780    /// > A number indicating the minimum delay in milliseconds between notifications from
781    /// > this observer for a given target.
782    ///
783    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-delay>
784    fn Delay(&self) -> i32 {
785        self.delay.get()
786    }
787
788    /// > A boolean indicating whether this IntersectionObserver will track changes in a target’s visibility.
789    ///
790    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-trackvisibility>
791    fn TrackVisibility(&self) -> bool {
792        self.track_visibility.get()
793    }
794
795    /// > Run the observe a target Element algorithm, providing this and target.
796    ///
797    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-observe>
798    fn Observe(&self, no_gc: &NoGC, target: &Element) {
799        self.observe_target_element(target, no_gc);
800    }
801
802    /// > Run the unobserve a target Element algorithm, providing this and target.
803    ///
804    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-unobserve>
805    fn Unobserve(&self, no_gc: &NoGC, target: &Element) {
806        self.unobserve_target_element(target, no_gc);
807    }
808
809    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-disconnect>
810    fn Disconnect(&self, no_gc: &NoGC) {
811        // > For each target in this’s internal [[ObservationTargets]] slot:
812        self.observation_targets.borrow().iter().for_each(|target| {
813            // > 1. Remove the IntersectionObserverRegistration record whose observer property is equal to
814            // >    this from target’s internal [[RegisteredIntersectionObservers]] slot.
815            target.remove_intersection_observer(self, no_gc);
816        });
817        // > 2. Remove target from this’s internal [[ObservationTargets]] slot.
818        self.observation_targets.borrow_mut().clear();
819
820        // We should remove this observer from the event loop.
821        self.disconnect_from_owner();
822    }
823
824    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-takerecords>
825    fn TakeRecords(&self) -> Vec<DomRoot<IntersectionObserverEntry>> {
826        // Step 1-3.
827        self.queued_entries
828            .take()
829            .iter()
830            .map(|entry| entry.as_rooted())
831            .collect()
832    }
833
834    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-intersectionobserver>
835    fn Constructor(
836        cx: &mut JSContext,
837        window: &Window,
838        proto: Option<HandleObject>,
839        callback: Rc<IntersectionObserverCallback>,
840        init: &IntersectionObserverInit,
841    ) -> Fallible<DomRoot<IntersectionObserver>> {
842        Self::new(cx, window, proto, callback, init)
843    }
844}
845
846#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
847enum ThresholdIndex {
848    NotMatching,
849    Matching(usize),
850}
851
852/// <https://w3c.github.io/IntersectionObserver/#intersectionobserverregistration>
853#[derive(Clone, JSTraceable, MallocSizeOf)]
854#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
855pub(crate) struct IntersectionObserverRegistration {
856    pub(crate) observer: Dom<IntersectionObserver>,
857    previous_threshold_index: Cell<Option<ThresholdIndex>>,
858    previous_is_intersecting: Cell<bool>,
859    #[no_trace]
860    last_update_time: Cell<CrossProcessInstant>,
861    previous_is_visible: Cell<bool>,
862}
863
864impl IntersectionObserverRegistration {
865    /// Initial value of [`IntersectionObserverRegistration`] according to
866    /// step 2 of <https://w3c.github.io/IntersectionObserver/#observe-target-element>.
867    /// > Let intersectionObserverRegistration be an IntersectionObserverRegistration record with
868    /// > an observer property set to observer, a previousThresholdIndex property set to -1,
869    /// > a previousIsIntersecting property set to false, and a previousIsVisible property set to false.
870    pub(crate) fn new_initial(observer: &IntersectionObserver) -> Self {
871        IntersectionObserverRegistration {
872            observer: Dom::from_ref(observer),
873            previous_threshold_index: Cell::new(None),
874            previous_is_intersecting: Cell::new(false),
875            last_update_time: Cell::new(CrossProcessInstant::epoch()),
876            previous_is_visible: Cell::new(false),
877        }
878    }
879}
880
881/// <https://w3c.github.io/IntersectionObserver/#parse-a-margin>
882fn parse_a_margin(value: Option<&DOMString>) -> Result<IntersectionObserverMargin, ()> {
883    // <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserverinit-rootmargin> &&
884    // <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserverinit-scrollmargin>
885    // > ... defaulting to "0px".
886    let value = match value {
887        Some(str) => &str.str(),
888        _ => "0px",
889    };
890
891    // Create necessary style ParserContext and utilize stylo's IntersectionObserverMargin
892    let mut input = ParserInput::new(value);
893    let mut parser = Parser::new(&mut input);
894
895    let context = parser_context_for_anonymous_content(
896        CssRuleType::Style,
897        ParsingMode::DEFAULT,
898        &ANONYMOUS_CONTENT_URL_DATA,
899    );
900
901    parser
902        .parse_entirely(|p| IntersectionObserverMargin::parse(&context, p))
903        .map_err(|_| ())
904}
905
906/// In terms of intersection observer, we consider zero-area rectangles as long as the area is not negative.
907fn intersect_rectangle(
908    lhs: &Rect<Au, CSSPixel>,
909    rhs: &Rect<Au, CSSPixel>,
910) -> Option<Rect<Au, CSSPixel>> {
911    let box_result = lhs.to_box2d().intersection_unchecked(&rhs.to_box2d());
912    if box_result.is_negative() {
913        None
914    } else {
915        Some(box_result.to_rect())
916    }
917}
918
919/// Compute the intersection rectangle of the target [`Element`] returning the results of intersection in the coordinate
920/// space of the target's owning [`Document`]. Additionally, we assume that both the target and the root is connected.
921/// <https://w3c.github.io/IntersectionObserver/#compute-the-intersection>
922fn compute_the_intersection(
923    target: &Element,
924    root: &ElementOrDocument,
925    root_bounds: Rect<Au, CSSPixel>,
926    mut intersection_rect: Rect<Au, CSSPixel>,
927    scroll_margin: &IntersectionObserverMargin,
928) -> Option<Rect<Au, CSSPixel>> {
929    // > 1. Let intersectionRect be the result of getting the bounding box for target.
930    // We had delegated the computation of this to the caller of the function.
931
932    // > 2. Let container be the containing block of target.
933    let mut container = match target
934        .upcast::<Node>()
935        .containing_block_node_without_reflow()
936    {
937        Some(node) => ElementOrDocument::Element(DomRoot::downcast(node).unwrap()),
938        None => ElementOrDocument::Document(target.owner_document()),
939    };
940
941    // Total offsets gained from traversing through multiple navigables. We use this to map the coordinate space.
942    // TODO: We should store the product sum of transformation matrices instead. But this should be enough to handle
943    // scrolling, simple translation, and offset from containing block.
944    let mut total_inter_document_offset = Vector2D::zero();
945
946    // > 3. While container is not root:
947    while container != *root {
948        let containing_element = match container {
949            ElementOrDocument::Document(ref containing_document) => {
950                // > 3.1. If container is the document of a nested browsing context, update intersectionRect by clipping
951                // >      to the viewport of the document, and update container to be the browsing context container of container.
952                if let Some(frame_container) = containing_document
953                    .browsing_context()
954                    .and_then(|window| window.frame_element().map(DomRoot::from_ref))
955                {
956                    let viewport_rect = f32_rect_to_au_rect(Rect::from_size(
957                        containing_document.window().viewport_details().size,
958                    ));
959
960                    intersection_rect = intersect_rectangle(&intersection_rect, &viewport_rect)?;
961
962                    let current_offset = frame_container
963                        .upcast::<Node>()
964                        .padding_box()
965                        .unwrap()
966                        .origin
967                        .to_vector();
968                    intersection_rect.origin += current_offset;
969                    total_inter_document_offset += current_offset;
970
971                    frame_container
972                } else {
973                    // TODO: Theoritically, this shouldn't be reachable as we have ensured that the root is reachable
974                    // in the previous steps. But we are still unable to iterate through cross-origin ancestor iframes,
975                    // and we will need to stop the iteration for that case.
976                    break;
977                }
978            },
979            ElementOrDocument::Element(ref root) => root.clone(),
980        };
981
982        // > 3.2. Map intersectionRect to the coordinate space of container.
983        // TODO(#35767): We don't map the coordinate space per each iteration yet, instead all the rectangles are
984        // in the viewport coordinate space. But this would cause the scroll margin calculation to be inaccurate
985        // with respect to transforms.
986
987        // > 3.3. If container is a scroll container, apply the IntersectionObserver’s [[scrollMargin]]
988        // >      to the container’s clip rect as described in apply scroll margin to a scrollport.
989        // > 3.4. If container has a content clip or a css clip-path property, update intersectionRect
990        // >      by applying container’s clip.
991        // TODO(#35767): handle `overflow: clip` and resolve clipping for x-axis and y-axis independently.
992        // Additionally, handle css `clip-path` as well.
993        if IntersectionObserver::has_content_clip(&containing_element) &&
994            let Some(container_padding_box) = containing_element
995                .upcast::<Node>()
996                .padding_box_without_reflow()
997        {
998            let container_padding_box =
999                if containing_element.establishes_scroll_container_without_reflow() {
1000                    let margin = IntersectionObserver::resolve_percentages_with_basis(
1001                        scroll_margin,
1002                        container_padding_box,
1003                    );
1004                    container_padding_box.outer_rect(margin)
1005                } else {
1006                    container_padding_box
1007                };
1008
1009            intersection_rect = intersect_rectangle(&intersection_rect, &container_padding_box)?;
1010        }
1011
1012        // > 3.5. If container is the root element of a browsing context, update container to be the
1013        // >      browsing context’s document; otherwise, update container to be the containing block
1014        // >      of container.
1015        // Additionally, for a node that doesn't have an element that establishes its containing block, we should
1016        // refer to the browsing context's document.
1017        container = match containing_element
1018            .upcast::<Node>()
1019            .containing_block_node_without_reflow()
1020            .and_then(DomRoot::downcast::<Element>)
1021        {
1022            Some(element) => ElementOrDocument::Element(element),
1023            None => ElementOrDocument::Document(containing_element.owner_document()),
1024        };
1025    }
1026
1027    // Step 4
1028    // > Map intersectionRect to the coordinate space of root.
1029    // TODO(#35767): we don't map the coordinate space per each iteration yet, instead all the rectangles are
1030    // in the viewport coordinate space.
1031
1032    // Step 5
1033    // > Update intersectionRect by intersecting it with the root intersection rectangle.
1034    intersection_rect = intersect_rectangle(&intersection_rect, &root_bounds)?;
1035
1036    // Step 6
1037    // > Map intersectionRect to the coordinate space of the viewport of the document containing target.
1038    // Offset the intersectionRect back to the coordinate space of target's document.
1039    intersection_rect.origin -= total_inter_document_offset;
1040
1041    // Step 7
1042    // > Return intersectionRect.
1043    Some(intersection_rect)
1044}
1045
1046/// The values from computing step 2.2.4-2.2.14 in
1047/// <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>.
1048/// See [`IntersectionObserver::maybe_compute_intersection_output`].
1049struct IntersectionObservationOutput {
1050    pub(crate) threshold_index: ThresholdIndex,
1051    pub(crate) is_intersecting: bool,
1052    pub(crate) target_rect: Rect<Au, CSSPixel>,
1053    pub(crate) intersection_rect: Rect<Au, CSSPixel>,
1054    pub(crate) intersection_ratio: f64,
1055    pub(crate) is_visible: bool,
1056
1057    /// The root intersection rectangle [`IntersectionObserver::root_intersection_rectangle`].
1058    /// If the processing is skipped, computation should report the default zero value.
1059    pub(crate) root_bounds: Rect<Au, CSSPixel>,
1060}
1061
1062impl IntersectionObservationOutput {
1063    /// Default values according to
1064    /// <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>.
1065    /// Step 4.
1066    /// > Let:
1067    /// > - thresholdIndex be 0.
1068    /// > - isIntersecting be false.
1069    /// > - targetRect be a DOMRectReadOnly with x, y, width, and height set to 0.
1070    /// > - intersectionRect be a DOMRectReadOnly with x, y, width, and height set to 0.
1071    ///
1072    /// For fields that the default values is not directly mentioned, the values conformant
1073    /// to current browser implementation or WPT test is used instead.
1074    fn default_skipped() -> Self {
1075        Self {
1076            threshold_index: ThresholdIndex::NotMatching,
1077            is_intersecting: false,
1078            target_rect: Rect::zero(),
1079            intersection_rect: Rect::zero(),
1080            intersection_ratio: 0.,
1081            is_visible: false,
1082            root_bounds: Rect::zero(),
1083        }
1084    }
1085
1086    fn new_computed(
1087        threshold_index: ThresholdIndex,
1088        is_intersecting: bool,
1089        target_rect: Rect<Au, CSSPixel>,
1090        intersection_rect: Rect<Au, CSSPixel>,
1091        intersection_ratio: f64,
1092        is_visible: bool,
1093        root_bounds: Rect<Au, CSSPixel>,
1094    ) -> Self {
1095        Self {
1096            threshold_index,
1097            is_intersecting,
1098            target_rect,
1099            intersection_rect,
1100            intersection_ratio,
1101            is_visible,
1102            root_bounds,
1103        }
1104    }
1105}
1106
1107impl script_bindings::callback::OwnerWindow<crate::DomTypeHolder> for IntersectionObserver {}