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