Skip to main content

script/dom/resizeobserver/
resizeobserver.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;
6use std::sync::atomic::{AtomicUsize, Ordering};
7
8use app_units::Au;
9use dom_struct::dom_struct;
10use euclid::Rect;
11use euclid::num::Zero;
12use html5ever::ns;
13use js::context::{JSContext, NoGC};
14use js::rust::HandleObject;
15use layout_api::BoxAreaType;
16use script_bindings::callback::{RootedCallback, TracedCallback};
17use script_bindings::cell::DomRefCell;
18use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
19use style::logical_geometry::WritingMode;
20
21use crate::dom::bindings::callback::ExceptionHandling;
22use crate::dom::bindings::codegen::Bindings::ResizeObserverBinding::{
23    ResizeObserverBoxOptions, ResizeObserverCallback, ResizeObserverMethods, ResizeObserverOptions,
24};
25use crate::dom::bindings::inheritance::Castable;
26use crate::dom::bindings::root::{Dom, DomRoot};
27use crate::dom::document::RenderingUpdateReason;
28use crate::dom::domrectreadonly::DOMRectReadOnly;
29use crate::dom::element::Element;
30use crate::dom::node::{Node, NodeTraits};
31use crate::dom::resizeobserverentry::ResizeObserverEntry;
32use crate::dom::resizeobserversize::{ResizeObserverSize, ResizeObserverSizeImpl};
33use crate::dom::window::Window;
34
35/// <https://drafts.csswg.org/resize-observer/#calculate-depth-for-node>
36#[derive(Debug, Default, PartialEq, PartialOrd)]
37pub(crate) struct ResizeObservationDepth(usize);
38
39impl ResizeObservationDepth {
40    pub(crate) fn max() -> ResizeObservationDepth {
41        ResizeObservationDepth(usize::MAX)
42    }
43}
44
45/// <https://drafts.csswg.org/resize-observer/#resize-observer-slots>
46/// See `ObservationState` for active and skipped observation targets.
47#[dom_struct]
48pub(crate) struct ResizeObserver {
49    reflector_: Reflector,
50
51    /// The [`Window`] that this [`ResizeObserver`] was created in.
52    window: Dom<Window>,
53
54    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-callback-slot>
55    callback: TracedCallback<ResizeObserverCallback>,
56
57    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-observationtargets-slot>
58    ///
59    /// This list simultaneously also represents the
60    /// [`[[activeTargets]]`](https://drafts.csswg.org/resize-observer/#dom-resizeobserver-activetargets-slot)
61    /// and [`[[skippedTargets]]`](https://drafts.csswg.org/resize-observer/#dom-resizeobserver-skippedtargets-slot)
62    /// internal slots.
63    observation_targets: DomRefCell<Vec<(ResizeObservation, Dom<Element>)>>,
64
65    /// An index that indicates what order this [`ResizeObsever`] was created in. This is used for
66    /// keeping them in sorted order in the `Document`'s collection of observers.
67    creation_order: usize,
68}
69
70impl ResizeObserver {
71    pub(crate) fn new_inherited(
72        window: &Window,
73        callback: RootedCallback<ResizeObserverCallback>,
74    ) -> ResizeObserver {
75        static CREATION_ORDER: AtomicUsize = AtomicUsize::new(0);
76        ResizeObserver {
77            reflector_: Reflector::new(),
78            window: Dom::from_ref(window),
79            callback: callback.to_traced(),
80            observation_targets: Default::default(),
81            creation_order: CREATION_ORDER.fetch_add(1, Ordering::Relaxed),
82        }
83    }
84
85    fn new(
86        cx: &mut JSContext,
87        window: &Window,
88        proto: Option<HandleObject>,
89        callback: RootedCallback<ResizeObserverCallback>,
90    ) -> DomRoot<ResizeObserver> {
91        let observer = Box::new(ResizeObserver::new_inherited(window, callback));
92        reflect_dom_object_with_proto(cx, observer, window, proto)
93    }
94
95    /// Step 2 of <https://drafts.csswg.org/resize-observer/#gather-active-observations-h>
96    ///
97    /// <https://drafts.csswg.org/resize-observer/#has-active-resize-observations>
98    pub(crate) fn gather_active_resize_observations_at_depth(
99        &self,
100        no_gc: &NoGC,
101        depth: &ResizeObservationDepth,
102        has_active: &mut bool,
103    ) {
104        // Step 2.1 Clear observer’s [[activeTargets]], and [[skippedTargets]].
105        // NOTE: This happens as part of Step 2.2
106
107        // Step 2.2 For each observation in observer.[[observationTargets]] run this step:
108        for (observation, target) in self.observation_targets.borrow().iter() {
109            observation.state.set(Default::default());
110
111            // Step 2.2.1 If observation.isActive() is true
112            if observation.is_active(target) {
113                // Step 2.2.1.1 Let targetDepth be result of calculate depth for node for observation.target.
114                let target_depth = calculate_depth_for_node(no_gc, target);
115
116                // Step 2.2.1.2 If targetDepth is greater than depth then add observation to [[activeTargets]].
117                if target_depth > *depth {
118                    observation.state.set(ObservationState::Active);
119                    *has_active = true;
120                }
121                // Step 2.2.1.3 Else add observation to [[skippedTargets]].
122                else {
123                    observation.state.set(ObservationState::Skipped);
124                }
125            }
126        }
127    }
128
129    /// Step 2 of <https://drafts.csswg.org/resize-observer/#broadcast-active-resize-observations>
130    pub(crate) fn broadcast_active_resize_observations(
131        &self,
132        cx: &mut JSContext,
133        shallowest_target_depth: &mut ResizeObservationDepth,
134    ) {
135        // Step 2.1 If observer.[[activeTargets]] slot is empty, continue.
136        // NOTE: Due to the way we implement the activeTarges internal slot we can't easily
137        // know if it's empty. Instead we remember whether there were any active observation
138        // targets during the following traversal and return if there were none.
139        let mut has_active_observation_targets = false;
140
141        // Step 2.2 Let entries be an empty list of ResizeObserverEntryies.
142        let mut entries: Vec<DomRoot<ResizeObserverEntry>> = Default::default();
143
144        // Step 2.3 For each observation in [[activeTargets]] perform these steps:
145        for (observation, target) in self.observation_targets.borrow().iter() {
146            let ObservationState::Active = observation.state.get() else {
147                continue;
148            };
149            has_active_observation_targets = true;
150
151            let window = target.owner_window();
152            let entry = create_and_populate_a_resizeobserverentry(cx, &window, target, observation);
153            entries.push(entry);
154            observation.state.set(ObservationState::Done);
155
156            let target_depth = calculate_depth_for_node(cx.no_gc(), target);
157            if target_depth < *shallowest_target_depth {
158                *shallowest_target_depth = target_depth;
159            }
160        }
161
162        if !has_active_observation_targets {
163            return;
164        }
165
166        // Step 2.4 Invoke observer.[[callback]] with entries.
167        let _ = self
168            .callback
169            .Call_(cx, self, entries, self, ExceptionHandling::Report);
170
171        // Step 2.5 Clear observer.[[activeTargets]].
172        // NOTE: The observation state was modified in Step 2.2
173    }
174
175    /// <https://drafts.csswg.org/resize-observer/#has-skipped-observations-h>
176    pub(crate) fn has_skipped_resize_observations(&self) -> bool {
177        self.observation_targets
178            .borrow()
179            .iter()
180            .any(|(observation, _)| observation.state.get() == ObservationState::Skipped)
181    }
182
183    /// Whether or not the given [`ResizeObserver`] was created after this one.
184    pub(crate) fn created_after(&self, other: &ResizeObserver) -> bool {
185        self.creation_order > other.creation_order
186    }
187}
188
189/// <https://drafts.csswg.org/resize-observer/#create-and-populate-a-resizeobserverentry>
190fn create_and_populate_a_resizeobserverentry(
191    cx: &mut JSContext,
192    window: &Window,
193    target: &Element,
194    observation: &ResizeObservation,
195) -> DomRoot<ResizeObserverEntry> {
196    // Step 3. Set this.borderBoxSize slot to result of calculating box size given target and observedBox of "border-box".
197    let border_box_size = calculate_box_size(target, &ResizeObserverBoxOptions::Border_box);
198    // Step 4. Set this.contentBoxSize slot to result of calculating box size given target and observedBox of "content-box".
199    let content_box_size = calculate_box_size(target, &ResizeObserverBoxOptions::Content_box);
200
201    // Step 5. Set this.devicePixelContentBoxSize slot to result of calculating box size given target and observedBox of "device-pixel-content-box".
202    let device_pixel_content_box =
203        calculate_box_size(target, &ResizeObserverBoxOptions::Device_pixel_content_box);
204
205    // Note: this is safe because an observation is
206    // initialized with one reported size (zero).
207    // The spec plans to store multiple reported sizes,
208    // but for now there can be only one.
209    let last_reported_size = match observation.observed_box {
210        ResizeObserverBoxOptions::Content_box => content_box_size,
211        ResizeObserverBoxOptions::Border_box => border_box_size,
212        ResizeObserverBoxOptions::Device_pixel_content_box => device_pixel_content_box,
213    };
214
215    {
216        let mut sizes = observation.last_reported_sizes.safe_borrow_mut(cx.no_gc());
217        if sizes.is_empty() {
218            sizes.push(last_reported_size);
219        } else {
220            sizes[0] = last_reported_size;
221        }
222    }
223
224    // Step 7. If target is not an SVG element or target is an SVG element with an associated CSS
225    // layout box do these steps:
226    let use_padding = *target.namespace() != ns!(svg) || target.has_css_layout_box();
227    let (padding_top, padding_left) = if use_padding {
228        // Step 7.1. Set this.contentRect.top to target.padding top.
229        // Step 7.2. Set this.contentRect.left to target.padding left.
230        let padding = target.upcast::<Node>().padding().unwrap_or_default();
231        (padding.top, padding.left)
232    } else {
233        // Step 8. If target is an SVG element without an associated CSS layout box do these steps:
234        // Step 8.1. Set this.contentRect.top and this.contentRect.left to 0.
235        (Au::zero(), Au::zero())
236    };
237
238    let writing_mode = target
239        .style_without_reflow()
240        .map_or_else(WritingMode::empty, |style| style.writing_mode);
241    let (width, height) = if writing_mode.is_horizontal() {
242        (content_box_size.inline_size, content_box_size.block_size)
243    } else {
244        (content_box_size.block_size, content_box_size.inline_size)
245    };
246
247    // Step 6. Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
248    let content_rect = DOMRectReadOnly::new(
249        cx,
250        window.upcast(),
251        None,
252        padding_left.to_f64_px(),
253        padding_top.to_f64_px(),
254        width,
255        height,
256    );
257
258    let border_box_size = ResizeObserverSize::new(cx, window, border_box_size);
259    let content_box_size = ResizeObserverSize::new(cx, window, content_box_size);
260    let device_pixel_content_box = ResizeObserverSize::new(cx, window, device_pixel_content_box);
261
262    // Step 1. Let this be a new ResizeObserverEntry.
263    // Step 2. Set this.target slot to target.
264    ResizeObserverEntry::new(
265        cx,
266        window,
267        target,
268        &content_rect,
269        &[&*border_box_size],
270        &[&*content_box_size],
271        &[&*device_pixel_content_box],
272    )
273}
274
275impl ResizeObserverMethods<crate::DomTypeHolder> for ResizeObserver {
276    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-resizeobserver>
277    fn Constructor(
278        cx: &mut JSContext,
279        window: &Window,
280        proto: Option<HandleObject>,
281        callback: RootedCallback<ResizeObserverCallback>,
282    ) -> DomRoot<ResizeObserver> {
283        ResizeObserver::new(cx, window, proto, callback)
284    }
285
286    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-observe>
287    fn Observe(&self, no_gc: &NoGC, target: &Element, options: &ResizeObserverOptions) {
288        let observed_box = self
289            .observation_targets
290            .borrow()
291            .iter()
292            .find(|(_, other)| &**other == target)
293            .map(|(observation, _)| observation.observed_box);
294        // Propoposed specification text from <https://github.com/web-platform-tests/wpt/issues/30708>.
295        // >  If preexistingTarget exists and its observedBox.box equals options.box return
296        // Both Chrome and Firefox do this and likely WebKit too.
297        if observed_box == Some(options.box_) {
298            return;
299        }
300
301        // Step 1. If target is in [[observationTargets]] slot, call unobserve() with argument target.
302        if observed_box.is_some() {
303            self.Unobserve(no_gc, target);
304        }
305
306        // Step 2. Let observedBox be the value of the box dictionary member of options.
307        // Step 3. Let resizeObservation be new ResizeObservation(target, observedBox).
308        let resize_observation = ResizeObservation::new(options.box_);
309
310        // Step 4. Add the resizeObservation to the [[observationTargets]] slot.
311        self.observation_targets
312            .safe_borrow_mut(no_gc)
313            .push((resize_observation, Dom::from_ref(target)));
314
315        let document = self.window.document_unrooted(no_gc);
316        document.add_rendering_update_reason(
317            RenderingUpdateReason::ResizeObserverStartedObservingTarget,
318        );
319
320        // This isn't specified, but this is what Servo does to ensure that ResizeObservers can be
321        // garbage collected properly. `Unobserve` will remove the observer from the Document.
322        document.add_resize_observer(no_gc, self);
323    }
324
325    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-unobserve>
326    fn Unobserve(&self, no_gc: &NoGC, target: &Element) {
327        self.observation_targets
328            .safe_borrow_mut(no_gc)
329            .retain_mut(|(_, other)| !(&**other == target));
330        if self.observation_targets.borrow().is_empty() {
331            self.window
332                .document_unrooted(no_gc)
333                .remove_resize_observer(no_gc, self);
334        }
335    }
336
337    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-disconnect>
338    fn Disconnect(&self, no_gc: &NoGC) {
339        self.observation_targets.safe_borrow_mut(no_gc).clear();
340        self.window
341            .document_unrooted(no_gc)
342            .remove_resize_observer(no_gc, self);
343    }
344}
345
346/// State machine equivalent of active and skipped observations.
347#[derive(Copy, Clone, Default, MallocSizeOf, PartialEq)]
348enum ObservationState {
349    #[default]
350    Done,
351    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-activetargets-slot>
352    Active,
353    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-skippedtargets-slot>
354    Skipped,
355}
356
357/// <https://drafts.csswg.org/resize-observer/#resizeobservation>
358///
359/// Note: `target` is kept out of here, to avoid having to root the `ResizeObservation`.
360/// <https://drafts.csswg.org/resize-observer/#dom-resizeobservation-target>
361#[derive(JSTraceable, MallocSizeOf)]
362struct ResizeObservation {
363    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobservation-observedbox>
364    observed_box: ResizeObserverBoxOptions,
365    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobservation-lastreportedsizes>
366    last_reported_sizes: DomRefCell<Vec<ResizeObserverSizeImpl>>,
367    /// State machine mimicking the "active" and "skipped" targets slots of the observer.
368    #[no_trace]
369    state: Cell<ObservationState>,
370}
371
372impl ResizeObservation {
373    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobservation-resizeobservation>
374    pub(crate) fn new(observed_box: ResizeObserverBoxOptions) -> ResizeObservation {
375        ResizeObservation {
376            observed_box,
377            last_reported_sizes: DomRefCell::new(vec![]),
378            state: Default::default(),
379        }
380    }
381
382    /// <https://drafts.csswg.org/resize-observer/#dom-resizeobservation-isactive>
383    fn is_active(&self, target: &Element) -> bool {
384        let Some(last_reported_size) = self.last_reported_sizes.borrow().first().copied() else {
385            return true;
386        };
387        calculate_box_size(target, &self.observed_box) != last_reported_size
388    }
389}
390
391/// <https://drafts.csswg.org/resize-observer/#calculate-depth-for-node>
392fn calculate_depth_for_node(no_gc: &NoGC, target: &Element) -> ResizeObservationDepth {
393    let node = target.upcast::<Node>();
394    let depth = node
395        .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
396        .count();
397    ResizeObservationDepth(depth)
398}
399
400/// <https://drafts.csswg.org/resize-observer/#calculate-box-size>
401///
402/// The dimensions of the returned `ResizeObserverSizeImpl` depend on the type of box being
403/// observed. For `ResizeObserverBoxOptions::Content_box` and
404/// `ResizeObserverBoxOptions::Border_box`, the values will be in `px`. For
405/// `ResizeObserverBoxOptions::Device_pixel_content_box` they will be in integral device pixels.
406fn calculate_box_size(
407    target: &Element,
408    observed_box: &ResizeObserverBoxOptions,
409) -> ResizeObserverSizeImpl {
410    let (width, height) = match observed_box {
411        ResizeObserverBoxOptions::Content_box => {
412            // Note: only taking first fragment,
413            // but the spec will expand to cover all fragments.
414            let content_box = target
415                .owner_window()
416                .box_area_query_without_reflow(target.upcast(), BoxAreaType::Content, true)
417                .unwrap_or_else(Rect::zero);
418
419            (
420                content_box.size.width.to_f64_px(),
421                content_box.size.height.to_f64_px(),
422            )
423        },
424        ResizeObserverBoxOptions::Border_box => {
425            // Note: only taking first fragment,
426            // but the spec will expand to cover all fragments.
427            let border_box = target
428                .owner_window()
429                .box_area_query_without_reflow(target.upcast(), BoxAreaType::Border, true)
430                .unwrap_or_else(Rect::zero);
431            (
432                border_box.size.width.to_f64_px(),
433                border_box.size.height.to_f64_px(),
434            )
435        },
436        ResizeObserverBoxOptions::Device_pixel_content_box => {
437            let device_pixel_ratio = target.owner_window().device_pixel_ratio().get() as f64;
438            let content_box = target
439                .owner_window()
440                .box_area_query_without_reflow(target.upcast(), BoxAreaType::Content, true)
441                .unwrap_or_else(Rect::zero);
442            // This code is snapping both edges of the rect to device pixels and then calculating
443            // the width. This gives the exact number of device pixels the rectangle takes up on
444            // the screen.
445            let to_device_px = |length: Au| (length.to_f64_px() * device_pixel_ratio).round();
446            let width = to_device_px(content_box.max_x()) - to_device_px(content_box.origin.x);
447            let height = to_device_px(content_box.max_y()) - to_device_px(content_box.origin.y);
448            (width, height)
449        },
450    };
451
452    let writing_mode = target
453        .style_without_reflow()
454        .map_or_else(WritingMode::empty, |style| style.writing_mode);
455    let (inline_size, block_size) = if writing_mode.is_horizontal() {
456        (width, height)
457    } else {
458        (height, width)
459    };
460
461    ResizeObserverSizeImpl {
462        inline_size,
463        block_size,
464    }
465}
466
467impl script_bindings::callback::OwnerWindow<crate::DomTypeHolder> for ResizeObserver {}