Skip to main content

nsh_core/core/
measure.rs

1//! Where views are: measuring a node for `ref.measure()`, scrolling one
2//! into view (`ref.reveal()`), and the areas descendants cover
3//! outside their parents' bounds, which platforms hit-test
4//! ([`MountItem::Overflow`]).
5
6use super::{Core, Key, Kind, NO_KEY, ScrollState, list::ListState};
7use crate::{
8    EventPayload, HeaderSlot, JsonValue, PayloadValue,
9    geometry::{Bounds, Point, Points, point, rect},
10    mount::MountItem,
11    ops::{Command, NodeId, RevealOptions, ScrollAlignment},
12    props::EdgeInsets,
13    text::TextEngine,
14};
15
16/// The offset that places the range `start..start + len` of a scroll
17/// view's content in its `viewport` as `align` says, from `offset`.
18fn aligned(start: f32, len: f32, viewport: f32, offset: f32, align: ScrollAlignment) -> f32 {
19    match align {
20        ScrollAlignment::Start => start,
21        ScrollAlignment::Center => start + (len - viewport) / 2.0,
22        ScrollAlignment::End => start + len - viewport,
23        // CSSOM View's "determine the scroll-into-view position".
24        ScrollAlignment::Nearest => {
25            let before = start < offset;
26            let after = start + len > offset + viewport;
27            if before == after {
28                offset
29            } else if before == (len <= viewport) {
30                start
31            } else {
32                start + len - viewport
33            }
34        }
35    }
36}
37
38/// Where a view is, from the last layout (`ref.measure()`).
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct Measurement {
41    /// The frame relative to the parent view, as `onLayout` reports it.
42    pub frame: Bounds<Points>,
43    /// The top left corner in the coordinates of the root view the view is
44    /// in (the surface, or the modal it is shown in): those of touches'
45    /// `pageX` / `pageY` (`pagePosition`). Scroll offsets and zoom scales of the scroll
46    /// views and lists around it are applied; transforms are not.
47    pub page: Point<Points>,
48}
49
50impl Measurement {
51    /// The JS object `ref.measure()` resolves to.
52    pub(crate) fn to_json(self) -> JsonValue {
53        serde_json::json!({
54            "bounds": {
55                "origin": { "x": self.frame.origin.x.0, "y": self.frame.origin.y.0 },
56                "size": { "width": self.frame.size.width.0, "height": self.frame.size.height.0 },
57            },
58            "pagePosition": { "x": self.page.x.0, "y": self.page.y.0 },
59        })
60    }
61}
62
63/// Where a list's viewport starts among its rows
64/// (`ref.measureScrollPosition()`), as GPUI's `ListOffset`: the row there
65/// and how far into it, along the list's axis from the side item 0 is on
66/// (the top, the bottom of an inverted list). Scrolling the list to row
67/// `index` with a view offset of `-offset` puts the viewport's start back
68/// there, wherever the list's sizes still are estimates.
69#[derive(Debug, Clone, Copy, Default, PartialEq)]
70#[non_exhaustive]
71pub struct ListScrollPosition {
72    /// The first item of the row the viewport starts in (`0` while it
73    /// starts in the header or before it).
74    pub index: u32,
75    /// How far past the row's start the viewport starts: negative before
76    /// the first row, past the row's size in the gap after it.
77    pub offset: Points,
78}
79
80impl ListScrollPosition {
81    /// The JS object `ref.measureScrollPosition()` resolves to.
82    pub(crate) fn to_json(self) -> JsonValue {
83        serde_json::json!({ "index": self.index, "offset": self.offset.0 })
84    }
85}
86
87/// Descendants reaching less than this far out of a view do not count
88/// (rounding).
89const OVERFLOW_EPSILON: f32 = 0.5;
90
91/// How a pointer meets a node ([`Core::pointer_hit`]).
92struct PointerHit {
93    /// The node itself is hit.
94    own: bool,
95    /// Its children are looked into.
96    children: bool,
97    /// The point in its content (its scroll offset and zoom undone).
98    inner: Point<Points>,
99}
100
101pub(super) fn valid(r: &Bounds<Points>) -> bool {
102    !(r.origin.x.0.is_nan()
103        || r.origin.y.0.is_nan()
104        || r.size.width.0.is_nan()
105        || r.size.height.0.is_nan())
106}
107
108impl<M: TextEngine> Core<M> {
109    /// The view a pointer pressing at `page` (in the root view `id` is in)
110    /// would press inside `id`, with the last layout: the innermost,
111    /// topmost one there that hears presses, and the point in it. `id`'s
112    /// own `pointerEvents` do not count: the component asking lies a hit
113    /// layer of its own over it.
114    pub(super) fn press_target(
115        &self,
116        id: NodeId,
117        page: Point<Points>,
118    ) -> Option<(NodeId, Point<Points>)> {
119        let origin = self.measure(id)?.page;
120        let key = self.key(id).ok()?;
121        self.press_target_in(key, point(page.x - origin.x, page.y - origin.y), true)
122    }
123
124    fn press_target_in(
125        &self,
126        key: Key,
127        p: Point<Points>,
128        top: bool,
129    ) -> Option<(NodeId, Point<Points>)> {
130        let hit = self.pointer_hit(key, p, top)?;
131        if hit.children {
132            for child in self.hit_children(key) {
133                let origin = self.nodes[child as usize].frame.origin;
134                let at = point(hit.inner.x - origin.x, hit.inner.y - origin.y);
135                if let Some(hit) = self.press_target_in(child, at, false) {
136                    return Some(hit);
137                }
138            }
139        }
140        let node = &self.nodes[key as usize];
141        (hit.own && node.mounted_events().contains(crate::EventKind::Press)).then_some((node.id, p))
142    }
143
144    /// How a pointer at `p` (`key`'s coordinates) meets `key`: `None` when
145    /// neither it nor anything in it can be hit there. `top`: `key`'s own
146    /// `pointerEvents` do not count.
147    fn pointer_hit(&self, key: Key, p: Point<Points>, top: bool) -> Option<PointerHit> {
148        use crate::props::PointerEvents;
149        let node = &self.nodes[key as usize];
150        if node.layout.is_none()
151            || !valid(&node.frame)
152            || node.view_style.hidden
153            || node.hidden_in_text
154        {
155            return None;
156        }
157        let pointer = match node.props.as_deref().map(|p| p.pointer_events) {
158            Some(PointerEvents::Auto) | None => node.class_pointer,
159            Some(set) => set,
160        };
161        let pointer = if top { PointerEvents::Auto } else { pointer };
162        if pointer == PointerEvents::None {
163            return None;
164        }
165        let size = node.frame.size;
166        let inside = p.x.0 >= 0.0 && p.y.0 >= 0.0 && p.x < size.width && p.y < size.height;
167        let clips = node.view_style.overflow_hidden
168            || matches!(node.kind, Kind::Scroll | Kind::List | Kind::Stack);
169        if !inside && (clips || pointer == PointerEvents::BoxOnly) {
170            return None;
171        }
172        // Outside its `clipPath`, neither the view nor anything in it.
173        if node
174            .view_style
175            .clip_path()
176            .is_some_and(|c| !c.contains(size, p))
177        {
178            return None;
179        }
180        let inner = match node.scroll.as_deref() {
181            Some(scroll) => {
182                let (sx, sy) = self.content_offset(scroll, node.list.as_deref());
183                point(
184                    Points((p.x.0 + sx) / scroll.zoom),
185                    Points((p.y.0 + sy) / scroll.zoom),
186                )
187            }
188            None => p,
189        };
190        Some(PointerHit {
191            own: inside && pointer != PointerEvents::BoxNone,
192            children: pointer != PointerEvents::BoxOnly,
193            inner,
194        })
195    }
196
197    /// The children of `key` a pointer can hit, topmost first: the last of
198    /// the highest `zIndex`.
199    fn hit_children(&self, key: Key) -> Vec<Key> {
200        let mut children: Vec<Key> = self.nodes[key as usize]
201            .children
202            .iter()
203            .copied()
204            .filter(|&c| {
205                let child = &self.nodes[c as usize];
206                !child.inline && !child.is_overlay()
207            })
208            .collect();
209        children.sort_by_key(|&c| self.nodes[c as usize].z_index);
210        children.reverse();
211        children
212    }
213
214    /// The views a pointer at `p` (`key`'s coordinates) is over in `key`,
215    /// innermost first, each with the point in it, as a platform picks
216    /// them: the innermost, topmost view hit and the views around it.
217    fn hover_path_in(
218        &self,
219        key: Key,
220        p: Point<Points>,
221        top: bool,
222        path: &mut Vec<(Key, Point<Points>)>,
223    ) -> bool {
224        let Some(hit) = self.pointer_hit(key, p, top) else {
225            return false;
226        };
227        let inner = hit.children
228            && self.hit_children(key).into_iter().any(|child| {
229                let origin = self.nodes[child as usize].frame.origin;
230                let at = point(hit.inner.x - origin.x, hit.inner.y - origin.y);
231                self.hover_path_in(child, at, false, path)
232            });
233        if inner || hit.own {
234            path.push((key, p));
235        }
236        inner || hit.own
237    }
238
239    /// Passes the pointers components passed on into their elements
240    /// ([`crate::element::ElementRef::hover_at`]) with the last layout:
241    /// the views that track hovers or hear the mouse under each are
242    /// hovered, those it left hear so from the inside out, then those it
243    /// came over from the outside in, then `onMouseMove` of the hovered
244    /// ones, inside out.
245    pub(super) fn pass_hovers(&mut self) {
246        use crate::{EventKind, element::JsEvent};
247        for (id, mouse) in std::mem::take(&mut self.components.hovers) {
248            let mut path = Vec::new();
249            if let Some(mouse) = mouse
250                && let Some(origin) = self.measure(id).map(|m| m.page)
251                && let Ok(key) = self.key(id)
252            {
253                let at = point(
254                    mouse.page_position.x - origin.x,
255                    mouse.page_position.y - origin.y,
256                );
257                self.hover_path_in(key, at, true, &mut path);
258            }
259            let hovered: Vec<(Key, Point<Points>)> = path
260                .into_iter()
261                .filter(|&(k, _)| {
262                    let n = &self.nodes[k as usize];
263                    crate::input::hoverable(n.tracked, n.mounted_events())
264                })
265                .collect();
266            let ids: Vec<NodeId> = hovered
267                .iter()
268                .map(|&(k, _)| self.nodes[k as usize].id)
269                .collect();
270            let old = match ids.is_empty() {
271                true => self.passed_hovers.remove(&id),
272                false => self.passed_hovers.insert(id, ids.clone()),
273            }
274            .unwrap_or_default();
275            let event = |position: Point<Points>| {
276                EventPayload::Mouse(crate::MouseEvent {
277                    position,
278                    ..mouse.unwrap_or_default()
279                })
280            };
281            let (left, entered) = crate::input::hover_changes(&old, &ids);
282            let (left, entered): (Vec<NodeId>, Vec<NodeId>) =
283                (left.copied().collect(), entered.copied().collect());
284            for node in left {
285                let Ok(key) = self.key(node) else { continue };
286                if !std::mem::take(&mut self.nodes[key as usize].passed_hover) {
287                    continue;
288                }
289                self.states_changed(key);
290                if self.nodes[key as usize]
291                    .mounted_events()
292                    .contains(EventKind::MouseLeave)
293                {
294                    let position = match (mouse, self.measure(node)) {
295                        (Some(m), Some(at)) => {
296                            point(m.page_position.x - at.page.x, m.page_position.y - at.page.y)
297                        }
298                        _ => Point::default(),
299                    };
300                    self.events
301                        .push(JsEvent::Event(node, EventKind::MouseLeave, event(position)));
302                }
303            }
304            for node in entered {
305                let Some(&(key, position)) = hovered
306                    .iter()
307                    .find(|&&(k, _)| self.nodes[k as usize].id == node)
308                else {
309                    continue;
310                };
311                self.nodes[key as usize].passed_hover = true;
312                self.states_changed(key);
313                if self.nodes[key as usize]
314                    .mounted_events()
315                    .contains(EventKind::MouseEnter)
316                {
317                    self.events
318                        .push(JsEvent::Event(node, EventKind::MouseEnter, event(position)));
319                }
320            }
321            for &(key, position) in &hovered {
322                let node = &self.nodes[key as usize];
323                if node.mounted_events().contains(EventKind::MouseMove) {
324                    self.events.push(JsEvent::Event(
325                        node.id,
326                        EventKind::MouseMove,
327                        event(position),
328                    ));
329                }
330            }
331        }
332    }
333
334    /// The text of node `id` and the nodes inside it, in tree order
335    /// ([`crate::element::ElementRef::text_content`]): what `display:
336    /// none` hides is left out; empty when it is not in the tree.
337    pub(super) fn text_content(&self, id: NodeId) -> String {
338        let mut text = String::new();
339        let Ok(key) = self.key(id) else {
340            return text;
341        };
342        let mut stack = vec![key];
343        while let Some(k) = stack.pop() {
344            let node = &self.nodes[k as usize];
345            if node.layout.is_some_and(|l| self.layout.displays_none(l)) {
346                continue;
347            }
348            if node.kind == Kind::RawText {
349                text.push_str(&node.text);
350            }
351            if let Some(run) = self.folded_text(k) {
352                text.push_str(run);
353            }
354            stack.extend(node.children.iter().rev().copied());
355        }
356        text
357    }
358
359    /// The content offset `scroll` shows with this commit: the platform's
360    /// last report, plus the instant scrolls the core sent or queued which
361    /// that report does not count yet. An animated scroll not applied yet
362    /// has not moved the content; its movement is what the platform
363    /// reports while it runs. The cross axis is the reported one. `list`
364    /// is the node's own list (`None` for a plain scroll view).
365    pub(super) fn content_offset(
366        &self,
367        scroll: &ScrollState,
368        list: Option<&ListState>,
369    ) -> (f32, f32) {
370        // Nothing sent or queued is unreported: what shows is the report.
371        // A list keeps the scrolls it issued in its own `pending`.
372        if list.is_none_or(ListState::settled)
373            && scroll.asked.is_none()
374            && scroll.pending.is_empty()
375        {
376            return scroll.offset;
377        }
378        let reported = if scroll.horizontal {
379            scroll.offset.0
380        } else {
381            scroll.offset.1
382        };
383        let shown = match list.filter(|list| !list.parent) {
384            Some(list) => list.shown_offset(reported),
385            None => super::list::replay_shown(reported, &scroll.pending),
386        };
387        let shown = scroll
388            .asked
389            .as_ref()
390            .map_or(shown, |asked| asked.shown(shown));
391        if scroll.horizontal {
392            (shown, scroll.offset.1)
393        } else {
394            (scroll.offset.0, shown)
395        }
396    }
397
398    /// Whether view `key` is a root view of its own, so positions in it do
399    /// not add its ancestors': modals, input accessories and the header
400    /// items a native header places. A screen's drawn `header` slot (no
401    /// native header, as on desktop) is a view in its screen.
402    fn own_root_view(&self, key: Key) -> bool {
403        let n = &self.nodes[key as usize];
404        match n.kind {
405            Kind::Modal | Kind::InputAccessory => true,
406            Kind::HeaderItem => {
407                self.native_header()
408                    || !n
409                        .root
410                        .as_ref()
411                        .is_some_and(|r| r.slot == HeaderSlot::Header)
412            }
413            _ => false,
414        }
415    }
416
417    /// Where view `id` is, from the last layout; `None` when it is not in
418    /// the tree or was never laid out.
419    pub fn measure(&self, id: NodeId) -> Option<Measurement> {
420        let key = self.key(id).ok()?;
421        let node = &self.nodes[key as usize];
422        if !(node.created || node.culled) || node.layout.is_none() || !valid(&node.frame) {
423            return None;
424        }
425        // Detached (not in the tree): no position.
426        if key != self.root && !self.in_tree(key) {
427            return None;
428        }
429        let (mut x, mut y) = (0.0f32, 0.0f32);
430        let mut k = key;
431        while k != NO_KEY {
432            let n = &self.nodes[k as usize];
433            // Modals (and the views UIKit places) are root views of their
434            // own: positions are in them. A screen fills its stack.
435            if self.own_root_view(k) {
436                break;
437            }
438            // Spans and raw text have no view; text attachments are placed
439            // in their text block.
440            if n.layout.is_some() && valid(&n.frame) {
441                x += n.frame.origin.x.0;
442                y += n.frame.origin.y.0;
443            }
444            // An overlay is placed in its root view.
445            if n.is_overlay() {
446                break;
447            }
448            let parent = n.parent;
449            if parent == NO_KEY {
450                break;
451            }
452            // In a scroll view's content: where the content shows with
453            // this batch (`Core::content_offset`).
454            let parent_node = &self.nodes[parent as usize];
455            if let Some(scroll) = parent_node.scroll.as_deref() {
456                let (sx, sy) = self.content_offset(scroll, parent_node.list.as_deref());
457                x = x * scroll.zoom - sx;
458                y = y * scroll.zoom - sy;
459            }
460            k = parent;
461        }
462        Some(Measurement {
463            frame: node.frame,
464            page: point(Points(x), Points(y)),
465        })
466    }
467
468    /// Inline attachments get their positions from their text's final layout.
469    /// A reveal must make a culled text first, as other commands make their view,
470    /// so its attachment can be measured before reveal expands into scrolls.
471    pub(super) fn prepare_reveals(&mut self) {
472        for index in 0..self.commands.len() {
473            let (id, command) = &self.commands[index];
474            if !matches!(command, Command::Reveal(_)) {
475                continue;
476            }
477            let Ok(mut key) = self.key(*id) else {
478                continue;
479            };
480            while key != NO_KEY {
481                if let Some(block) = self.attachment_block(key) {
482                    if !self.nodes[block as usize].created {
483                        self.uncull(block);
484                    }
485                    break;
486                }
487                key = self.nodes[key as usize].parent;
488            }
489        }
490    }
491
492    /// The `ScrollTo` commands that bring view `id` into view, as
493    /// `options` places it: one for each scroll view around it that has to
494    /// move, innermost first, each from where the ones inside it end up.
495    /// Lists and the root view's own scrolling are left alone. None when
496    /// the view is not laid out. A scroll view in `projected` (the offsets
497    /// earlier commands of the commit scroll it to, the last one last) is
498    /// taken to be there.
499    pub(super) fn reveal_scrolls(
500        &self,
501        id: NodeId,
502        options: RevealOptions,
503        projected: &[(NodeId, (f32, f32))],
504    ) -> Vec<(NodeId, Command)> {
505        let mut scrolls = Vec::new();
506        if self.measure(id).is_none() {
507            log::warn!("reveal: view {id} is not laid out");
508            return scrolls;
509        }
510        let Ok(mut k) = self.key(id) else {
511            return scrolls;
512        };
513        let size = self.nodes[k as usize].frame.size;
514        let (mut x, mut y) = (0.0f32, 0.0f32);
515        let (mut width, mut height) = (size.width.0, size.height.0);
516        while k != NO_KEY {
517            let n = &self.nodes[k as usize];
518            if self.own_root_view(k) {
519                break;
520            }
521            if n.layout.is_some() && valid(&n.frame) {
522                x += n.frame.origin.x.0;
523                y += n.frame.origin.y.0;
524            }
525            if n.is_overlay() || n.parent == NO_KEY {
526                break;
527            }
528            let parent = &self.nodes[n.parent as usize];
529            if let Some(scroll) = parent.scroll.as_deref() {
530                (x, y) = (x * scroll.zoom, y * scroll.zoom);
531                (width, height) = (width * scroll.zoom, height * scroll.zoom);
532                let mut offset = scroll.offset;
533                // A culled scroll view is made for its command.
534                if parent.kind == Kind::Scroll && valid(&parent.frame) {
535                    let viewport = parent.frame.size;
536                    let inset = scroll.behavior.content_inset;
537                    // The range the platforms scroll over: the content and its insets.
538                    let range =
539                        |content: Option<Points>, viewport: Points, lead: Points, trail: Points| {
540                            let most = content.map_or(f32::INFINITY, |c| (c + trail - viewport).0);
541                            (-lead.0, most.max(-lead.0))
542                        };
543                    let content = (
544                        scroll.content.map(|c| c.width),
545                        scroll.content.map(|c| c.height),
546                    );
547                    let x_range = range(content.0, viewport.width, inset.left, inset.right);
548                    let y_range = range(content.1, viewport.height, inset.top, inset.bottom);
549                    let issued = projected
550                        .iter()
551                        .rfind(|(s, _)| *s == parent.id)
552                        .map(|&(_, to)| to)
553                        .or(scroll.target.map(|(_, to)| to));
554                    if let Some((px, py)) = issued {
555                        offset = (
556                            px.clamp(x_range.0, x_range.1),
557                            py.clamp(y_range.0, y_range.1),
558                        );
559                    }
560                    // Unclamped when it stays: UIKit adds insets the core does not know.
561                    let settle = |to: f32, at: f32, (least, most): (f32, f32)| {
562                        if to == at { at } else { to.clamp(least, most) }
563                    };
564                    let to = if scroll.horizontal {
565                        let to = aligned(x, width, viewport.width.0, offset.0, options.horizontal);
566                        (settle(to, offset.0, x_range), offset.1)
567                    } else {
568                        let to = aligned(y, height, viewport.height.0, offset.1, options.vertical);
569                        (offset.0, settle(to, offset.1, y_range))
570                    };
571                    if to != offset {
572                        scrolls.push((
573                            parent.id,
574                            Command::ScrollTo {
575                                x: Points(to.0),
576                                y: Points(to.1),
577                                animated: options.animated,
578                            },
579                        ));
580                        offset = to;
581                    }
582                }
583                (x, y) = (x - offset.0, y - offset.1);
584            }
585            k = n.parent;
586        }
587        scrolls
588    }
589
590    /// The offset `command` scrolls scroll view `id` to, when it does.
591    pub(super) fn scrolled_to(&self, id: NodeId, command: &Command) -> Option<(f32, f32)> {
592        let node = &self.nodes[self.key(id).ok()? as usize];
593        if node.kind != Kind::Scroll {
594            return None;
595        }
596        let scroll = node.scroll.as_deref()?;
597        match *command {
598            Command::ScrollTo { x, y, .. } => Some((x.0, y.0)),
599            Command::ScrollToEnd { .. } => {
600                let content = scroll.content?;
601                let viewport = node.frame.size;
602                Some(if scroll.horizontal {
603                    ((content.width - viewport.width).0.max(0.0), 0.0)
604                } else {
605                    (0.0, (content.height - viewport.height).0.max(0.0))
606                })
607            }
608            _ => None,
609        }
610    }
611
612    /// Completes an input's `onCaretMove` payload from its platform: adds
613    /// `pageBounds`, its `bounds` (in the input) moved by where the input is
614    /// in its root view. The platforms know the caret in their text views,
615    /// the core where the input is (`ref.measure()`'s `pagePosition`, with
616    /// the scroll views around it).
617    pub fn locate_caret(&self, id: NodeId, payload: &mut EventPayload) {
618        if matches!(payload, EventPayload::None) {
619            *payload = EventPayload::Map(Vec::new());
620        }
621        let EventPayload::Map(fields) = payload else {
622            return;
623        };
624        if fields.iter().any(|(k, _)| *k == "pageBounds") {
625            return;
626        }
627        // A platform that could not place the caret reports an empty one.
628        let caret = match fields.iter().find(|(k, _)| *k == "bounds") {
629            Some(&(_, PayloadValue::Bounds(caret))) => caret,
630            _ => {
631                fields.retain(|(k, _)| *k != "bounds");
632                fields.push(("bounds", PayloadValue::Bounds(Bounds::default())));
633                Bounds::default()
634            }
635        };
636        fields.push((
637            "pageBounds",
638            PayloadValue::Bounds(self.page_bounds(id, caret)),
639        ));
640    }
641
642    /// Completes a selectable view's `onSelectionChange` payload from its
643    /// platform: adds `pageBounds`, its `bounds` (the selected text in the
644    /// view) moved by where the view is in its root view, as
645    /// [`Self::locate_caret`] does for a caret. A payload without `bounds`
646    /// (nothing selected, an input's selection) stays as it is.
647    pub fn locate_selection(&self, id: NodeId, payload: &mut EventPayload) {
648        let EventPayload::Map(fields) = payload else {
649            return;
650        };
651        if fields.iter().any(|(k, _)| *k == "pageBounds") {
652            return;
653        }
654        if let Some(&(_, PayloadValue::Bounds(selected))) =
655            fields.iter().find(|(k, _)| *k == "bounds")
656        {
657            fields.push((
658                "pageBounds",
659                PayloadValue::Bounds(self.page_bounds(id, selected)),
660            ));
661        }
662    }
663
664    /// `bounds` in view `id` moved by where the view is in its root view.
665    fn page_bounds(&self, id: NodeId, bounds: Bounds<Points>) -> Bounds<Points> {
666        let page = self.measure(id).map_or(Point::default(), |m| m.page);
667        Bounds {
668            origin: point(page.x + bounds.origin.x, page.y + bounds.origin.y),
669            size: bounds.size,
670        }
671    }
672
673    /// Whether `key` hangs from the main tree's root or a root view that
674    /// does.
675    pub(super) fn in_tree(&self, mut key: Key) -> bool {
676        while key != NO_KEY {
677            if key == self.root {
678                return true;
679            }
680            key = self.nodes[key as usize].parent;
681        }
682        false
683    }
684
685    /// Answers `ref.measure()` call `call` on `id` (null when it is not
686    /// laid out).
687    pub(super) fn answer_measure(&mut self, id: NodeId, call: u32) {
688        let value = self
689            .measure(id)
690            .map_or(JsonValue::Null, Measurement::to_json);
691        self.settle(call, Ok(Box::new(value)));
692    }
693
694    /// Where list `id`'s viewport starts among its rows, from the last
695    /// layout; `None` when it is no list in the tree, is not laid out or
696    /// has no items.
697    pub fn list_scroll_position(&self, id: NodeId) -> Option<ListScrollPosition> {
698        let key = self.key(id).ok()?;
699        let node = &self.nodes[key as usize];
700        if !node.created || (key != self.root && !self.in_tree(key)) {
701            return None;
702        }
703        let (index, offset) = node.list.as_ref()?.scroll_position()?;
704        Some(ListScrollPosition {
705            index,
706            offset: Points(offset),
707        })
708    }
709
710    /// Answers JS's `ref.measureScrollPosition()` call `call`.
711    pub(super) fn answer_scroll_position(&mut self, id: NodeId, call: u32) {
712        let value = self
713            .list_scroll_position(id)
714            .map_or(JsonValue::Null, ListScrollPosition::to_json);
715        self.settle(call, Ok(Box::new(value)));
716    }
717
718    /// Updates the area `key`'s descendants cover outside its bounds (its
719    /// children's frames and areas are current), and mounts it when it
720    /// changed; whether it did. The area takes in the descendants' hit
721    /// slop, so a touch there reaches them through every view around.
722    /// Clipping views have none: what is outside is not drawn, and takes
723    /// no touches.
724    pub(super) fn update_overflow(&mut self, key: Key) -> bool {
725        let node = &self.nodes[key as usize];
726        if !node.created || key == self.root {
727            return false;
728        }
729        let clips = node.view_style.overflow_hidden
730            || matches!(node.kind, Kind::Scroll | Kind::List | Kind::Stack);
731        let extent = if clips || !valid(&node.frame) || node.children.is_empty() {
732            None
733        } else {
734            let (w, h) = (node.frame.size.width.0, node.frame.size.height.0);
735            let (mut x0, mut y0, mut x1, mut y1) = (0.0f32, 0.0f32, w, h);
736            for &child in &node.children {
737                let c = &self.nodes[child as usize];
738                if c.is_layout_root() || c.layout.is_none() || !c.created || !valid(&c.frame) {
739                    continue;
740                }
741                let f = c.frame;
742                let slop = c
743                    .props
744                    .as_ref()
745                    .map_or(EdgeInsets::default(), |p| p.hit_slop);
746                let (sx0, sy0) = (f.origin.x.0 - slop.left.0, f.origin.y.0 - slop.top.0);
747                let sx1 = f.origin.x.0 + f.size.width.0 + slop.right.0;
748                let sy1 = f.origin.y.0 + f.size.height.0 + slop.bottom.0;
749                if sx1 > sx0 && sy1 > sy0 {
750                    x0 = x0.min(sx0);
751                    y0 = y0.min(sy0);
752                    x1 = x1.max(sx1);
753                    y1 = y1.max(sy1);
754                }
755                if let Some(e) = c.overflow {
756                    x0 = x0.min(f.origin.x.0 + e.origin.x.0);
757                    y0 = y0.min(f.origin.y.0 + e.origin.y.0);
758                    x1 = x1.max(f.origin.x.0 + e.origin.x.0 + e.size.width.0);
759                    y1 = y1.max(f.origin.y.0 + e.origin.y.0 + e.size.height.0);
760                }
761            }
762            let out = x0 < -OVERFLOW_EPSILON
763                || y0 < -OVERFLOW_EPSILON
764                || x1 > w + OVERFLOW_EPSILON
765                || y1 > h + OVERFLOW_EPSILON;
766            out.then_some(rect(x0, y0, x1 - x0, y1 - y0))
767        };
768        let node = &mut self.nodes[key as usize];
769        if node.overflow == extent {
770            return false;
771        }
772        node.overflow = extent;
773        let id = node.id;
774        self.mount.push(MountItem::Overflow { id, extent });
775        true
776    }
777
778    /// Works out again the areas of the views around those whose hit slop
779    /// changed, after the round's layout: up from each, while an area
780    /// changes.
781    pub(super) fn update_slop_overflow(&mut self) {
782        let mut moved = std::mem::take(&mut self.slop_moved);
783        for &key in &moved {
784            if !self.nodes.contains(key as usize) || !self.nodes[key as usize].created {
785                continue;
786            }
787            let mut parent = self.nodes[key as usize].parent;
788            while parent != NO_KEY && self.update_overflow(parent) {
789                parent = self.nodes[parent as usize].parent;
790            }
791        }
792        // The buffer, for the next round.
793        moved.clear();
794        self.slop_moved = moved;
795    }
796}