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::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            .safe_borrow_mut(no_gc)
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            .safe_borrow_mut(no_gc)
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
393            .safe_borrow_mut(cx.no_gc())
394            .push(entry.as_traced());
395
396        // Step 3. Queue an intersection observer task for document.
397        document.queue_an_intersection_observer_task();
398    }
399
400    /// Step 3.1-3.5 of <https://w3c.github.io/IntersectionObserver/#notify-intersection-observers-algo>
401    pub(crate) fn invoke_callback_if_necessary(&self, cx: &mut js::context::JSContext) {
402        // Step 1
403        // > If observer’s internal [[QueuedEntries]] slot is empty, continue.
404        if self.queued_entries.borrow().is_empty() {
405            return;
406        }
407
408        // Step 2-3
409        // We trivially moved the entries and root them.
410        let queued_entries = self
411            .queued_entries
412            .take()
413            .iter_mut()
414            .map(|entry| entry.as_rooted())
415            .collect();
416
417        // Step 4-5
418        let _ = self
419            .callback
420            .Call_(cx, self, queued_entries, self, ExceptionHandling::Report);
421    }
422
423    /// Connect the observer itself into owner doc if it is unconnected.
424    /// If the [`IntersectionObserver`] is already connected, do nothing.
425    fn connect_to_owner(&self) {
426        if !self.connected_to_document.get() {
427            self.owner_doc.add_intersection_observer(self);
428            self.connected_to_document.set(true);
429        }
430    }
431
432    /// Disconnect the observer itself from owner doc.
433    /// If not connected to a [`Document`], do nothing.
434    fn disconnect_from_owner(&self) {
435        if self.connected_to_document.get() {
436            self.owner_doc.remove_intersection_observer(self);
437        }
438    }
439
440    /// <https://w3c.github.io/IntersectionObserver/#ref-for-intersectionobserver-content-clip>
441    /// An Element is defined as having a content clip if its computed style has overflow properties
442    /// that cause its content to be clipped to the element’s padding edge.
443    // TODO: this is not clear for `overflow: clip` since it is clipped based on overflow clip rect.
444    fn has_content_clip(element: &Element) -> bool {
445        element
446            .upcast::<Node>()
447            .effective_overflow_without_reflow()
448            .is_some_and(|overflow_axes| {
449                overflow_axes.x != Overflow::Visible || overflow_axes.y != Overflow::Visible
450            })
451    }
452
453    /// > The root intersection rectangle for an IntersectionObserver is
454    /// > the rectangle we’ll use to check against the targets.
455    ///
456    /// <https://w3c.github.io/IntersectionObserver/#intersectionobserver-root-intersection-rectangle>
457    pub(crate) fn root_intersection_rectangle(&self) -> Option<Rect<Au, CSSPixel>> {
458        let intersection_rectangle = match self.concrete_root() {
459            // Handle if root is an element.
460            Some(ElementOrDocument::Element(element)) => {
461                // TODO: recheck scrollbar approach and clip-path clipping from Chromium implementation.
462                if IntersectionObserver::has_content_clip(&element) {
463                    // > Otherwise, if the intersection root has a content clip, it’s the element’s padding area.
464                    element.upcast::<Node>().padding_box_without_reflow()
465                } else {
466                    // > Otherwise, it’s the result of getting the bounding box for the intersection root.
467                    element.upcast::<Node>().border_box_without_reflow()
468                }
469            },
470            // Handle if root is a Document, which includes implicit root and explicit Document root.
471            Some(ElementOrDocument::Document(document)) => {
472                // > If the intersection root is a document, it’s the size of the document's viewport
473                // > (note that this processing step can only be reached if the document is fully active).
474                // TODO: viewport should consider native scrollbar if exist. Recheck Servo's scrollbar approach.
475                let viewport = document.window().viewport_details().size;
476                Some(Rect::from_size(Size2D::new(
477                    Au::from_f32_px(viewport.width),
478                    Au::from_f32_px(viewport.height),
479                )))
480            },
481            None => None,
482        };
483
484        // > When calculating the root intersection rectangle for a same-origin-domain target,
485        // > the rectangle is then expanded according to the offsets in the IntersectionObserver’s
486        // > [[rootMargin]] slot in a manner similar to CSS’s margin property, with the four values
487        // > indicating the amount the top, right, bottom, and left edges, respectively, are offset by,
488        // > with positive lengths indicating an outward offset. Percentages are resolved relative to
489        // > the width of the undilated rectangle.
490        // TODO(stevennovaryo): add check for same-origin-domain
491        intersection_rectangle.map(|intersection_rectangle| {
492            let margin = Self::resolve_percentages_with_basis(
493                &self.root_margin.borrow(),
494                intersection_rectangle,
495            );
496            intersection_rectangle.outer_rect(margin)
497        })
498    }
499
500    /// Return root or try to get the top-level browsing context document in case if this is a implicit root.
501    /// <https://w3c.github.io/IntersectionObserver/#intersectionobserver-intersection-root>
502    // TODO: Currently we are unable to get the cross `ScriptThread` document.
503    fn concrete_root(&self) -> Option<ElementOrDocument> {
504        match &self.root {
505            Some(root) => Some(root.into()),
506            None => self
507                .owner_doc
508                .window()
509                .top_level_document_if_local()
510                .map(ElementOrDocument::Document),
511        }
512    }
513
514    /// Step 2.2.4-2.2.21 of <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>
515    ///
516    /// If some conditions require to skips "processing further", we will skips those steps and
517    /// return default values conformant to step 2.2.4. See [`IntersectionObservationOutput::default_skipped`].
518    ///
519    /// Note that current draft specs skipped wrong steps, as it should skip computing fields that
520    /// would result in different intersection entry other than the default entry per published spec.
521    /// <https://www.w3.org/TR/intersection-observer/>
522    fn maybe_compute_intersection_output(
523        &self,
524        target: &Element,
525        maybe_root_bounds: Option<Rect<Au, CSSPixel>>,
526    ) -> IntersectionObservationOutput {
527        // Step 5
528        // > If the intersection root is not the implicit root, and target is not in
529        // > the same document as the intersection root, skip to step 11.
530        // Step 6
531        // > If the intersection root is an Element, and target is not a descendant of
532        // > the intersection root in the containing block chain, skip to step 11.
533        match &self.root {
534            Some(UnrootedElementOrDocument::Document(document))
535                if document.as_rooted() != target.owner_document() =>
536            {
537                return IntersectionObservationOutput::default_skipped();
538            },
539            Some(UnrootedElementOrDocument::Element(element)) => {
540                // To ensure consistency, we also check for elements right now, but we can depend on the
541                // layout query later.
542                if element.owner_document() != target.owner_document() {
543                    return IntersectionObservationOutput::default_skipped();
544                }
545                if !element
546                    .owner_window()
547                    .is_containing_block_descendant_query_without_reflow(
548                        element.upcast(),
549                        target.upcast(),
550                    )
551                {
552                    return IntersectionObservationOutput::default_skipped();
553                }
554            },
555            _ => {},
556        }
557
558        // Step 7
559        // > Set targetRect to the DOMRectReadOnly obtained by getting the bounding box for target.
560        let maybe_target_rect = target.upcast::<Node>().border_box_without_reflow();
561
562        // Following the implementation of Gecko, we will skip further processing if these
563        // information not available. This would also handle display none element.
564        let (Some(root_bounds), Some(target_rect), Some(root_intersection)) =
565            (maybe_root_bounds, maybe_target_rect, self.concrete_root())
566        else {
567            return IntersectionObservationOutput::default_skipped();
568        };
569
570        // TODO(stevennovaryo): we should probably also consider adding visibity check, ideally
571        //                      it would require new query from LayoutThread.
572
573        // Step 8
574        // > Let intersectionRect be the result of running the compute the intersection algorithm on
575        // > target and observer’s intersection root.
576        let maybe_intersection_rect = compute_the_intersection(
577            target,
578            &root_intersection,
579            root_bounds,
580            target_rect,
581            &self.scroll_margin.borrow(),
582        );
583        let intersection_rect = maybe_intersection_rect.unwrap_or_default();
584
585        // Step 9
586        // > Let targetArea be targetRect’s area.
587        // Step 10
588        // > Let intersectionArea be intersectionRect’s area.
589        // These steps are folded in Step 12, rewriting (w1 * h1) / (w2 * h2) as (w1 / w2) * (h1 / h2)
590        // to avoid multiplication overflows.
591
592        // Step 11
593        // > Let isIntersecting be true if targetRect and rootBounds intersect or are edge-adjacent,
594        // > even if the intersection has zero area (because rootBounds or targetRect have zero area).
595        // Because we are considering edge-adjacent, instead of checking whether the rectangle is empty,
596        // we are checking whether the rectangle is negative or not.
597        let is_intersecting = maybe_intersection_rect.is_some();
598
599        // Step 12
600        // > If targetArea is non-zero, let intersectionRatio be intersectionArea divided by targetArea.
601        // > Otherwise, let intersectionRatio be 1 if isIntersecting is true, or 0 if isIntersecting is false.
602        let intersection_ratio = if target_rect.size.width.0 == 0 || target_rect.size.height.0 == 0
603        {
604            is_intersecting.into()
605        } else {
606            (intersection_rect.size.width.0 as f64 / target_rect.size.width.0 as f64) *
607                (intersection_rect.size.height.0 as f64 / target_rect.size.height.0 as f64)
608        };
609
610        // Step 13
611        // > Set thresholdIndex to the index of the first entry in observer.thresholds whose value is
612        // > greater than intersectionRatio, or the length of observer.thresholds if intersectionRatio is
613        // > greater than or equal to the last entry in observer.thresholds.
614        let threshold_index = self
615            .thresholds
616            .borrow()
617            .iter()
618            .position(|threshold| **threshold > intersection_ratio)
619            .unwrap_or(self.thresholds.borrow().len());
620
621        // If the index is 0, the first threshold value is greater
622        // than the observed ratio, so we're not actually matching yet.
623        // The spec differentiates between this case and the case where
624        // there is no intersection, but other browser engines do not.
625        let threshold_index = if is_intersecting && threshold_index > 0 {
626            ThresholdIndex::Matching(threshold_index)
627        } else {
628            ThresholdIndex::NotMatching
629        };
630
631        // Step 14
632        // > Let isVisible be the result of running the visibility algorithm on target.
633        // TODO: Implement visibility algorithm
634        let is_visible = false;
635
636        // We never report isIntersecting as true unless we have exceeded a threshold,
637        // which matches other browser eengines.
638        // See https://github.com/w3c/IntersectionObserver/issues/432 for background.
639        let is_intersecting = matches!(threshold_index, ThresholdIndex::Matching(..));
640
641        IntersectionObservationOutput::new_computed(
642            threshold_index,
643            is_intersecting,
644            target_rect,
645            intersection_rect,
646            intersection_ratio,
647            is_visible,
648            root_bounds,
649        )
650    }
651
652    /// Step 2.2.1-2.2.21 of <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>
653    pub(crate) fn update_intersection_observations_steps(
654        &self,
655        cx: &mut JSContext,
656        document: &Document,
657        time: CrossProcessInstant,
658        root_bounds: Option<Rect<Au, CSSPixel>>,
659    ) {
660        for target in &*self.observation_targets.borrow() {
661            // Step 1
662            // > Let registration be the IntersectionObserverRegistration record in target’s internal
663            // > [[RegisteredIntersectionObservers]] slot whose observer property is equal to observer.
664            let registration = target.get_intersection_observer_registration(self).unwrap();
665
666            // Step 2
667            // > If (time - registration.lastUpdateTime < observer.delay), skip further processing for target.
668            if time - registration.last_update_time.get() <
669                Duration::from_millis(self.delay.get().max(0) as u64)
670            {
671                return;
672            }
673
674            // Step 3
675            // > Set registration.lastUpdateTime to time.
676            registration.last_update_time.set(time);
677
678            // step 4-14
679            let intersection_output = self.maybe_compute_intersection_output(target, root_bounds);
680
681            // Step 15-17
682            // > 15. Let previousThresholdIndex be the registration’s previousThresholdIndex property.
683            // > 16. Let previousIsIntersecting be the registration’s previousIsIntersecting property.
684            // > 17. Let previousIsVisible be the registration’s previousIsVisible property.
685            let previous_threshold_index = registration.previous_threshold_index.get();
686            let previous_is_intersecting = registration.previous_is_intersecting.get();
687            let previous_is_visible = registration.previous_is_visible.get();
688
689            // Step 18
690            // > If thresholdIndex does not equal previousThresholdIndex, or
691            // > if isIntersecting does not equal previousIsIntersecting, or
692            // > if isVisible does not equal previousIsVisible,
693            // > queue an IntersectionObserverEntry, passing in observer, time, rootBounds,
694            // > targetRect, intersectionRect, isIntersecting, isVisible, and target.
695            if Some(intersection_output.threshold_index) != previous_threshold_index ||
696                intersection_output.is_intersecting != previous_is_intersecting ||
697                intersection_output.is_visible != previous_is_visible
698            {
699                // TODO(stevennovaryo): Per IntersectionObserverEntry interface, the rootBounds
700                //                      should be null for cross-origin-domain target.
701                self.queue_an_intersectionobserverentry(
702                    cx,
703                    document,
704                    time,
705                    intersection_output.root_bounds,
706                    intersection_output.target_rect,
707                    intersection_output.intersection_rect,
708                    intersection_output.is_intersecting,
709                    intersection_output.is_visible,
710                    intersection_output.intersection_ratio,
711                    target,
712                );
713            }
714
715            // Step 19-21
716            // > 19. Assign thresholdIndex to registration’s previousThresholdIndex property.
717            // > 20. Assign isIntersecting to registration’s previousIsIntersecting property.
718            // > 21. Assign isVisible to registration’s previousIsVisible property.
719            registration
720                .previous_threshold_index
721                .set(Some(intersection_output.threshold_index));
722            registration
723                .previous_is_intersecting
724                .set(intersection_output.is_intersecting);
725            registration
726                .previous_is_visible
727                .set(intersection_output.is_visible);
728        }
729    }
730
731    fn resolve_percentages_with_basis(
732        margin: &IntersectionObserverMargin,
733        containing_block: Rect<Au, CSSPixel>,
734    ) -> SideOffsets2D<Au, CSSPixel> {
735        let inner = &margin.0;
736        SideOffsets2D::new(
737            inner.0.to_used_value(containing_block.height()),
738            inner.1.to_used_value(containing_block.width()),
739            inner.2.to_used_value(containing_block.height()),
740            inner.3.to_used_value(containing_block.width()),
741        )
742    }
743}
744
745impl IntersectionObserverMethods<crate::DomTypeHolder> for IntersectionObserver {
746    /// > The root provided to the IntersectionObserver constructor, or null if none was provided.
747    ///
748    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-root>
749    fn GetRoot(&self) -> Option<ElementOrDocument> {
750        self.root.as_ref().map(|root| root.into())
751    }
752
753    /// > Offsets applied to the root intersection rectangle, effectively growing or
754    /// > shrinking the box that is used to calculate intersections. These offsets are only
755    /// > applied when handling same-origin-domain targets; for cross-origin-domain targets
756    /// > they are ignored.
757    ///
758    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin>
759    fn RootMargin(&self) -> DOMString {
760        self.root_margin.borrow().to_css_string().into()
761    }
762
763    /// > Offsets are applied to scrollports on the path from intersection root to target,
764    /// > effectively growing or shrinking the clip rects used to calculate intersections.
765    ///
766    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-scrollmargin>
767    fn ScrollMargin(&self) -> DOMString {
768        self.scroll_margin.borrow().to_css_string().into()
769    }
770
771    /// > A list of thresholds, sorted in increasing numeric order, where each threshold
772    /// > is a ratio of intersection area to bounding box area of an observed target.
773    /// > Notifications for a target are generated when any of the thresholds are crossed
774    /// > for that target. If no options.threshold was provided to the IntersectionObserver
775    /// > constructor, or the sequence is empty, the value of this attribute will be `[0]`.
776    ///
777    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-thresholds>
778    fn Thresholds(&self, cx: &mut JSContext, retval: MutableHandleValue) {
779        to_frozen_array(cx, &self.thresholds.borrow(), retval);
780    }
781
782    /// > A number indicating the minimum delay in milliseconds between notifications from
783    /// > this observer for a given target.
784    ///
785    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-delay>
786    fn Delay(&self) -> i32 {
787        self.delay.get()
788    }
789
790    /// > A boolean indicating whether this IntersectionObserver will track changes in a target’s visibility.
791    ///
792    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-trackvisibility>
793    fn TrackVisibility(&self) -> bool {
794        self.track_visibility.get()
795    }
796
797    /// > Run the observe a target Element algorithm, providing this and target.
798    ///
799    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-observe>
800    fn Observe(&self, no_gc: &NoGC, target: &Element) {
801        self.observe_target_element(target, no_gc);
802    }
803
804    /// > Run the unobserve a target Element algorithm, providing this and target.
805    ///
806    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-unobserve>
807    fn Unobserve(&self, no_gc: &NoGC, target: &Element) {
808        self.unobserve_target_element(target, no_gc);
809    }
810
811    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-disconnect>
812    fn Disconnect(&self, no_gc: &NoGC) {
813        // > For each target in this’s internal [[ObservationTargets]] slot:
814        self.observation_targets.borrow().iter().for_each(|target| {
815            // > 1. Remove the IntersectionObserverRegistration record whose observer property is equal to
816            // >    this from target’s internal [[RegisteredIntersectionObservers]] slot.
817            target.remove_intersection_observer(self, no_gc);
818        });
819        // > 2. Remove target from this’s internal [[ObservationTargets]] slot.
820        self.observation_targets.safe_borrow_mut(no_gc).clear();
821
822        // We should remove this observer from the event loop.
823        self.disconnect_from_owner();
824    }
825
826    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-takerecords>
827    fn TakeRecords(&self) -> Vec<DomRoot<IntersectionObserverEntry>> {
828        // Step 1-3.
829        self.queued_entries
830            .take()
831            .iter()
832            .map(|entry| entry.as_rooted())
833            .collect()
834    }
835
836    /// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-intersectionobserver>
837    fn Constructor(
838        cx: &mut JSContext,
839        window: &Window,
840        proto: Option<HandleObject>,
841        callback: Rc<IntersectionObserverCallback>,
842        init: &IntersectionObserverInit,
843    ) -> Fallible<DomRoot<IntersectionObserver>> {
844        Self::new(cx, window, proto, callback, init)
845    }
846}
847
848#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
849enum ThresholdIndex {
850    NotMatching,
851    Matching(usize),
852}
853
854/// <https://w3c.github.io/IntersectionObserver/#intersectionobserverregistration>
855#[derive(Clone, JSTraceable, MallocSizeOf)]
856#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
857pub(crate) struct IntersectionObserverRegistration {
858    pub(crate) observer: Dom<IntersectionObserver>,
859    previous_threshold_index: Cell<Option<ThresholdIndex>>,
860    previous_is_intersecting: Cell<bool>,
861    #[no_trace]
862    last_update_time: Cell<CrossProcessInstant>,
863    previous_is_visible: Cell<bool>,
864}
865
866impl IntersectionObserverRegistration {
867    /// Initial value of [`IntersectionObserverRegistration`] according to
868    /// step 2 of <https://w3c.github.io/IntersectionObserver/#observe-target-element>.
869    /// > Let intersectionObserverRegistration be an IntersectionObserverRegistration record with
870    /// > an observer property set to observer, a previousThresholdIndex property set to -1,
871    /// > a previousIsIntersecting property set to false, and a previousIsVisible property set to false.
872    pub(crate) fn new_initial(observer: &IntersectionObserver) -> Self {
873        IntersectionObserverRegistration {
874            observer: Dom::from_ref(observer),
875            previous_threshold_index: Cell::new(None),
876            previous_is_intersecting: Cell::new(false),
877            last_update_time: Cell::new(CrossProcessInstant::epoch()),
878            previous_is_visible: Cell::new(false),
879        }
880    }
881}
882
883/// <https://w3c.github.io/IntersectionObserver/#parse-a-margin>
884fn parse_a_margin(value: Option<&DOMString>) -> Result<IntersectionObserverMargin, ()> {
885    // <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserverinit-rootmargin> &&
886    // <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserverinit-scrollmargin>
887    // > ... defaulting to "0px".
888    let value = match value {
889        Some(str) => &str.str(),
890        _ => "0px",
891    };
892
893    // Create necessary style ParserContext and utilize stylo's IntersectionObserverMargin
894    let mut input = ParserInput::new(value);
895    let mut parser = Parser::new(&mut input);
896
897    let context = parser_context_for_anonymous_content(
898        CssRuleType::Style,
899        ParsingMode::DEFAULT,
900        &ANONYMOUS_CONTENT_URL_DATA,
901    );
902
903    parser
904        .parse_entirely(|p| IntersectionObserverMargin::parse(&context, p))
905        .map_err(|_| ())
906}
907
908/// In terms of intersection observer, we consider zero-area rectangles as long as the area is not negative.
909fn intersect_rectangle(
910    lhs: &Rect<Au, CSSPixel>,
911    rhs: &Rect<Au, CSSPixel>,
912) -> Option<Rect<Au, CSSPixel>> {
913    let box_result = lhs.to_box2d().intersection_unchecked(&rhs.to_box2d());
914    if box_result.is_negative() {
915        None
916    } else {
917        Some(box_result.to_rect())
918    }
919}
920
921/// Compute the intersection rectangle of the target [`Element`] returning the results of intersection in the coordinate
922/// space of the target's owning [`Document`]. Additionally, we assume that both the target and the root is connected.
923/// <https://w3c.github.io/IntersectionObserver/#compute-the-intersection>
924fn compute_the_intersection(
925    target: &Element,
926    root: &ElementOrDocument,
927    root_bounds: Rect<Au, CSSPixel>,
928    mut intersection_rect: Rect<Au, CSSPixel>,
929    scroll_margin: &IntersectionObserverMargin,
930) -> Option<Rect<Au, CSSPixel>> {
931    // > 1. Let intersectionRect be the result of getting the bounding box for target.
932    // We had delegated the computation of this to the caller of the function.
933
934    // > 2. Let container be the containing block of target.
935    let mut container = match target
936        .upcast::<Node>()
937        .containing_block_node_without_reflow()
938    {
939        Some(node) => ElementOrDocument::Element(DomRoot::downcast(node).unwrap()),
940        None => ElementOrDocument::Document(target.owner_document()),
941    };
942
943    // Total offsets gained from traversing through multiple navigables. We use this to map the coordinate space.
944    // TODO: We should store the product sum of transformation matrices instead. But this should be enough to handle
945    // scrolling, simple translation, and offset from containing block.
946    let mut total_inter_document_offset = Vector2D::zero();
947
948    // > 3. While container is not root:
949    while container != *root {
950        let containing_element = match container {
951            ElementOrDocument::Document(ref containing_document) => {
952                // > 3.1. If container is the document of a nested browsing context, update intersectionRect by clipping
953                // >      to the viewport of the document, and update container to be the browsing context container of container.
954                if let Some(frame_container) = containing_document
955                    .browsing_context()
956                    .and_then(|window| window.frame_element().map(DomRoot::from_ref))
957                {
958                    let viewport_rect = f32_rect_to_au_rect(Rect::from_size(
959                        containing_document.window().viewport_details().size,
960                    ));
961
962                    intersection_rect = intersect_rectangle(&intersection_rect, &viewport_rect)?;
963
964                    let current_offset = frame_container
965                        .upcast::<Node>()
966                        .padding_box()
967                        .unwrap()
968                        .origin
969                        .to_vector();
970                    intersection_rect.origin += current_offset;
971                    total_inter_document_offset += current_offset;
972
973                    frame_container
974                } else {
975                    // TODO: Theoritically, this shouldn't be reachable as we have ensured that the root is reachable
976                    // in the previous steps. But we are still unable to iterate through cross-origin ancestor iframes,
977                    // and we will need to stop the iteration for that case.
978                    break;
979                }
980            },
981            ElementOrDocument::Element(ref root) => root.clone(),
982        };
983
984        // > 3.2. Map intersectionRect to the coordinate space of container.
985        // TODO(#35767): We don't map the coordinate space per each iteration yet, instead all the rectangles are
986        // in the viewport coordinate space. But this would cause the scroll margin calculation to be inaccurate
987        // with respect to transforms.
988
989        // > 3.3. If container is a scroll container, apply the IntersectionObserver’s [[scrollMargin]]
990        // >      to the container’s clip rect as described in apply scroll margin to a scrollport.
991        // > 3.4. If container has a content clip or a css clip-path property, update intersectionRect
992        // >      by applying container’s clip.
993        // TODO(#35767): handle `overflow: clip` and resolve clipping for x-axis and y-axis independently.
994        // Additionally, handle css `clip-path` as well.
995        if IntersectionObserver::has_content_clip(&containing_element) &&
996            let Some(container_padding_box) = containing_element
997                .upcast::<Node>()
998                .padding_box_without_reflow()
999        {
1000            let container_padding_box =
1001                if containing_element.establishes_scroll_container_without_reflow() {
1002                    let margin = IntersectionObserver::resolve_percentages_with_basis(
1003                        scroll_margin,
1004                        container_padding_box,
1005                    );
1006                    container_padding_box.outer_rect(margin)
1007                } else {
1008                    container_padding_box
1009                };
1010
1011            intersection_rect = intersect_rectangle(&intersection_rect, &container_padding_box)?;
1012        }
1013
1014        // > 3.5. If container is the root element of a browsing context, update container to be the
1015        // >      browsing context’s document; otherwise, update container to be the containing block
1016        // >      of container.
1017        // Additionally, for a node that doesn't have an element that establishes its containing block, we should
1018        // refer to the browsing context's document.
1019        container = match containing_element
1020            .upcast::<Node>()
1021            .containing_block_node_without_reflow()
1022            .and_then(DomRoot::downcast::<Element>)
1023        {
1024            Some(element) => ElementOrDocument::Element(element),
1025            None => ElementOrDocument::Document(containing_element.owner_document()),
1026        };
1027    }
1028
1029    // Step 4
1030    // > Map intersectionRect to the coordinate space of root.
1031    // TODO(#35767): we don't map the coordinate space per each iteration yet, instead all the rectangles are
1032    // in the viewport coordinate space.
1033
1034    // Step 5
1035    // > Update intersectionRect by intersecting it with the root intersection rectangle.
1036    intersection_rect = intersect_rectangle(&intersection_rect, &root_bounds)?;
1037
1038    // Step 6
1039    // > Map intersectionRect to the coordinate space of the viewport of the document containing target.
1040    // Offset the intersectionRect back to the coordinate space of target's document.
1041    intersection_rect.origin -= total_inter_document_offset;
1042
1043    // Step 7
1044    // > Return intersectionRect.
1045    Some(intersection_rect)
1046}
1047
1048/// The values from computing step 2.2.4-2.2.14 in
1049/// <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>.
1050/// See [`IntersectionObserver::maybe_compute_intersection_output`].
1051struct IntersectionObservationOutput {
1052    pub(crate) threshold_index: ThresholdIndex,
1053    pub(crate) is_intersecting: bool,
1054    pub(crate) target_rect: Rect<Au, CSSPixel>,
1055    pub(crate) intersection_rect: Rect<Au, CSSPixel>,
1056    pub(crate) intersection_ratio: f64,
1057    pub(crate) is_visible: bool,
1058
1059    /// The root intersection rectangle [`IntersectionObserver::root_intersection_rectangle`].
1060    /// If the processing is skipped, computation should report the default zero value.
1061    pub(crate) root_bounds: Rect<Au, CSSPixel>,
1062}
1063
1064impl IntersectionObservationOutput {
1065    /// Default values according to
1066    /// <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>.
1067    /// Step 4.
1068    /// > Let:
1069    /// > - thresholdIndex be 0.
1070    /// > - isIntersecting be false.
1071    /// > - targetRect be a DOMRectReadOnly with x, y, width, and height set to 0.
1072    /// > - intersectionRect be a DOMRectReadOnly with x, y, width, and height set to 0.
1073    ///
1074    /// For fields that the default values is not directly mentioned, the values conformant
1075    /// to current browser implementation or WPT test is used instead.
1076    fn default_skipped() -> Self {
1077        Self {
1078            threshold_index: ThresholdIndex::NotMatching,
1079            is_intersecting: false,
1080            target_rect: Rect::zero(),
1081            intersection_rect: Rect::zero(),
1082            intersection_ratio: 0.,
1083            is_visible: false,
1084            root_bounds: Rect::zero(),
1085        }
1086    }
1087
1088    fn new_computed(
1089        threshold_index: ThresholdIndex,
1090        is_intersecting: bool,
1091        target_rect: Rect<Au, CSSPixel>,
1092        intersection_rect: Rect<Au, CSSPixel>,
1093        intersection_ratio: f64,
1094        is_visible: bool,
1095        root_bounds: Rect<Au, CSSPixel>,
1096    ) -> Self {
1097        Self {
1098            threshold_index,
1099            is_intersecting,
1100            target_rect,
1101            intersection_rect,
1102            intersection_ratio,
1103            is_visible,
1104            root_bounds,
1105        }
1106    }
1107}
1108
1109impl script_bindings::callback::OwnerWindow<crate::DomTypeHolder> for IntersectionObserver {}