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