Skip to main content

nsh_core/core/
overlay.rs

1//! Overlays ([`crate::overlay`]): an `<overlay>` node stays where the app
2//! put it (its parent's child for the reactive graph, events, lifetime,
3//! inherited text styles), while its native view is in the root view
4//! around it (the surface, or the nearest modal), above that root view's
5//! own children and the overlays shown before it.
6//!
7//! Each commit [`Core::sync_overlays`] works out which overlays are shown
8//! (every view around them is, and the overlays around them are) and in
9//! which root view, and moves their native views there: one opened later
10//! goes on top. An overlay is a layout root of its own, laid out in a box
11//! the size of its root view (`position: fixed`), or with an anchor in the
12//! room it is placed in (the root view's safe area less its `margin`: its
13//! percentage sizes and insets are against that room), and placed against
14//! its anchor when it has one ([`crate::overlay::place`]); it follows the
15//! anchor as it moves ([`Core::place_overlays`], after the lists and scroll
16//! offsets of the commit). The core also routes what dismissing
17//! takes: presses outside (`onPressOutside`: the overlays watching them,
18//! their anchors and root views listen to touches while they are shown)
19//! and Escape / the back button (`onCancel`, to the top overlay listening:
20//! a binding of the root's table and the root's back listener while one
21//! is shown). Closing is the app's (`nsh-base`'s components). A shown
22//! overlay's content goes in the Tab order where the app put it, after the
23//! view before it there ([`Core::order_overlays_for_tab`],
24//! [`crate::ViewProps::tab_after`]), not after its root view's children.
25//!
26//! A hint overlay ([`OverlayConfig::hint`]) is shown by the core: its
27//! anchor (its parent without one) listens to the pointer coming and going
28//! while the overlay is in the view on a desktop; the pointer resting on it
29//! for the hint's delay shows the hint (a task of the components' executor
30//! wakes the engine then), the pointer leaving or pressing it hides it, as
31//! GPUI's tooltips do. Once the pointer showed one, it moves on without
32//! waiting: the pointer coming to an anchor within the hint's grace period
33//! after it left one whose hint it showed, or while one it showed is still
34//! in the view, shows it at once ([`Core::hint_skips_delay`],
35//! `gpui-base`'s `TooltipDefaults` grace period, Radix's
36//! `skipDelayDuration`); a press on an anchor or Escape ends the period,
37//! and the focus starts none. In every idiom the focus the keyboard moved
38//! shows it too, as WAI-ARIA's tooltips: the focus that Tab, an arrow, a
39//! shortcut or the app's `focus()` after a key brought to its anchor (or
40//! into it, outside an overlay, the nearest hint's) shows it at once until
41//! the focus leaves ([`Core::focus_hints`]), by `focus-visible:`'s rule
42//! ([`Core::focus_shows`]) without its exception for an input that edits.
43//! A press, a tap or a click that brings the focus leaves the hint to the
44//! pointer, as Radix's tooltips do: the press hid it, and it shows again
45//! when the pointer comes back and rests, so nothing stays up once the
46//! pointer left. Escape hides a hint that is shown
47//! ([`Core::overlay_escape`]). The overlay hears what it asks for (`Show`,
48//! `Dismiss`, with the [`HintReason`]), so a component owning it
49//! (`nsh-base`'s `Tooltip`) can decide instead ([`OverlayConfig::open`]). An element's `tooltip` is a
50//! hint overlay the core makes inside the element ([`Core::set_tooltip`]).
51
52use rustc_hash::FxHashMap;
53use taffy::NodeId as LayoutId;
54
55use super::{Core, Key, Kind, NO_KEY, definite};
56use crate::{
57    ContextMenuEvent, EventKind, EventPayload, NodeId, PayloadValue, PointerType, Prop, ROOT_ID,
58    Tag, TextEngine, TouchEvent, TouchPhase,
59    element::{
60        HintReason,
61        task::{Action, Task, act_after},
62    },
63    geometry::{Bounds, Point, Points, Size, point, px, rect},
64    keymap::{KeyBinding, Keystroke, When},
65    mount::MountItem,
66    ops::{Op, OverlayProp},
67    overlay::{
68        HINT_DELAY, HINT_ENDLESS, HINT_GRACE_PERIOD, OverlayAnchor, OverlayConfig, Placed,
69        Placement, TooltipContent, inset, place, place_fitted,
70    },
71    props::PointerEvents,
72};
73
74/// What the overlays have a node listen to (`Node::overlay_watched`).
75pub(super) mod watch {
76    /// Touches, for an overlay's `onPressOutside`.
77    pub(in crate::core) const PRESS: u8 = 1;
78    /// The pointer coming and going and touches, for a hint.
79    pub(in crate::core) const HINT: u8 = 2;
80}
81
82/// The gap between an element and its `tooltip`, and the distance the
83/// tooltip keeps from the safe area's edges.
84const TOOLTIP_GAP: f32 = 4.0;
85
86/// A hint's wait for the pointer to rest (dropping it cancels it).
87pub(super) struct HintTimer(#[allow(dead_code)] Task<()>);
88
89impl std::fmt::Debug for HintTimer {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.write_str("HintTimer")
92    }
93}
94
95/// The nodes the core made for an element's `tooltip`.
96#[derive(Debug, Clone, Copy)]
97pub(super) struct CoreTooltip {
98    /// The hint overlay, a child of the element.
99    pub(super) overlay: NodeId,
100    /// The element shown as the tooltip, inside the overlay (JS's).
101    content: Option<NodeId>,
102}
103
104/// The binding id of Escape while an overlay listens to `onCancel`: above
105/// any JS gives and any view's ([`crate::element::keys::FIRST_ID`] counts up).
106pub(super) const ESCAPE_BINDING: u32 = u32::MAX;
107
108/// An overlay's own state.
109#[derive(Debug)]
110pub(super) struct OverlayState {
111    /// How it is placed.
112    pub(super) config: OverlayConfig,
113    /// A layout node the size of the root view, holding the overlay's as
114    /// an absolutely placed child: what its insets and percentages are
115    /// against.
116    pub(super) wrapper: LayoutId,
117    /// The root view its native view is in, while it is shown.
118    pub(super) host: Option<NodeId>,
119    /// Where it was placed last, as `onPosition` reported it.
120    pub(super) placed: Option<(Placed, Bounds<Points>)>,
121    pub(super) native_anchor: Option<crate::overlay::PlacedAnchor>,
122    /// The view it follows in the Tab order while it is shown
123    /// ([`crate::ViewProps::tab_after`], [`Core::order_overlays_for_tab`]).
124    pub(super) tab_after: Option<NodeId>,
125    /// Its `margin` was set: it keeps that from the edges, else the app's
126    /// overlay margin ([`Core::set_snap_to_window_margin`]).
127    pub(super) margin_set: bool,
128    /// A hint: the pointer rested on its anchor, and has not left or
129    /// pressed it since.
130    pub(super) hinted: bool,
131    /// A hint: the pointer is on its anchor, resting until it shows.
132    pub(super) waiting: Option<HintTimer>,
133    /// A hint: the focus is on its anchor, whatever brought it there.
134    pub(super) focus_on: bool,
135    /// A hint: the focus on its anchor shows it, the keyboard having
136    /// brought it there (`Core::focus_by_keyboard`), and no Escape or
137    /// press hid it since.
138    pub(super) focus_shown: bool,
139    /// A hint on a link of a text (a span, which has no frame of its own):
140    /// where the pointer came over it, in its root view's coordinates,
141    /// what it is placed against ([`Core::resolved_anchor`]).
142    pub(super) pointer: Option<Point<Points>>,
143    /// Its `cover` view's frame in it, once that was laid out, with the
144    /// overlay's size and the view's frame in its parent then.
145    pub(super) covered: Option<(Bounds<Points>, Size<Points>, Bounds<Points>)>,
146    /// The room `onPosition` last told it (`available`), kept while it is
147    /// hidden: an overlay whose max size along its side is still that room
148    /// when shown again follows it ([`Core::natural_extent`]).
149    pub(super) told: Option<Size<Points>>,
150    /// Its extent along its side without the room it was told, measured
151    /// once per layout while that room holds it ([`Core::natural_extent`]).
152    pub(super) natural: Option<Points>,
153    /// The max size it was last found held to, along its side: still that
154    /// room's while the app has yet to take the newer one `told` carries
155    /// (the core flipped it, and told it so, in the same commit).
156    pub(super) held: Option<Points>,
157}
158
159impl OverlayState {
160    /// A hint the pointer or the focus the keyboard moved shows.
161    fn hint_shown(&self) -> bool {
162        self.hinted || self.focus_shown
163    }
164}
165
166/// What the overlays add to the native side: the nodes listening to
167/// touches for `onPressOutside`, and whether Escape and back are taken.
168#[derive(Debug, Default)]
169pub(super) struct Overlays {
170    /// The shown overlays and the other nodes listening to touches for
171    /// them (their anchors and root views), checked by id (keys are
172    /// reused).
173    pub(super) watched: Vec<(Key, NodeId)>,
174    /// A shown overlay listens to `onCancel`: Escape is bound and the back
175    /// button listened to.
176    pub(super) cancel: bool,
177    /// A hint is shown: Escape is bound (it hides it).
178    pub(super) hint_escape: bool,
179    /// The keyboard focus is inside the top overlay listening to
180    /// `onCancel`, on a view whose `captureKeys` (or an enabled
181    /// ancestor's within that overlay) takes Escape: the key is the
182    /// content's, so the overlay does not bind it (#2424).
183    pub(super) escape_to_focus: bool,
184    /// The anchors of the hints in the view listening to the pointer
185    /// (desktops), checked by id.
186    pub(super) hinting: Vec<(Key, NodeId)>,
187    /// When the hints' grace period started: the pointer left an anchor
188    /// whose hint it showed, in the view. `None`: none runs (a press on an
189    /// anchor or Escape ended it).
190    pub(super) grace_from: Option<crate::time::Instant>,
191    /// The elements with a `tooltip`, by id: the nodes made for it.
192    pub(super) tooltips: FxHashMap<NodeId, CoreTooltip>,
193}
194
195impl<M: TextEngine> Core<M> {
196    /// A new overlay node `key` with layout node `layout`: its wrapper.
197    pub(super) fn overlay_made(&mut self, key: Key, layout: LayoutId) {
198        let wrapper = self
199            .layout
200            .new_with_children(taffy::Style::default(), &[layout]);
201        // A terminal sizes a box by its content unless told its explicit
202        // size is its size: the wrapper's is its host's, the box the
203        // overlay's room is measured in (without it, 0 rows, and the
204        // overlay's content shrinks to a row apiece).
205        self.layout.set_role(
206            wrapper,
207            super::terminal_layout::Role {
208                sized: true,
209                ..Default::default()
210            },
211        );
212        if let Some(root) = self.nodes[key as usize].root.as_mut() {
213            root.overlay = Some(Box::new(OverlayState {
214                config: OverlayConfig::default(),
215                wrapper,
216                host: None,
217                placed: None,
218                native_anchor: None,
219                tab_after: None,
220                margin_set: false,
221                hinted: false,
222                waiting: None,
223                focus_on: false,
224                focus_shown: false,
225                pointer: None,
226                covered: None,
227                told: None,
228                natural: None,
229                held: None,
230            }));
231        }
232        self.overlays.push(key);
233    }
234
235    /// The views whose `position: fixed` changed become overlays (laid out
236    /// in their root view's box, shown above its children, as CSS places
237    /// a fixed box against the viewport), or views in their parents again.
238    pub(super) fn sync_fixed(&mut self) {
239        if self.fixed_changed.is_empty() {
240            return;
241        }
242        for (key, id) in std::mem::take(&mut self.fixed_changed) {
243            let Some(node) = self.nodes.get(key as usize) else {
244                continue;
245            };
246            if node.id != id {
247                continue;
248            }
249            let parent = node.parent;
250            let at = (parent != NO_KEY).then(|| {
251                let siblings = &self.nodes[parent as usize].children;
252                let i = siblings.iter().position(|&c| c == key).expect("child");
253                let next = siblings.get(i + 1).map(|&c| self.nodes[c as usize].id);
254                (self.nodes[parent as usize].id, next)
255            });
256            if self.fix_or_unfix(key)
257                && let Some((parent, before)) = at
258            {
259                let _ = self.insert(parent, id, before);
260            }
261        }
262    }
263
264    /// Makes view `key` an overlay when its style says `position: fixed`,
265    /// or a view again when it no longer does; whether it changed.
266    pub(super) fn fix_or_unfix(&mut self, key: Key) -> bool {
267        let node = &self.nodes[key as usize];
268        let fixed = node.wants_fixed
269            && !node.kind.is_root()
270            && (node.layout.is_some() || node.kind == Kind::Text);
271        if fixed == node.fixed_view {
272            return false;
273        }
274        if fixed {
275            self.fix_view(key);
276        } else {
277            self.unfix_view(key);
278        }
279        true
280    }
281
282    /// View `key` becomes an overlay of no anchor: out of its parent's
283    /// layout and native view, shown by `sync_overlays` in its root view.
284    fn fix_view(&mut self, key: Key) {
285        if self.nodes[key as usize].parent != NO_KEY {
286            self.unlink(key, true);
287        }
288        self.set_inline(key, false);
289        let node = &mut self.nodes[key as usize];
290        node.fixed_view = true;
291        node.root = Some(Box::default());
292        let layout = node.layout.expect("a view has a layout");
293        let style = self.layout.style(layout).clone();
294        self.nodes[key as usize].base_layout = Some(Box::new(style));
295        self.roots.push(key);
296        self.overlay_made(key, layout);
297        self.sync_layout_style(key);
298        self.uncull_subtree(key);
299    }
300
301    /// Overlay `key`, a view `position: fixed` made one, is a view again:
302    /// out of its root view, laid out in its parent.
303    fn unfix_view(&mut self, key: Key) {
304        self.set_native_overlay_anchor(key, None);
305        let (id, created) = (
306            self.nodes[key as usize].id,
307            self.nodes[key as usize].created,
308        );
309        let state = self.overlay(key).map(|s| (s.host, s.wrapper));
310        if let Some((Some(_), _)) = state
311            && created
312        {
313            self.mount.push(MountItem::Remove { id });
314        }
315        if self.nodes[key as usize].parent != NO_KEY {
316            self.unlink(key, false);
317        }
318        let layout = self.nodes[key as usize]
319            .layout
320            .expect("a view has a layout");
321        if let Some((_, wrapper)) = state {
322            self.layout.remove_child(wrapper, layout);
323            self.overlay_released(key, wrapper);
324        }
325        self.roots.retain(|&k| k != key);
326        let node = &mut self.nodes[key as usize];
327        node.fixed_view = false;
328        node.root = None;
329        if let Some(base) = node.base_layout.as_deref() {
330            self.layout.set_style(layout, base.clone());
331        }
332        if !node.kind.derives_layout() {
333            node.base_layout = None;
334        }
335        self.needs_layout = true;
336    }
337
338    /// Overlay `key` is released: forgets it and drops its wrapper (its own
339    /// layout node is gone already).
340    pub(super) fn overlay_released(&mut self, key: Key, wrapper: LayoutId) {
341        self.overlays.retain(|&k| k != key);
342        self.layout.remove(wrapper);
343    }
344
345    /// Node `id` is released: the nodes made for its `tooltip` go with it.
346    pub(super) fn tooltip_released(&mut self, id: NodeId) {
347        if let Some(made) = self.overlay_state.tooltips.remove(&id) {
348            self.release_tooltip(made);
349        }
350    }
351
352    /// Whether `key` is the overlay of an element's `tooltip`, or another
353    /// hint overlay inside an element (a Rust `tooltip`, a link's URL hint
354    /// of `nsh-base`): not one of its children for its classes (`first:`,
355    /// `last:`, ...).
356    pub(super) fn is_tooltip_overlay(&self, key: Key) -> bool {
357        let node = &self.nodes[key as usize];
358        node.is_overlay()
359            && node.parent != NO_KEY
360            && (self.overlay(key).is_some_and(|s| s.config.hint.is_some())
361                || self
362                    .overlay_state
363                    .tooltips
364                    .get(&self.nodes[node.parent as usize].id)
365                    .is_some_and(|t| t.overlay == node.id))
366    }
367
368    pub(super) fn overlay(&self, key: Key) -> Option<&OverlayState> {
369        self.nodes[key as usize]
370            .root
371            .as_ref()
372            .and_then(|r| r.overlay.as_deref())
373    }
374
375    pub(super) fn overlay_mut(&mut self, key: Key) -> Option<&mut OverlayState> {
376        self.nodes[key as usize]
377            .root
378            .as_mut()
379            .and_then(|r| r.overlay.as_deref_mut())
380    }
381
382    /// Changes how overlay `key` is placed.
383    pub(super) fn set_overlay_config(&mut self, key: Key, f: impl FnOnce(&mut OverlayConfig)) {
384        if let Some(state) = self.overlay_mut(key) {
385            let before = state.config;
386            f(&mut state.config);
387            if state.config != before {
388                state.placed = None;
389                // Placed again with its size, or laid out again (no anchor:
390                // its insets place it).
391                if let Some(root) = self.nodes[key as usize].root.as_mut() {
392                    root.laid_out = None;
393                }
394                self.needs_layout = true;
395            }
396        }
397    }
398
399    /// The first overlay shown in root view `parent`: the native sibling
400    /// its own children go below.
401    pub(super) fn first_overlay_in(&self, parent: Key) -> Option<NodeId> {
402        // Only the root view and a modal show overlays (`overlay_host`):
403        // the views made in any other are not looked up among all the
404        // overlays, which are as many as a document's links (their hints).
405        if parent != self.root && self.nodes[parent as usize].kind != Kind::Modal {
406            return None;
407        }
408        let id = self.nodes[parent as usize].id;
409        self.overlays.iter().find_map(|&k| {
410            self.placing(1);
411            (self.overlay(k)?.host == Some(id)).then(|| self.nodes[k as usize].id)
412        })
413    }
414
415    /// The root view overlay `key` is shown in, or `None` while it is not
416    /// shown: a view around it is not (out of the tree, its native view
417    /// not made, `display: none`), or the overlay around it is not.
418    fn overlay_host(&self, key: Key) -> Option<Key> {
419        let mut modal = None;
420        let mut k = self.nodes[key as usize].parent;
421        while k != NO_KEY {
422            if k == self.root {
423                return Some(modal.unwrap_or(self.root));
424            }
425            let n = &self.nodes[k as usize];
426            if let Some(layout) = n.layout {
427                if !n.created {
428                    return None;
429                }
430                let hidden = self.layout.displays_none(layout);
431                if hidden && !n.is_overlay() {
432                    return None;
433                }
434            }
435            match n.kind {
436                Kind::Modal if modal.is_none() => modal = Some(k),
437                _ if n.is_overlay() => {
438                    // Shown in its root view, which is this one's unless a
439                    // modal is between them.
440                    let host = self.overlay(k)?.host?;
441                    return Some(modal.unwrap_or(self.key(host).ok()?));
442                }
443                _ => {}
444            }
445            k = n.parent;
446        }
447        None
448    }
449
450    /// The overlays around `key`.
451    fn overlay_depth(&self, key: Key) -> u32 {
452        let mut depth = 0;
453        let mut k = self.nodes[key as usize].parent;
454        while k != NO_KEY {
455            if self.nodes[k as usize].is_overlay() {
456                depth += 1;
457            }
458            k = self.nodes[k as usize].parent;
459        }
460        depth
461    }
462
463    /// Shows the overlays whose views around them are shown, in their root
464    /// views, and hides the others (and the hints the pointer has not
465    /// asked for); then what they listen to (once per commit, before the
466    /// dirty views are flushed).
467    pub(super) fn sync_overlays(&mut self) {
468        if self.overlays.is_empty()
469            && self.overlay_state.watched.is_empty()
470            && self.overlay_state.hinting.is_empty()
471        {
472            return;
473        }
474        // The overlays around one first: theirs say where it goes.
475        if !self.overlay_state.tooltips.is_empty() {
476            self.adopt_hint_tooltips();
477        }
478        let mut order: Vec<(u32, Key)> = self
479            .overlays
480            .iter()
481            .map(|&k| (self.overlay_depth(k), k))
482            .collect();
483        order.sort_by_key(|&(depth, _)| depth);
484        let mut opened = Vec::new();
485        // The hints in the view, whose anchors listen to the pointer.
486        let mut hints = Vec::new();
487        for (_, key) in order {
488            let mut target = self.overlay_host(key);
489            let Some(state) = self.overlay(key) else {
490                continue;
491            };
492            if state.config.hint.is_some() {
493                if target.is_some() {
494                    hints.push(key);
495                } else {
496                    // Out of the view: the pointer starts again.
497                    self.unhint(key);
498                }
499                let state = self.overlay(key).expect("overlay");
500                if !state.config.open.unwrap_or(state.hint_shown()) {
501                    target = None;
502                }
503            }
504            let target_id = target.map(|h| self.nodes[h as usize].id);
505            let current = self.overlay(key).expect("overlay").host;
506            if current == target_id {
507                continue;
508            }
509            let id = self.nodes[key as usize].id;
510            if let Some(old) = current
511                && self.key(old).is_ok_and(|h| self.nodes[h as usize].created)
512                && self.nodes[key as usize].created
513            {
514                self.mount.push(MountItem::Remove { id });
515            }
516            let state = self.overlay_mut(key).expect("overlay");
517            state.host = target_id;
518            state.placed = None;
519            let Some(host) = target_id else {
520                continue;
521            };
522            self.ensure_created(key);
523            self.mount.push(MountItem::Insert {
524                parent: host,
525                child: id,
526                before: None,
527            });
528            // Its native parent is this host; its logical ancestry may
529            // need the override.
530            self.key_ancestry_dirty = true;
531            if let Some(root) = self.nodes[key as usize].root.as_mut() {
532                root.laid_out = None;
533            }
534            self.needs_layout = true;
535            self.tab_places_stale = true;
536            opened.push(key);
537        }
538        // Opened last, on top: in the order they were shown.
539        if !opened.is_empty() {
540            self.overlays.retain(|k| !opened.contains(k));
541            self.overlays.extend(opened);
542        }
543        self.sync_overlay_listeners(&hints);
544    }
545
546    /// Finds again which shown overlays need a keyboard ancestry override
547    /// ([`crate::ViewProps::key_parent`]): their native parent is their
548    /// root view, while a listener or capture rule on their logical
549    /// ancestry must still hear keys. Runs when a key rule or an overlay
550    /// changed, not per key; an ordinary app's overlays keep `None`.
551    pub(super) fn sync_key_parents(&mut self) {
552        for index in 0..self.overlays.len() {
553            let key = self.overlays[index];
554            let logical = self.nodes[key as usize].parent;
555            let desired = (logical != NO_KEY)
556                .then(|| self.nodes[logical as usize].id)
557                .filter(|parent| self.logical_key_interest(*parent));
558            if self.nodes[key as usize].key_parent == desired {
559                continue;
560            }
561            self.nodes[key as usize].key_parent = desired;
562            self.mark(key, super::dirty::VIEW_PROPS);
563        }
564    }
565
566    /// Publishes an unfocused key target only when its path has a listener or
567    /// capture rule. With neither, the backend can use the window root.
568    pub(super) fn sync_key_contents(&mut self) {
569        let changes: Vec<_> = std::iter::once(self.root)
570            .chain(
571                self.window_ids
572                    .values()
573                    .filter_map(|&(id, _)| self.key(id).ok()),
574            )
575            .filter_map(|key| {
576                let start = self.key_start(key);
577                let desired = (start != key)
578                    .then(|| self.nodes[start as usize].id)
579                    .filter(|&id| self.logical_key_interest(id));
580                let mounted = self.nodes[key as usize]
581                    .props
582                    .as_ref()
583                    .and_then(|props| props.key_content);
584                (mounted != desired).then_some((key, desired))
585            })
586            .collect();
587        for (key, desired) in changes {
588            self.nodes[key as usize]
589                .props
590                .get_or_insert_default()
591                .key_content = desired;
592            self.mark(key, super::dirty::VIEW_PROPS);
593        }
594    }
595
596    /// Whether `id` or an ancestor in the logical tree has a key listener
597    /// or a capture rule. Disabled views still count: a native adapter skips
598    /// them itself, and a stale override changes no behavior.
599    fn logical_key_interest(&self, id: NodeId) -> bool {
600        let Ok(mut key) = self.key(id) else {
601            return false;
602        };
603        let window = self.key_window(key);
604        loop {
605            let node = &self.nodes[key as usize];
606            if node.mounted_events().contains(EventKind::KeyDown)
607                || node.mounted_events().contains(EventKind::KeyUp)
608                || node
609                    .props
610                    .as_ref()
611                    .is_some_and(|p| !p.key_capture.is_none())
612            {
613                return true;
614            }
615            if node.id == window || node.parent == NO_KEY {
616                return false;
617            }
618            key = node.parent;
619        }
620    }
621
622    /// The touches and keys the shown overlays need, and the pointer the
623    /// anchors of `hints` (in the view) follow.
624    fn sync_overlay_listeners(&mut self, hints: &[Key]) {
625        let mut watched: Vec<(Key, NodeId)> = Vec::new();
626        let mut cancel = false;
627        let mut hint_escape = false;
628        let watching = self.overlays.iter().any(|&k| {
629            self.overlay(k).is_some_and(|s| s.host.is_some())
630                && self.nodes[k as usize]
631                    .events
632                    .contains(EventKind::PressOutside)
633        });
634        for &key in &self.overlays {
635            let Some(state) = self.overlay(key) else {
636                continue;
637            };
638            let Some(host) = state.host else { continue };
639            let node = &self.nodes[key as usize];
640            cancel |= node.events.contains(EventKind::Cancel);
641            hint_escape |= state.config.hint.is_some();
642            if !watching {
643                continue;
644            }
645            // Every shown overlay, so a press in one inside a watching one
646            // tells where it is.
647            watched.push((key, node.id));
648            if node.events.contains(EventKind::PressOutside) {
649                for id in [Some(host), anchor_node(state)].into_iter().flatten() {
650                    if let Ok(k) = self.key(id) {
651                        watched.push((k, self.nodes[k as usize].id));
652                    }
653                }
654            }
655        }
656        watched.sort_unstable();
657        watched.dedup();
658        let old = std::mem::take(&mut self.overlay_state.watched);
659        self.rewatch(&old, &watched, watch::PRESS);
660        self.overlay_state.watched = watched;
661        // Hints only follow a pointer (the desktops).
662        let mut hinting: Vec<(Key, NodeId)> = Vec::new();
663        if self
664            .components
665            .environment
666            .idiom
667            .desktop_on(self.components.environment.os)
668        {
669            for &key in hints {
670                if let Some(k) = self.hint_anchor(key) {
671                    hinting.push((k, self.nodes[k as usize].id));
672                    // A link of a text: its block listens to touches, so a
673                    // press on the link hides the hint. A span is not
674                    // watched yet the first time (`is_text_span`, not
675                    // `is_link_span`): watching it is what makes it one.
676                    if self.is_text_span(k)
677                        && let Some(block) = self.framed(k)
678                    {
679                        hinting.push((block, self.nodes[block as usize].id));
680                    }
681                }
682            }
683            hinting.sort_unstable();
684            hinting.dedup();
685        }
686        let old = std::mem::take(&mut self.overlay_state.hinting);
687        self.rewatch(&old, &hinting, watch::HINT);
688        self.overlay_state.hinting = hinting;
689        if cancel != self.overlay_state.cancel {
690            self.overlay_state.cancel = cancel;
691            // The root's table and back listener are made again.
692            self.components.executor.keys.borrow_mut().changed = true;
693            self.components.executor.back.borrow_mut().changed = true;
694        }
695        if hint_escape != self.overlay_state.hint_escape {
696            self.overlay_state.hint_escape = hint_escape;
697            self.components.executor.keys.borrow_mut().changed = true;
698        }
699    }
700
701    /// The nodes of `old` not in `new` stop listening for `bit`, those of
702    /// `new` not in `old` start. A link of a text listens through its text
703    /// block's links ([`crate::text::TextLink::events`]): the block is
704    /// merged again.
705    ///
706    /// Both lists are sorted and hold each node once
707    /// ([`Self::sync_overlay_listeners`]). This runs every commit, and on a
708    /// desktop the hints' list holds an anchor for each link of a document
709    /// in the view: the lists are walked side by side, not each searched
710    /// for the other's nodes.
711    fn rewatch(&mut self, old: &[(Key, NodeId)], new: &[(Key, NodeId)], bit: u8) {
712        debug_assert!(old.is_sorted() && new.is_sorted());
713        if old == new {
714            self.watching(old.len());
715            return;
716        }
717        let (mut i, mut j) = (0, 0);
718        loop {
719            self.watching(1);
720            let (start, (k, id)) = match (old.get(i), new.get(j)) {
721                (Some(&a), Some(&b)) if a == b => {
722                    i += 1;
723                    j += 1;
724                    continue;
725                }
726                (Some(&a), Some(&b)) if b < a => {
727                    j += 1;
728                    (true, b)
729                }
730                (Some(&a), _) => {
731                    i += 1;
732                    (false, a)
733                }
734                (None, Some(&b)) => {
735                    j += 1;
736                    (true, b)
737                }
738                (None, None) => break,
739            };
740            if start {
741                self.nodes[k as usize].overlay_watched |= bit;
742            } else if self.nodes.get(k as usize).is_some_and(|n| n.id == id) {
743                self.nodes[k as usize].overlay_watched &= !bit;
744            } else {
745                // Released since: its key may be another node's now.
746                continue;
747            }
748            self.mark(k, super::dirty::EVENTS);
749            if self.nodes[k as usize].inline {
750                self.mark_text_block(k);
751            }
752        }
753    }
754
755    /// `n` more watched nodes looked at to tell what starts and stops
756    /// listening ([`super::components::Components::watch_work`]).
757    #[cfg(test)]
758    fn watching(&self, n: usize) {
759        let work = &self.components.watch_work;
760        work.set(work.get() + n);
761    }
762
763    #[cfg(not(test))]
764    #[inline(always)]
765    fn watching(&self, _n: usize) {}
766
767    /// What hint overlay `key` is placed against and whose pointer it
768    /// follows: its anchor, else its parent when that is a span of a text
769    /// (a link, pressable or not: once its hint watches it, the platforms
770    /// report the pointer coming over its characters and leaving them),
771    /// else the nearest view around it with a frame.
772    fn hint_anchor(&self, key: Key) -> Option<Key> {
773        match self.overlay(key)?.config.anchor {
774            OverlayAnchor::Node(id)
775            | OverlayAnchor::Content(id)
776            | OverlayAnchor::Beside { node: id, .. } => self.key(id).ok(),
777            OverlayAnchor::Point(_) | OverlayAnchor::Bounds(_) => None,
778            OverlayAnchor::None => {
779                let parent = self.nodes[key as usize].parent;
780                // Any span, watched or not yet: the watch that makes it a
781                // link of its text ([`Self::is_link_span`]) comes from
782                // this answer.
783                if parent != NO_KEY && self.is_text_span(parent) {
784                    return Some(parent);
785                }
786                self.framed(parent)
787            }
788        }
789    }
790
791    /// Whether `key` is a nested span of a text, with no frame of its own.
792    pub(super) fn is_text_span(&self, key: Key) -> bool {
793        let n = &self.nodes[key as usize];
794        n.kind == Kind::Text && n.inline && n.layout.is_none()
795    }
796
797    /// Whether `key` is a link of a text (`AttributedText::links`): a
798    /// nested span taking presses, or one a hint watches (a `RichEditor`'s
799    /// link mark, whose presses are the editor's: it only hears the
800    /// pointer come and go).
801    fn is_link_span(&self, key: Key) -> bool {
802        let n = &self.nodes[key as usize];
803        self.is_text_span(key)
804            && (super::pressable(n.events) || n.overlay_watched & watch::HINT != 0)
805    }
806
807    /// `key` itself, or the nearest view around it, with a frame (a link
808    /// span's text block).
809    fn framed(&self, mut k: Key) -> Option<Key> {
810        while k != NO_KEY {
811            let n = &self.nodes[k as usize];
812            if n.layout.is_some() {
813                return Some(k);
814            }
815            k = n.parent;
816        }
817        None
818    }
819
820    /// What overlay `key` is placed against: a hint without an anchor
821    /// against the view it follows ([`Self::hint_anchor`]); one on a link
822    /// of a text where the pointer came over the link (its text block
823    /// for the keyboard focus, which comes with no pointer).
824    fn resolved_anchor(&self, key: Key) -> OverlayAnchor {
825        let Some(state) = self.overlay(key) else {
826            return OverlayAnchor::None;
827        };
828        match state.config.anchor {
829            OverlayAnchor::None if state.config.hint.is_some() => {
830                let Some(k) = self.hint_anchor(key) else {
831                    return OverlayAnchor::None;
832                };
833                if self.is_text_span(k) {
834                    if let Some(at) = state.pointer.filter(|_| !state.focus_shown) {
835                        return OverlayAnchor::Point(at);
836                    }
837                    return self.framed(k).map_or(OverlayAnchor::None, |f| {
838                        OverlayAnchor::Node(self.nodes[f as usize].id)
839                    });
840                }
841                OverlayAnchor::Node(self.nodes[k as usize].id)
842            }
843            anchor => anchor,
844        }
845    }
846
847    /// The pointer came over node `id` or left it (`kind`), at `at` in its
848    /// root view: the hints it anchors wait for it to rest, or hide.
849    pub(super) fn overlay_hover(&mut self, id: NodeId, kind: EventKind, at: Option<Point<Points>>) {
850        let Ok(anchor) = self.key(id) else {
851            return;
852        };
853        if self.nodes[anchor as usize].overlay_watched & watch::HINT == 0 {
854            return;
855        }
856        let hints: Vec<Key> = self
857            .overlays
858            .iter()
859            .copied()
860            .filter(|&k| {
861                self.overlay(k).is_some_and(|s| s.config.hint.is_some())
862                    && self.hint_anchor(k) == Some(anchor)
863            })
864            .collect();
865        let span = self.is_link_span(anchor);
866        for key in hints {
867            match kind {
868                EventKind::MouseEnter => {
869                    if span && let Some(state) = self.overlay_mut(key) {
870                        // Where it goes, unless it shows already.
871                        if !state.hint_shown() {
872                            state.pointer = at;
873                        }
874                    }
875                    self.hint_wait(key)
876                }
877                _ => {
878                    // Moving on from a hint it showed: the next anchor the
879                    // pointer comes to within its grace period shows its
880                    // hint at once.
881                    if self
882                        .overlay(key)
883                        .is_some_and(|s| s.hinted && s.host.is_some())
884                    {
885                        self.overlay_state.grace_from = Some(crate::time::now());
886                    }
887                    self.unhint(key)
888                }
889            }
890        }
891    }
892
893    /// The pointer is on hint `key`'s anchor: it shows once the pointer
894    /// rested there for its delay ([`Self::hint_due`]), or at once within
895    /// its grace period ([`Self::hint_skips_delay`]).
896    fn hint_wait(&mut self, key: Key) {
897        let executor = self.components.executor.clone();
898        let id = self.nodes[key as usize].id;
899        let skips = self.hint_skips_delay(key);
900        let Some(state) = self.overlay_mut(key) else {
901            return;
902        };
903        if state.hinted || state.waiting.is_some() {
904            return;
905        }
906        if skips {
907            self.hint_for_pointer(key);
908            return;
909        }
910        let delay = state.config.hint.unwrap_or(HINT_DELAY);
911        state.waiting = Some(HintTimer(act_after(&executor, id, delay, Action::Hint(id))));
912    }
913
914    /// Whether hint `key` shows at once as the pointer comes to its anchor,
915    /// without waiting its delay: the pointer left an anchor whose hint it
916    /// showed less than the grace period ago ([`HINT_GRACE_PERIOD`]), or a hint it showed is still
917    /// in the view (an anchor inside another). Hints the focus or the app
918    /// showed count for nothing: the pointer has not paid its rest. A hint
919    /// whose delay never ends ([`HINT_ENDLESS`]) waits it still.
920    fn hint_skips_delay(&self, key: Key) -> bool {
921        let Some(state) = self.overlay(key) else {
922            return false;
923        };
924        if state.config.hint.is_some_and(|d| d >= HINT_ENDLESS) {
925            return false;
926        }
927        let grace = HINT_GRACE_PERIOD;
928        let recent = self
929            .overlay_state
930            .grace_from
931            .is_some_and(|from| crate::time::now().saturating_duration_since(from) < grace);
932        recent
933            || self.overlays.iter().any(|&k| {
934                k != key
935                    && self
936                        .overlay(k)
937                        .is_some_and(|s| s.config.hint.is_some() && s.hinted && s.host.is_some())
938            })
939    }
940
941    /// Hint overlay `id`'s delay is over with the pointer on its anchor: it
942    /// shows (in the commit).
943    pub(super) fn hint_due(&mut self, id: NodeId) {
944        let Ok(key) = self.key(id) else {
945            return;
946        };
947        let Some(state) = self.overlay_mut(key) else {
948            return;
949        };
950        if state.waiting.take().is_none() || state.config.hint.is_none() {
951            return;
952        }
953        self.hint_for_pointer(key);
954    }
955
956    /// The pointer shows hint `key` (in the commit): it asks to show unless
957    /// the focus showed it already.
958    fn hint_for_pointer(&mut self, key: Key) {
959        let Some(state) = self.overlay_mut(key) else {
960            return;
961        };
962        let was = state.hint_shown();
963        state.hinted = true;
964        if !was {
965            self.hint_changed(key, true, HintReason::Pointer);
966        }
967    }
968
969    /// Hint `key` stops waiting, and hides when the pointer had it shown
970    /// (and the focus does not keep it).
971    fn unhint(&mut self, key: Key) {
972        self.hide_hint(key, false, HintReason::Pointer);
973    }
974
975    /// Scroll view or list `scroll` moved its content: a hint on a link of
976    /// a text in it, placed where the pointer came over the link (a point
977    /// of the root view, which does not move with the link), would show
978    /// where the link was. It hides, as when the pointer leaves the link;
979    /// the pointer coming over a link again shows that link's where it is.
980    /// A hint the keyboard focus shows stays, placed against the link's
981    /// text block, which the scroll moves.
982    pub(super) fn overlay_scrolled(&mut self, scroll: Key) {
983        let hints: Vec<Key> = self
984            .overlays
985            .iter()
986            .copied()
987            .filter(|&k| {
988                self.overlay(k).is_some_and(|s| {
989                    s.config.hint.is_some()
990                        && matches!(s.config.anchor, OverlayAnchor::None)
991                        && s.pointer.is_some()
992                        && (s.hinted || s.waiting.is_some())
993                }) && self
994                    .hint_anchor(k)
995                    .is_some_and(|a| self.is_text_span(a) && self.is_within(a, scroll))
996            })
997            .collect();
998        for key in hints {
999            if let Some(state) = self.overlay_mut(key) {
1000                state.pointer = None;
1001            }
1002            self.unhint(key);
1003        }
1004    }
1005
1006    /// Whether `key` is `outer` or inside it.
1007    pub(super) fn is_within(&self, mut key: Key, outer: Key) -> bool {
1008        while key != NO_KEY {
1009            if key == outer {
1010                return true;
1011            }
1012            key = self.nodes[key as usize].parent;
1013        }
1014        false
1015    }
1016
1017    /// Hint `key` stops waiting and the pointer's showing ends, the
1018    /// focus's too when `focus`: it asks to hide when it was shown.
1019    fn hide_hint(&mut self, key: Key, focus: bool, reason: HintReason) {
1020        let Some(state) = self.overlay_mut(key) else {
1021            return;
1022        };
1023        state.waiting = None;
1024        let was = state.hint_shown();
1025        state.hinted = false;
1026        if focus {
1027            state.focus_shown = false;
1028        }
1029        if was && !state.hint_shown() {
1030            self.hint_changed(key, false, reason);
1031        }
1032    }
1033
1034    /// The focus moved: the hints whose anchor it came to show when the
1035    /// keyboard brought it there (`Core::focus_by_keyboard`), those it left
1036    /// hide; a move inside an anchor decides nothing again. The focus
1037    /// counts for the nearest hint's anchor on its chain, up to the overlay
1038    /// it is in (a popup's focus is not on its trigger's hint).
1039    pub(super) fn focus_hints(&mut self) {
1040        let mut target = None;
1041        for &(k, _) in &self.focus_chain {
1042            if self.overlays.iter().any(|&h| {
1043                self.overlay(h).is_some_and(|s| s.config.hint.is_some())
1044                    && self.hint_anchor(h) == Some(k)
1045            }) {
1046                target = Some(k);
1047                break;
1048            }
1049            if self.nodes[k as usize].is_overlay() {
1050                break;
1051            }
1052        }
1053        let hints: Vec<Key> = self
1054            .overlays
1055            .iter()
1056            .copied()
1057            .filter(|&k| self.overlay(k).is_some_and(|s| s.config.hint.is_some()))
1058            .collect();
1059        let keyboard = self.focus_by_keyboard;
1060        for key in hints {
1061            let on = target.is_some() && self.hint_anchor(key) == target;
1062            let Some(state) = self.overlay_mut(key) else {
1063                continue;
1064            };
1065            if on == state.focus_on {
1066                continue;
1067            }
1068            state.focus_on = on;
1069            let was = state.hint_shown();
1070            // A press that brings the focus hid the pointer's hint: showing
1071            // it for that focus would keep it up long after the pointer
1072            // left (a toolbar's tooltip after every click). Only the
1073            // keyboard's focus shows it, as `focus-visible:` shows a ring.
1074            state.focus_shown = on && keyboard;
1075            let now = state.hint_shown();
1076            if was != now {
1077                self.hint_changed(key, now, HintReason::Focus);
1078            }
1079        }
1080    }
1081
1082    /// Tells hint `key` what the pointer or the focus asks for: `Show` or
1083    /// `Dismiss`, with why.
1084    fn hint_changed(&mut self, key: Key, shown: bool, reason: HintReason) {
1085        let node = &self.nodes[key as usize];
1086        let kind = if shown {
1087            EventKind::Show
1088        } else {
1089            EventKind::Dismiss
1090        };
1091        if node.events.contains(kind) {
1092            self.events.push(crate::element::JsEvent::Event(
1093                node.id,
1094                kind,
1095                EventPayload::Map(vec![(
1096                    "reason",
1097                    PayloadValue::Str(reason.as_str().to_owned()),
1098                )]),
1099            ));
1100        }
1101    }
1102
1103    /// A finger or button went down: the hints whose anchors it is on hide
1104    /// (and wait for the pointer to come again).
1105    fn hint_touches(&mut self, touch: &TouchEvent) {
1106        let hints: Vec<Key> = self
1107            .overlays
1108            .iter()
1109            .copied()
1110            .filter(|&k| {
1111                self.overlay(k).is_some_and(|s| {
1112                    s.config.hint.is_some() && (s.hint_shown() || s.waiting.is_some())
1113                })
1114            })
1115            .collect();
1116        for key in hints {
1117            // A link's text block for a link of a text: a touch's path
1118            // holds views.
1119            let Some(anchor) = self
1120                .hint_anchor(key)
1121                .and_then(|k| self.framed(k))
1122                .map(|k| self.nodes[k as usize].id)
1123            else {
1124                continue;
1125            };
1126            let pressed = touch
1127                .points
1128                .iter()
1129                .any(|p| p.changed && p.path.contains(&anchor));
1130            if pressed {
1131                // Acting on the anchor, not reading hints: the next anchor
1132                // waits its delay, as `gpui-component`'s press hides its
1133                // tooltip with no grace period.
1134                self.overlay_state.grace_from = None;
1135                self.hide_hint(key, true, HintReason::Pointer);
1136            }
1137        }
1138    }
1139
1140    /// Sets the `tooltip` of node `key`: a hint overlay the core makes
1141    /// inside it, showing the element JS made.
1142    pub(super) fn set_tooltip(&mut self, key: Key, content: TooltipContent) {
1143        let id = self.nodes[key as usize].id;
1144        let mut made = self.overlay_state.tooltips.get(&id).copied();
1145        // The element was the hint overlay itself: anything else starts
1146        // again from a hint overlay of the core's.
1147        if let Some(adopted) = made.filter(|m| m.content == Some(m.overlay)) {
1148            if content == TooltipContent::Node(adopted.overlay) {
1149                return;
1150            }
1151            self.overlay_state.tooltips.remove(&id);
1152            self.release_tooltip(adopted);
1153            made = None;
1154        }
1155        let made = match (content, made) {
1156            (TooltipContent::None, made) => {
1157                if let Some(made) = made {
1158                    self.overlay_state.tooltips.remove(&id);
1159                    self.release_tooltip(made);
1160                }
1161                return;
1162            }
1163            (TooltipContent::Node(node), made) => {
1164                let mut made = match made {
1165                    Some(made) => made,
1166                    None => match self.make_tooltip(id) {
1167                        Some(made) => made,
1168                        None => return,
1169                    },
1170                };
1171                if made.content == Some(node) {
1172                    return;
1173                }
1174                if let Some(old) = made.content.take() {
1175                    self.detach_tooltip_content(old);
1176                }
1177                match self.insert(made.overlay, node, None) {
1178                    Ok(()) => made.content = Some(node),
1179                    Err(e) => log::error!(target: "js", "a tooltip's element is not shown: {e:?}"),
1180                }
1181                made
1182            }
1183        };
1184        self.overlay_state.tooltips.insert(id, made);
1185    }
1186
1187    /// A hint overlay inside element `id`, above it, for its `tooltip`.
1188    fn make_tooltip(&mut self, id: NodeId) -> Option<CoreTooltip> {
1189        let overlay = self.components.alloc();
1190        let gap = px(TOOLTIP_GAP);
1191        let ops = [
1192            Op::Create {
1193                id: overlay,
1194                tag: Tag::Overlay,
1195            },
1196            // Never in the way of the pointer: the element works as without.
1197            Op::SetProp {
1198                id: overlay,
1199                prop: Prop::PointerEvents(PointerEvents::None),
1200            },
1201            Op::SetProp {
1202                id: overlay,
1203                prop: Prop::Overlay(OverlayProp::Hint(Some(HINT_DELAY))),
1204            },
1205            Op::SetProp {
1206                id: overlay,
1207                prop: Prop::Overlay(OverlayProp::Placement(Placement::Top)),
1208            },
1209            Op::SetProp {
1210                id: overlay,
1211                prop: Prop::Overlay(OverlayProp::Offset(gap)),
1212            },
1213            Op::SetProp {
1214                id: overlay,
1215                prop: Prop::Overlay(OverlayProp::Margin(gap)),
1216            },
1217        ];
1218        for op in ops {
1219            if let Err(e) = self.apply_op(op) {
1220                log::error!(target: "js", "a tooltip is not made: {e:?}");
1221                return None;
1222            }
1223        }
1224        // Into the element itself, wherever a component places its
1225        // children.
1226        if let Err(e) = self.insert(id, overlay, None) {
1227            log::error!(target: "js", "a tooltip is not made: {e:?}");
1228            let _ = self.release(overlay);
1229            return None;
1230        }
1231        Some(CoreTooltip {
1232            overlay,
1233            content: None,
1234        })
1235    }
1236
1237    /// The elements of `tooltip`s that are hint overlays themselves (a
1238    /// `Tooltip` of `nsh-base`, whose root its view made one) take the place
1239    /// of the core's: in the element, with their own placement, delay and
1240    /// look (after the components rendered, before the overlays are shown).
1241    fn adopt_hint_tooltips(&mut self) {
1242        let adoptable: Vec<(NodeId, CoreTooltip)> = self
1243            .overlay_state
1244            .tooltips
1245            .iter()
1246            .filter(|(_, m)| {
1247                m.content.is_some_and(|c| {
1248                    c != m.overlay
1249                        && self.key(c).is_ok_and(|k| {
1250                            self.nodes[k as usize].is_overlay()
1251                                && self.overlay(k).is_some_and(|s| s.config.hint.is_some())
1252                        })
1253                })
1254            })
1255            .map(|(&id, &m)| (id, m))
1256            .collect();
1257        for (id, mut made) in adoptable {
1258            let content = made.content.expect("content");
1259            if let Err(e) = self.insert(id, content, None) {
1260                log::error!(target: "js", "a tooltip's element is not shown: {e:?}");
1261                continue;
1262            }
1263            let _ = self.release(made.overlay);
1264            made.overlay = content;
1265            self.overlay_state.tooltips.insert(id, made);
1266        }
1267    }
1268
1269    /// The element shown as a tooltip leaves it (it stays JS's).
1270    fn detach_tooltip_content(&mut self, content: NodeId) {
1271        if let Ok(k) = self.key(content)
1272            && self.nodes[k as usize].parent != NO_KEY
1273        {
1274            self.detach(k);
1275        }
1276    }
1277
1278    /// Releases the nodes made for a `tooltip`.
1279    fn release_tooltip(&mut self, made: CoreTooltip) {
1280        if let Some(content) = made.content {
1281            self.detach_tooltip_content(content);
1282            if content == made.overlay {
1283                // The element's own (a `Tooltip`'s): JS's to release.
1284                return;
1285            }
1286        }
1287        let _ = self.release(made.overlay);
1288    }
1289
1290    /// Escape's binding, while an overlay listens to `onCancel` or a hint
1291    /// is shown.
1292    pub(super) fn overlay_key_binding(&self) -> Option<KeyBinding> {
1293        if !self.overlay_state.cancel && !self.overlay_state.hint_escape {
1294            return None;
1295        }
1296        // The focused content takes Escape itself: no binding above it.
1297        if self.overlay_state.escape_to_focus && !self.overlay_state.hint_escape {
1298            return None;
1299        }
1300        let escape = Keystroke::parse_with("escape", false).ok()?;
1301        Some(KeyBinding::new(ESCAPE_BINDING, escape, When::Always, false))
1302    }
1303
1304    /// Escape: the top shown overlay that is a hint hides (it asks to,
1305    /// [`HintReason::Escape`]), else `onCancel` of the top overlay
1306    /// listening to it.
1307    pub(super) fn overlay_escape(&mut self) {
1308        let top = self.overlays.iter().rev().copied().find(|&k| {
1309            self.overlay(k).is_some_and(|s| {
1310                s.host.is_some()
1311                    && (s.config.hint.is_some()
1312                        || self.nodes[k as usize].events.contains(EventKind::Cancel))
1313            })
1314        });
1315        let Some(key) = top else {
1316            return;
1317        };
1318        if self.overlay(key).is_some_and(|s| s.config.hint.is_none()) {
1319            // Bound for a hint lower down: the focused content of this
1320            // overlay keeps Escape.
1321            if !self.overlay_state.escape_to_focus {
1322                self.overlay_cancel();
1323            }
1324            return;
1325        }
1326        let state = self.overlay_mut(key).expect("overlay");
1327        state.waiting = None;
1328        state.hinted = false;
1329        state.focus_shown = false;
1330        // Dismissed: the next anchor waits its delay.
1331        self.overlay_state.grace_from = None;
1332        // Shown by the app (`open`) or the pointer and focus: it asks to
1333        // hide either way.
1334        self.hint_changed(key, false, HintReason::Escape);
1335    }
1336
1337    /// Whether the keyboard focus is inside the top shown overlay listening
1338    /// to `onCancel` and it, or an enabled ancestor within that overlay,
1339    /// captures Escape (`captureKeys`): the content, like an editor in a
1340    /// popover, handles Escape first, as a focused element does on the
1341    /// Web before the page's own handlers. Back and the screen reader's
1342    /// escape gesture still cancel the overlay.
1343    pub(super) fn focus_takes_escape(&self) -> bool {
1344        if !self.overlay_state.cancel {
1345            return false;
1346        }
1347        let Some((focus, focus_id)) = self.focus else {
1348            return false;
1349        };
1350        if self
1351            .nodes
1352            .get(focus as usize)
1353            .is_none_or(|n| n.id != focus_id)
1354        {
1355            return false;
1356        }
1357        let top = self.overlays.iter().rev().copied().find(|&k| {
1358            self.overlay(k).is_some_and(|s| s.host.is_some())
1359                && self.nodes[k as usize].events.contains(EventKind::Cancel)
1360        });
1361        let Some(top) = top else {
1362            return false;
1363        };
1364        let Ok(escape) = Keystroke::parse_with("escape", false) else {
1365            return false;
1366        };
1367        // A native text input keeps its own keys and captures none.
1368        if self.nodes[focus as usize].kind == Kind::Input {
1369            return false;
1370        }
1371        let mut key = focus;
1372        let mut captured = false;
1373        loop {
1374            if key == top {
1375                return captured;
1376            }
1377            let node = &self.nodes[key as usize];
1378            if !captured
1379                && node.props.as_ref().is_some_and(|p| {
1380                    !p.accessibility.state.disabled && p.key_capture.captures_key(Some(&escape))
1381                })
1382            {
1383                captured = true;
1384            }
1385            if node.parent == NO_KEY {
1386                return false;
1387            }
1388            key = node.parent;
1389        }
1390    }
1391
1392    /// Escape or back: `onCancel` of the top overlay listening to it;
1393    /// whether one took it.
1394    pub(super) fn overlay_cancel(&mut self) -> bool {
1395        let top = self.overlays.iter().rev().copied().find(|&k| {
1396            self.overlay(k).is_some_and(|s| s.host.is_some())
1397                && self.nodes[k as usize].events.contains(EventKind::Cancel)
1398        });
1399        let Some(key) = top else {
1400            return false;
1401        };
1402        let id = self.nodes[key as usize].id;
1403        self.events.push(crate::element::JsEvent::Event(
1404            id,
1405            EventKind::Cancel,
1406            EventPayload::None,
1407        ));
1408        true
1409    }
1410
1411    /// A touch on the surface: `onPressOutside` of the shown overlays
1412    /// watching presses that a finger went down outside of.
1413    pub(super) fn overlay_touches(&mut self, touch: &TouchEvent) {
1414        if touch.phase != TouchPhase::Start {
1415            return;
1416        }
1417        if !self.overlay_state.hinting.is_empty() {
1418            self.hint_touches(touch);
1419        }
1420        if self.overlay_state.watched.is_empty() {
1421            return;
1422        }
1423        for point in touch.points.iter().filter(|p| p.changed) {
1424            self.press_outside(point.page, &point.path);
1425        }
1426    }
1427
1428    /// A context menu asked for on `id`: a secondary click goes down as a
1429    /// press does, so the shown overlays it is outside of hear
1430    /// `onPressOutside` (a menu open elsewhere closes as a new one opens).
1431    /// The platforms send no touch for a secondary click; a menu asked for
1432    /// by the keyboard or an assistive technology is no press, nor is a
1433    /// long press, whose touch went down already.
1434    ///
1435    /// Returns those `onPressOutside` events (each overlay and its payload)
1436    /// for the caller to hand out before `onContextMenu` itself, as a
1437    /// press outside comes before what the press does: a context menu open
1438    /// on the view closes before the view asks for one again, which then
1439    /// opens where the pointer is.
1440    pub fn context_menu_presses_outside(
1441        &mut self,
1442        id: NodeId,
1443        event: &ContextMenuEvent,
1444    ) -> Vec<(NodeId, EventPayload)> {
1445        if event.pointer_type != Some(PointerType::Mouse) || self.overlay_state.watched.is_empty() {
1446            return Vec::new();
1447        }
1448        self.presses_on(id, event.page_position)
1449    }
1450
1451    /// A press at `page` that went to view `id`'s hosted native content
1452    /// (a web view's page takes its presses, and the platform does not
1453    /// pick them through the core): the shown overlays watching presses
1454    /// that `id` is outside of hear `onPressOutside`, as for a press on
1455    /// any other view.
1456    ///
1457    /// Returns those events for the caller to hand out, as
1458    /// [`Core::context_menu_presses_outside`].
1459    pub fn presses_on_native(
1460        &mut self,
1461        id: NodeId,
1462        page: Point<Points>,
1463    ) -> Vec<(NodeId, EventPayload)> {
1464        if self.overlay_state.watched.is_empty() {
1465            return Vec::new();
1466        }
1467        self.presses_on(id, page)
1468    }
1469
1470    /// The `onPressOutside` events of a press at `page` on `id` and its
1471    /// ancestors.
1472    fn presses_on(&mut self, id: NodeId, page: Point<Points>) -> Vec<(NodeId, EventPayload)> {
1473        let Ok(mut key) = self.key(id) else {
1474            return Vec::new();
1475        };
1476        let mut path = Vec::new();
1477        while key != NO_KEY {
1478            path.push(self.nodes[key as usize].id);
1479            key = self.nodes[key as usize].parent;
1480        }
1481        self.presses_outside(page, &path)
1482    }
1483
1484    /// A press beyond the root view, at `page` in its coordinates: on what
1485    /// is around the surface, where the platform draws the root view's
1486    /// anchored overlays too (the web page around the player's container,
1487    /// `overlays: "viewport"`). It misses every view, so each shown
1488    /// overlay watching presses hears `onPressOutside`, as a press in the
1489    /// root view outside it.
1490    ///
1491    /// Returns those events (each overlay and its payload) for the caller
1492    /// to hand out, as [`Core::context_menu_presses_outside`].
1493    pub fn presses_beyond_root(&mut self, page: Point<Points>) -> Vec<(NodeId, EventPayload)> {
1494        if self.overlay_state.watched.is_empty() {
1495            return Vec::new();
1496        }
1497        self.presses_outside(page, &[])
1498    }
1499
1500    /// The `onPressOutside` events of a press at `page` on the views of
1501    /// `path`, taken from the queue for the caller to hand out.
1502    fn presses_outside(
1503        &mut self,
1504        page: Point<Points>,
1505        path: &[NodeId],
1506    ) -> Vec<(NodeId, EventPayload)> {
1507        let from = self.events.len();
1508        self.press_outside(page, path);
1509        self.events
1510            .drain(from..)
1511            .filter_map(|event| match event {
1512                crate::element::JsEvent::Event(id, _, payload) => Some((id, payload)),
1513                _ => None,
1514            })
1515            .collect()
1516    }
1517
1518    /// A press at `page` on the views of `path` (the one pressed first):
1519    /// `onPressOutside` of the shown overlays watching presses that it is
1520    /// outside of, their anchors and the overlays inside them.
1521    fn press_outside(&mut self, page: Point<Points>, path: &[NodeId]) {
1522        for i in 0..self.overlays.len() {
1523            let key = self.overlays[i];
1524            let node = &self.nodes[key as usize];
1525            let Some(state) = self.overlay(key) else {
1526                continue;
1527            };
1528            if state.host.is_none() || !node.events.contains(EventKind::PressOutside) {
1529                continue;
1530            }
1531            let id = node.id;
1532            let anchor = anchor_node(state);
1533            let inside = path.iter().any(|&p| {
1534                p == id
1535                    || Some(p) == anchor
1536                    || self.key(p).is_ok_and(|k| {
1537                        self.nodes[k as usize].is_overlay() && self.is_ancestor(key, k)
1538                    })
1539            });
1540            if inside {
1541                continue;
1542            }
1543            self.events.push(crate::element::JsEvent::Event(
1544                id,
1545                EventKind::PressOutside,
1546                EventPayload::Map(vec![("pagePosition", PayloadValue::Point(page))]),
1547            ));
1548        }
1549    }
1550
1551    /// The size of the root view overlay `key` is shown in.
1552    fn overlay_host_size(&self, host: NodeId) -> Option<(Size<Points>, crate::EdgeInsets)> {
1553        if host == ROOT_ID {
1554            return Some((self.viewport, self.safe_area));
1555        }
1556        let key = self.key(host).ok()?;
1557        let root = self.nodes[key as usize].root.as_ref()?;
1558        // A window whose size is not known yet: as large as its content.
1559        let size = self
1560            .root_view_size(key)
1561            .unwrap_or(self.nodes[key as usize].frame.size);
1562        Some((size, root.insets))
1563    }
1564
1565    /// The room overlay `key` shown in `host` keeps to beside its anchor:
1566    /// the root view's safe area less the overlay's `margin`, or the area
1567    /// the platform shows the root view's overlays in
1568    /// ([`Core::set_overlay_area`]). In the surface's root view it also
1569    /// leaves out what the software keyboard covers of the view's bottom
1570    /// (the environment's keyboard height, which includes the bottom safe
1571    /// area under it), so a popover flips or shrinks above the keyboard
1572    /// rather than go under it, as a panel docked to the bottom is lifted
1573    /// above it. That height is measured over the surface's root view, so
1574    /// a modal's root view keeps to its own insets; the platform's area
1575    /// leaves the keyboard out already.
1576    fn overlay_area(&self, key: Key, host: NodeId) -> Option<Bounds<Points>> {
1577        let state = self.overlay(key)?;
1578        // In a terminal the Cell of the frame around the box keeps it off
1579        // the edge already: the app's margin would add a blank column.
1580        let m = if state.margin_set {
1581            state.config.margin.0
1582        } else if self.layout.grid().is_some() {
1583            0.0
1584        } else {
1585            self.snap_to_window_margin.0
1586        };
1587        // Shown beyond the root view (the web's `overlays: "viewport"`):
1588        // the platform's area, its safe area already left out.
1589        if host == ROOT_ID
1590            && let Some(area) = self.overlay_bounds
1591        {
1592            return Some(inset(area, [m, m, m, m]));
1593        }
1594        let (size, insets) = self.overlay_host_size(host)?;
1595        let bottom = match host {
1596            ROOT_ID => insets
1597                .bottom
1598                .max(self.components.environment.keyboard_height),
1599            _ => insets.bottom,
1600        };
1601        Some(inset(
1602            rect(0.0, 0.0, size.width.0, size.height.0),
1603            [
1604                insets.top.0 + m,
1605                insets.right.0 + m,
1606                bottom.0 + m,
1607                insets.left.0 + m,
1608            ],
1609        ))
1610    }
1611
1612    /// Lays out shown overlay `key` when the box it is laid out in or its
1613    /// content changed, and places it. One with an anchor is laid out in
1614    /// the room it is placed in ([`Self::overlay_area`]), so content wider
1615    /// than that room wraps within it; one without in a box the size of
1616    /// its root view, as a `position: fixed` box.
1617    pub(super) fn layout_overlay(&mut self, key: Key) {
1618        let Some(state) = self.overlay(key) else {
1619            return;
1620        };
1621        let (Some(host), wrapper) = (state.host, state.wrapper) else {
1622            return;
1623        };
1624        let anchored = self.resolved_anchor(key) != OverlayAnchor::None;
1625        let size = match anchored {
1626            false => self.overlay_host_size(host).map(|(size, _)| size),
1627            true => self.overlay_area(key, host).map(|area| area.size),
1628        };
1629        let Some(size) = size else {
1630            return;
1631        };
1632        let root = self.nodes[key as usize].root.as_ref().expect("root state");
1633        let changed = root.laid_out != Some((size, 0.0));
1634        if !changed && !self.layout.dirty(wrapper) {
1635            return;
1636        }
1637        // Also when only its content changed: the box may still be the
1638        // frame's room of the layout before (below).
1639        self.layout.set_style(wrapper, sized(size));
1640        self.nodes[key as usize]
1641            .root
1642            .as_mut()
1643            .expect("root state")
1644            .laid_out = Some((size, 0.0));
1645        // Its content may have changed: measured again when needed.
1646        if let Some(state) = self.overlay_mut(key) {
1647            state.natural = None;
1648        }
1649        self.layout_root(wrapper, definite(size));
1650        // A terminal frames a popup's box one Cell outside it, which is
1651        // placed with the box (`overlay_origin`): a box that fills the
1652        // room would put its frame past the margin. Whether there is such
1653        // a frame is the layout's (it keeps a card's border inside the box
1654        // instead), so it is known only now: such a box is laid out once
1655        // more, within the frame.
1656        if anchored && self.layout.grid().is_some() {
1657            let ring = self.outside_frame(key);
1658            let room = framed_room(size, ring);
1659            let laid = self.nodes[key as usize]
1660                .layout
1661                .map(|l| self.rounded_layout(l).size);
1662            if laid.is_some_and(|l| l.width > room.width.0 + 0.5 || l.height > room.height.0 + 0.5)
1663            {
1664                self.layout.set_style(wrapper, sized(room));
1665                self.layout_root(wrapper, definite(room));
1666            }
1667        }
1668        self.emit_frames(key);
1669    }
1670
1671    /// Where overlay `key` of `frame` (as laid out in its root view) goes:
1672    /// against its anchor when it has one it can find. Reports a new
1673    /// placement to `onPosition`.
1674    pub(super) fn overlay_origin(&mut self, key: Key, frame: Bounds<Points>) -> Point<Points> {
1675        let Some(state) = self.overlay(key) else {
1676            return frame.origin;
1677        };
1678        let (config, Some(host)) = (state.config, state.host) else {
1679            return frame.origin;
1680        };
1681        let resolved_anchor = self.resolved_anchor(key);
1682        let anchor = match resolved_anchor {
1683            OverlayAnchor::None => None,
1684            // In a terminal the pointer is on a Cell, not a point: the
1685            // whole Cell is the anchor, so an overlay below it starts on
1686            // the next row instead of covering the row it points at.
1687            OverlayAnchor::Point(p) => Some(match self.layout.grid() {
1688                Some(grid) => rect(
1689                    (p.x.0 / grid.width).floor() * grid.width,
1690                    (p.y.0 / grid.height).floor() * grid.height,
1691                    grid.width,
1692                    grid.height,
1693                ),
1694                None => Bounds {
1695                    origin: p,
1696                    size: Size::default(),
1697                },
1698            }),
1699            OverlayAnchor::Bounds(bounds) => Some(bounds),
1700            OverlayAnchor::Node(id) => self.measure(id).map(|m| Bounds {
1701                origin: m.page,
1702                size: m.frame.size,
1703            }),
1704            OverlayAnchor::Content(id) => self.content_bounds(self.content_anchor(id)),
1705            OverlayAnchor::Beside { node, edges } => {
1706                match (self.measure(node), self.measure(edges)) {
1707                    (Some(n), Some(e)) => Some(if config.placement.is_horizontal() {
1708                        rect(
1709                            e.page.x.0,
1710                            n.page.y.0,
1711                            e.frame.size.width.0,
1712                            n.frame.size.height.0,
1713                        )
1714                    } else {
1715                        rect(
1716                            n.page.x.0,
1717                            e.page.y.0,
1718                            n.frame.size.width.0,
1719                            e.frame.size.height.0,
1720                        )
1721                    }),
1722                    (Some(n), None) => Some(Bounds {
1723                        origin: n.page,
1724                        size: n.frame.size,
1725                    }),
1726                    _ => None,
1727                }
1728            }
1729        };
1730        let Some(anchor) = anchor else {
1731            // A terminal stacks an overlay's boxes over the page by its
1732            // placement (they clear the Cells behind them): one placed by
1733            // its insets (a sheet's panel, a toast) is its own anchor.
1734            let origin = self.framed_within(key, frame, host);
1735            let own = self.layout.grid().map(|_| crate::overlay::PlacedAnchor {
1736                bounds: Bounds {
1737                    origin,
1738                    size: frame.size,
1739                },
1740                node: None,
1741                placement: config.placement,
1742            });
1743            self.set_native_overlay_anchor(key, own);
1744            return origin;
1745        };
1746        let Some(area) = self.overlay_area(key, host) else {
1747            return frame.origin;
1748        };
1749        // A terminal frames a popup's box one Cell outside it (a rounded
1750        // line, `nsh-platform-tui`): it is placed with that frame, which
1751        // then sits beside the trigger, never on its row, and lines up
1752        // with its start or end.
1753        let ring = self.outside_frame(key);
1754        let framed = Size {
1755            width: frame.size.width + ring.width * 2.0,
1756            height: frame.size.height + ring.height * 2.0,
1757        };
1758        let placed = match self.covering(key, config, framed) {
1759            Some(at) => {
1760                // Its start on the anchor's (a list as wide as its
1761                // trigger lines up with it), the cover view's middle on
1762                // the anchor's (a row taller or shorter than the trigger
1763                // keeps its text on the trigger's), inside the area as far
1764                // as it fits.
1765                let keep = |v: f32, lo: f32, hi: f32, len: f32| v.min(hi - len).max(lo);
1766                let x = keep(
1767                    anchor.origin.x.0,
1768                    area.origin.x.0,
1769                    area.right().0,
1770                    framed.width.0,
1771                );
1772                let y = keep(
1773                    anchor.origin.y.0 + (anchor.size.height.0 - at.size.height.0) / 2.0
1774                        - at.origin.y.0
1775                        - ring.height.0,
1776                    area.origin.y.0,
1777                    area.bottom().0,
1778                    framed.height.0,
1779                );
1780                Placed {
1781                    origin: point(Points(x), Points(y)),
1782                    placement: config.placement,
1783                    available: area.size,
1784                }
1785            }
1786            None => {
1787                // Beside its anchor (a submenu beside its item) the frame
1788                // takes the rows around the anchor's: the box's first row
1789                // is the anchor's (its last, aligned with the end), as a
1790                // submenu's first item lines up with its item.
1791                // The frame is a ring outside the box or the panel's own
1792                // line inside it: a row either way.
1793                let line = match self.layout.grid() {
1794                    Some(grid) if self.framed_box(key).is_some() => grid.height,
1795                    _ => ring.height.0,
1796                };
1797                // Elsewhere the overlay's own padding and border are the
1798                // rows around it: its content, not its edge, lines up with
1799                // the row beside it, as a submenu's first item is level
1800                // with its trigger.
1801                let own = match (resolved_anchor, self.layout.grid()) {
1802                    (OverlayAnchor::Beside { .. }, None) => self.nodes[key as usize]
1803                        .layout
1804                        .map(|l| self.rounded_layout(l)),
1805                    _ => None,
1806                };
1807                let (lead, trail) = match (own, config.placement.is_horizontal()) {
1808                    (Some(l), true) => (
1809                        l.padding.top + l.border.top,
1810                        l.padding.bottom + l.border.bottom,
1811                    ),
1812                    (Some(l), false) => (
1813                        l.padding.left + l.border.left,
1814                        l.padding.right + l.border.right,
1815                    ),
1816                    (None, _) => (0.0, 0.0),
1817                };
1818                let anchor = match config.placement.is_horizontal() {
1819                    true => rect(
1820                        anchor.origin.x.0,
1821                        anchor.origin.y.0 - line - lead,
1822                        anchor.size.width.0,
1823                        anchor.size.height.0 + line * 2.0 + lead + trail,
1824                    ),
1825                    false => rect(
1826                        anchor.origin.x.0 - lead,
1827                        anchor.origin.y.0,
1828                        anchor.size.width.0 + lead + trail,
1829                        anchor.size.height.0,
1830                    ),
1831                };
1832                // A terminal's frame is the gap: it starts on the row (or
1833                // the column) after the trigger's, as rounding an offset
1834                // up to a Cell would leave a blank row between them.
1835                let config = match self.layout.grid() {
1836                    Some(_) => OverlayConfig {
1837                        offset: Points::ZERO,
1838                        ..config
1839                    },
1840                    None => config,
1841                };
1842                let rtl = self.nodes[key as usize].rtl;
1843                let horizontal = config.placement.is_horizontal();
1844                match self.natural_extent(key, horizontal, frame.size, area, ring) {
1845                    // Its size follows the room it is told: the side is
1846                    // chosen at its natural size.
1847                    Some(natural) => {
1848                        let natural = match horizontal {
1849                            true => Size {
1850                                width: natural + ring.width * 2.0,
1851                                ..framed
1852                            },
1853                            false => Size {
1854                                height: natural + ring.height * 2.0,
1855                                ..framed
1856                            },
1857                        };
1858                        place_fitted(anchor, natural, area, &config, rtl)
1859                    }
1860                    None => place(anchor, framed, area, &config, rtl),
1861                }
1862            }
1863        };
1864        // On the device pixel grid, as every other frame is (`round`): an
1865        // origin between two pixels (a context menu at the pointer, a
1866        // popup centred on a trigger of odd width) would have the window
1867        // resample the whole overlay, its text included, and draw it soft.
1868        let ratio = self.pixel_ratio();
1869        let placed = Placed {
1870            origin: point(
1871                Points(super::round((placed.origin.x + ring.width).0, ratio)),
1872                Points(super::round((placed.origin.y + ring.height).0, ratio)),
1873            ),
1874            available: framed_room(placed.available, ring),
1875            ..placed
1876        };
1877        let bounds = Bounds {
1878            origin: placed.origin,
1879            size: frame.size,
1880        };
1881        let node = &self.nodes[key as usize];
1882        let (id, listens) = (node.id, node.events.contains(EventKind::Position));
1883        let state = self.overlay_mut(key).expect("overlay");
1884        if state.placed != Some((placed, bounds)) {
1885            state.placed = Some((placed, bounds));
1886            if listens {
1887                state.told = Some(placed.available);
1888                self.events.push(crate::element::JsEvent::Event(
1889                    id,
1890                    EventKind::Position,
1891                    EventPayload::Map(vec![
1892                        (
1893                            "placement",
1894                            PayloadValue::Str(placed.placement.name().into()),
1895                        ),
1896                        ("bounds", PayloadValue::Bounds(bounds)),
1897                        ("available", PayloadValue::Size(placed.available)),
1898                    ]),
1899                ));
1900            }
1901        }
1902        self.set_native_overlay_anchor(
1903            key,
1904            Some(crate::overlay::PlacedAnchor {
1905                bounds: anchor,
1906                node: match resolved_anchor {
1907                    OverlayAnchor::Node(id) => Some(id),
1908                    _ => None,
1909                },
1910                placement: placed.placement,
1911            }),
1912        );
1913        placed.origin
1914    }
1915
1916    /// The extent of overlay `key` (laid out at `size`) along its side's
1917    /// axis (`horizontal`: its width) when its size follows the room it
1918    /// was told: its max size that way is the `available` it last heard
1919    /// (a select's list, an app's popup that scrolls past it). That room
1920    /// may be the other side's, or the side's before its content grew, so
1921    /// while it holds the overlay to it the core measures the overlay
1922    /// without it (up to `area`, as large as either side's room can be,
1923    /// less the terminal's frame `ring`): once per layout, only then.
1924    /// `None` for any other overlay: its size is its own, placed as it is.
1925    fn natural_extent(
1926        &mut self,
1927        key: Key,
1928        horizontal: bool,
1929        size: Size<Points>,
1930        area: Bounds<Points>,
1931        ring: Size<Points>,
1932    ) -> Option<Points> {
1933        let state = self.overlay(key)?;
1934        let told = state.told?;
1935        let layout = self.nodes[key as usize].layout?;
1936        let max = self.layout.style(layout).max_size;
1937        let room = framed_room(area.size, ring);
1938        let (max, told, extent, room) = match horizontal {
1939            true => (max.width, told.width, size.width, room.width),
1940            false => (max.height, told.height, size.height, room.height),
1941        };
1942        // A max size of the app's own: the overlay's size is its own.
1943        let taffy::ExpandedLengthPercentageAuto::Length(max) = max.expand() else {
1944            return None;
1945        };
1946        let follows = |room: Points| (max - room.0).abs() <= 0.5;
1947        if !follows(told) && !state.held.is_some_and(follows) {
1948            return None;
1949        }
1950        let state = self.overlay_mut(key)?;
1951        state.held = Some(Points(max));
1952        let state = self.overlay(key)?;
1953        // Short of the max it is held to: its natural size already.
1954        if extent.0 < max - 0.5 {
1955            return Some(extent);
1956        }
1957        if let Some(natural) = state.natural {
1958            return Some(natural);
1959        }
1960        let measure = super::leaf_measure(&self.text_engine, &mut self.measure_cache);
1961        let measured = self
1962            .layout
1963            .extent_capped(layout, !horizontal, room.0, measure)?;
1964        let natural = Points(measured).max(extent);
1965        self.overlay_mut(key)?.natural = Some(natural);
1966        Some(natural)
1967    }
1968
1969    /// Where unanchored overlay `key`, laid out at `frame` in host
1970    /// `host`, goes: in a terminal moved so the frame drawn outside its box
1971    /// (`outside_frame`) stays on the screen, as the box would at its edge
1972    /// (a toast at the bottom); where it is. A box across the whole screen
1973    /// (a bottom sheet as wide as it, a drawer as tall) is docked to the
1974    /// edge it is flush with: it stays there, the frame's side on that edge
1975    /// off the screen, rather than leave a row for a line under it.
1976    fn framed_within(&self, key: Key, frame: Bounds<Points>, host: NodeId) -> Point<Points> {
1977        let (Some((ring, inner)), Some((size, _))) =
1978            (self.framed_box(key), self.overlay_host_size(host))
1979        else {
1980            return frame.origin;
1981        };
1982        let spans = |extent: Points, ring: Points, room: Points| extent + ring * 2.0 > room;
1983        let fit = |at: Points,
1984                   offset: Points,
1985                   extent: Points,
1986                   ring: Points,
1987                   room: Points,
1988                   docked: bool| {
1989            let (first, last) = (at + offset, at + offset + extent);
1990            let flush = docked && (first.0.abs() < 0.5 || (room - last).0.abs() < 0.5);
1991            let (start, end) = (first - ring, last + ring);
1992            if spans(extent, ring, room) || flush {
1993                at
1994            } else if start < Points::ZERO {
1995                at - start
1996            } else if end > room {
1997                at - (end - room)
1998            } else {
1999                at
2000            }
2001        };
2002        point(
2003            fit(
2004                frame.origin.x,
2005                inner.origin.x,
2006                inner.size.width,
2007                ring.width,
2008                size.width,
2009                spans(inner.size.height, ring.height, size.height),
2010            ),
2011            fit(
2012                frame.origin.y,
2013                inner.origin.y,
2014                inner.size.height,
2015                ring.height,
2016                size.height,
2017                spans(inner.size.width, ring.width, size.width),
2018            ),
2019        )
2020    }
2021
2022    /// The Cell a terminal frames overlay `key`'s box in, outside it, on
2023    /// each side (none elsewhere): the painter draws a rounded line around
2024    /// the first box in it that has a surface, unless the layout kept that
2025    /// box's border (a card's) inside it.
2026    fn outside_frame(&self, key: Key) -> Size<Points> {
2027        self.framed_box(key)
2028            .map_or_else(Size::default, |(ring, _)| ring)
2029    }
2030
2031    /// The frame [`Self::outside_frame`] is around in a terminal, and
2032    /// that box's bounds in overlay `key`.
2033    fn framed_box(&self, key: Key) -> Option<(Size<Points>, Bounds<Points>)> {
2034        let grid = self.layout.grid()?;
2035        // A popup is its line, at every depth of color: the frame around
2036        // its box takes a Cell each side, and the app's fill of its panel
2037        // is the popup itself, which the painter does not paint again.
2038        let ring = Size {
2039            width: Points(grid.width),
2040            height: Points(grid.height),
2041        };
2042        let mut at = key;
2043        let mut origin = Point::default();
2044        loop {
2045            let n = &self.nodes[at as usize];
2046            let layout = n.layout.map(|l| self.layout.unrounded_layout(l));
2047            if at != key
2048                && let Some(l) = layout
2049            {
2050                origin.x += Points(l.location.x);
2051                origin.y += Points(l.location.y);
2052            }
2053            let w = n.view_style.borders.widths;
2054            let bordered = [w.top, w.right, w.bottom, w.left]
2055                .iter()
2056                .any(|&v| v > Points::ZERO);
2057            if bordered || n.view_style.background_color.0 & 255 != 0 {
2058                let kept = layout.is_some_and(|l| l.border.top > 0.0 || l.border.left > 0.0);
2059                let ring = if kept { Size::default() } else { ring };
2060                let size = layout.map_or_else(Size::default, |l| Size {
2061                    width: Points(l.size.width),
2062                    height: Points(l.size.height),
2063                });
2064                return Some((ring, Bounds { origin, size }));
2065            }
2066            // The list itself with no box of its own: its options are
2067            // not the popup's box (a highlighted first option's fill
2068            // would take the frame), so the popup is framed as below.
2069            let first = if self.is_options(at) {
2070                None
2071            } else {
2072                n.children.iter().find(|&&c| {
2073                    let c = &self.nodes[c as usize];
2074                    !c.is_overlay() && c.layout.is_some()
2075                })
2076            };
2077            let Some(&first) = first else {
2078                // No box of the app's: a popup holding a list (a select's,
2079                // a menu) is framed around its own box all the same, a
2080                // terminal's surface for the list.
2081                if !self.holds_list(key, 3) {
2082                    return None;
2083                }
2084                // The layout's own line around the list (a popup's panel
2085                // takes a Cell each side for it) is the frame already.
2086                let ring = match self.lined_panel(at, 3) {
2087                    true => Size::default(),
2088                    false => ring,
2089                };
2090                let n = &self.nodes[key as usize];
2091                let size = n.layout.map_or_else(Size::default, |l| {
2092                    let l = self.layout.unrounded_layout(l);
2093                    Size {
2094                        width: Points(l.size.width),
2095                        height: Points(l.size.height),
2096                    }
2097                });
2098                return Some((
2099                    ring,
2100                    Bounds {
2101                        origin: Point::default(),
2102                        size,
2103                    },
2104                ));
2105            };
2106            at = first;
2107        }
2108    }
2109
2110    /// Whether `key` or its first view down to `depth` levels below it has
2111    /// a line of the layout's (a popup's panel a Cell each side): the
2112    /// popup's frame already, drawn inside its box.
2113    fn lined_panel(&self, key: Key, depth: usize) -> bool {
2114        let n = &self.nodes[key as usize];
2115        let lined = n.layout.is_some_and(|l| {
2116            let l = self.layout.unrounded_layout(l);
2117            l.border.top > 0.0 || l.border.left > 0.0
2118        });
2119        lined
2120            || (depth > 0
2121                && n.children
2122                    .iter()
2123                    .find(|&&c| {
2124                        let c = &self.nodes[c as usize];
2125                        !c.is_overlay() && c.layout.is_some()
2126                    })
2127                    .is_some_and(|&c| self.lined_panel(c, depth - 1)))
2128    }
2129
2130    /// Whether `key` or a view `depth` levels below it is a list of
2131    /// options or a menu (`nsh-platform-tui` frames the same popups).
2132    fn holds_list(&self, key: Key, depth: usize) -> bool {
2133        self.is_options(key)
2134            || (depth > 0
2135                && self.nodes[key as usize]
2136                    .children
2137                    .iter()
2138                    .any(|&c| self.holds_list(c, depth - 1)))
2139    }
2140
2141    /// Whether `key` is a list of options or a menu.
2142    fn is_options(&self, key: Key) -> bool {
2143        self.nodes[key as usize].props.as_ref().is_some_and(|p| {
2144            matches!(
2145                p.accessibility.role,
2146                crate::AccessibilityRole::Listbox | crate::AccessibilityRole::Menu
2147            )
2148        })
2149    }
2150
2151    /// Finds where each shown overlay goes in the Tab order and mounts it
2152    /// where that changed ([`crate::ViewProps::tab_after`]): its native
2153    /// view is at the end of its root view, but its content follows what
2154    /// comes before it where the app put it, as WAI-ARIA's non-modal
2155    /// popups have it (a popover's content right after its trigger). A list
2156    /// of options or a menu keeps its place (a select's list, a menu: they
2157    /// move the focus with their own keys, and Tab leaves them for the
2158    /// control after their trigger).
2159    pub(super) fn order_overlays_for_tab(&mut self) {
2160        for i in 0..self.overlays.len() {
2161            let key = self.overlays[i];
2162            if self.overlay(key).is_none_or(|s| s.host.is_none())
2163                || !self.nodes[key as usize].created
2164            {
2165                continue;
2166            }
2167            let after = if self.holds_options(key, 3) {
2168                None
2169            } else {
2170                self.tab_predecessor(key)
2171            };
2172            let state = self.overlay_mut(key).expect("overlay");
2173            if state.tab_after == after {
2174                continue;
2175            }
2176            state.tab_after = after;
2177            let node = &self.nodes[key as usize];
2178            self.mount.push(MountItem::ViewProps {
2179                id: node.id,
2180                props: node.mounted_props(),
2181            });
2182        }
2183    }
2184
2185    /// Whether `key` or a view of its own `depth` levels below it (not of
2186    /// an overlay inside it) is a list of options or a menu.
2187    fn holds_options(&self, key: Key, depth: usize) -> bool {
2188        self.is_options(key)
2189            || (depth > 0
2190                && self.nodes[key as usize].children.iter().any(|&c| {
2191                    !self.nodes[c as usize].is_overlay() && self.holds_options(c, depth - 1)
2192                }))
2193    }
2194
2195    /// The native view right before `key` in the app's tree, depth first:
2196    /// the last one in the subtrees of the siblings before it, else its
2197    /// parent's, going up. Other overlays' subtrees are not where they
2198    /// are, so they are passed over.
2199    fn tab_predecessor(&self, key: Key) -> Option<NodeId> {
2200        let mut at = key;
2201        loop {
2202            let parent = self.nodes[at as usize].parent;
2203            if parent == NO_KEY {
2204                return None;
2205            }
2206            let siblings = &self.nodes[parent as usize].children;
2207            let pos = siblings.iter().position(|&c| c == at)?;
2208            if let Some(last) = siblings[..pos]
2209                .iter()
2210                .rev()
2211                .find_map(|&s| self.last_native_in(s))
2212            {
2213                return Some(last);
2214            }
2215            let p = &self.nodes[parent as usize];
2216            if p.created {
2217                return Some(p.id);
2218            }
2219            at = parent;
2220        }
2221    }
2222
2223    /// The last native view in `key`'s subtree, depth first, overlays
2224    /// passed over. A view without one has none below it either (a culled
2225    /// one, a span).
2226    fn last_native_in(&self, key: Key) -> Option<NodeId> {
2227        let node = &self.nodes[key as usize];
2228        if node.is_overlay() || !node.created {
2229            return None;
2230        }
2231        node.children
2232            .iter()
2233            .rev()
2234            .find_map(|&c| self.last_native_in(c))
2235            .or(Some(node.id))
2236    }
2237
2238    fn set_native_overlay_anchor(
2239        &mut self,
2240        key: Key,
2241        anchor: Option<crate::overlay::PlacedAnchor>,
2242    ) {
2243        let Some(state) = self.overlay_mut(key) else {
2244            return;
2245        };
2246        if state.native_anchor == anchor {
2247            return;
2248        }
2249        state.native_anchor = anchor;
2250        let node = &self.nodes[key as usize];
2251        if node.created {
2252            self.mount.push(MountItem::ViewProps {
2253                id: node.id,
2254                props: node.mounted_props(),
2255            });
2256        }
2257    }
2258
2259    /// Where overlay `key`'s `cover` view is in it: taken once both are
2260    /// laid out and kept while the overlay keeps its size `size` and the
2261    /// view its frame in its parent, so its content scrolling moves
2262    /// nothing (a new width once the trigger's is known, a row inserted
2263    /// before it, the view growing or shrinking, take it again).
2264    fn covering(
2265        &mut self,
2266        key: Key,
2267        config: OverlayConfig,
2268        size: Size<Points>,
2269    ) -> Option<Bounds<Points>> {
2270        let cover = config.cover?;
2271        let inner = self.measure(cover)?;
2272        // Its frame in its parent: a scroll moves the parent's content,
2273        // not this; a row inserted before it does. Its size too: placed
2274        // while the overlay's own frame is out, the view still has its
2275        // former one (its frame comes out after), and the end of the
2276        // commit, which places the overlay again, must not keep that.
2277        let place = inner.frame;
2278        if let Some((at, kept, was)) = self.overlay(key)?.covered
2279            && kept == size
2280            && was == place
2281        {
2282            return Some(at);
2283        }
2284        let id = self.nodes[key as usize].id;
2285        let outer = self.measure(id)?;
2286        let at = Bounds {
2287            origin: point(inner.page.x - outer.page.x, inner.page.y - outer.page.y),
2288            size: inner.frame.size,
2289        };
2290        self.overlay_mut(key)?.covered = Some((at, size, place));
2291        Some(at)
2292    }
2293
2294    /// The box around what view `id` draws in its root view: around its
2295    /// children's frames, or its own while it has none (laid out ones only).
2296    /// Only along an axis its style leaves the size `auto` (a wrapper its
2297    /// parent stretches): along one it sets (a trigger 28 points tall with
2298    /// its label centered), its own box is what shows.
2299    fn content_bounds(&self, id: NodeId) -> Option<Bounds<Points>> {
2300        let own = self.measure(id)?;
2301        let key = self.key(id).ok()?;
2302        let mut out: Option<(f32, f32, f32, f32)> = None;
2303        for &c in &self.nodes[key as usize].children {
2304            let n = &self.nodes[c as usize];
2305            if n.is_overlay() || n.layout.is_none() {
2306                continue;
2307            }
2308            let Some(m) = self.measure(n.id) else {
2309                continue;
2310            };
2311            let (x0, y0) = (m.page.x.0, m.page.y.0);
2312            let (x1, y1) = (x0 + m.frame.size.width.0, y0 + m.frame.size.height.0);
2313            out = Some(match out {
2314                None => (x0, y0, x1, y1),
2315                Some((a, b, c, d)) => (a.min(x0), b.min(y0), c.max(x1), d.max(y1)),
2316            });
2317        }
2318        Some(match out {
2319            // Around the children, and the view's own padding and border
2320            // around them (a trigger draws those too), within its frame.
2321            Some((x0, y0, x1, y1)) => {
2322                let l = self.rounded_layout(self.nodes[key as usize].layout?);
2323                let (left, top) = (own.page.x.0, own.page.y.0);
2324                let (right, bottom) =
2325                    (left + own.frame.size.width.0, top + own.frame.size.height.0);
2326                let size = self.layout.style(self.nodes[key as usize].layout?).size;
2327                let auto = taffy::Dimension::auto();
2328                let (x0, x1) = if size.width == auto {
2329                    (
2330                        (x0 - l.padding.left - l.border.left).max(left),
2331                        (x1 + l.padding.right + l.border.right).min(right),
2332                    )
2333                } else {
2334                    (left, right)
2335                };
2336                let (y0, y1) = if size.height == auto {
2337                    (
2338                        (y0 - l.padding.top - l.border.top).max(top),
2339                        (y1 + l.padding.bottom + l.border.bottom).min(bottom),
2340                    )
2341                } else {
2342                    (top, bottom)
2343                };
2344                rect(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2345            }
2346            None => Bounds {
2347                origin: own.page,
2348                size: own.frame.size,
2349            },
2350        })
2351    }
2352
2353    /// Whether an overlay with an anchor is shown in the root view (not in
2354    /// a modal): one whose room [`Core::set_overlay_area`] changes.
2355    pub(super) fn root_overlay_shown(&self) -> bool {
2356        self.overlays.iter().any(|&key| {
2357            self.overlay(key).is_some_and(|s| s.host == Some(ROOT_ID))
2358                && self.resolved_anchor(key) != OverlayAnchor::None
2359        })
2360    }
2361
2362    /// Places the shown overlays with an anchor again, at the end of the
2363    /// commit: their anchors may have moved (the layout, the lists,
2364    /// scrolling).
2365    pub(super) fn place_overlays(&mut self) {
2366        for i in 0..self.overlays.len() {
2367            let key = self.overlays[i];
2368            let anchored = self.overlay(key).is_some_and(|s| s.host.is_some())
2369                && self.resolved_anchor(key) != OverlayAnchor::None;
2370            let frame = self.nodes[key as usize].frame;
2371            // In a terminal an unanchored one is its own anchor
2372            // (`overlay_origin`), which its layout set.
2373            if !anchored && self.layout.grid().is_none() {
2374                self.set_native_overlay_anchor(key, None);
2375            }
2376            if !anchored || !self.nodes[key as usize].created || frame.size.width.0.is_nan() {
2377                continue;
2378            }
2379            let origin = self.overlay_origin(key, frame);
2380            if origin != frame.origin {
2381                self.set_frame(
2382                    key,
2383                    Bounds {
2384                        origin,
2385                        size: frame.size,
2386                    },
2387                );
2388            }
2389        }
2390    }
2391}
2392
2393/// The style of an overlay's wrapper: the box `size` it is laid out in.
2394fn sized(size: Size<Points>) -> taffy::Style {
2395    taffy::Style {
2396        size: taffy::Size {
2397            width: taffy::Dimension::length(size.width.0),
2398            height: taffy::Dimension::length(size.height.0),
2399        },
2400        ..taffy::Style::default()
2401    }
2402}
2403
2404/// The room inside `room` left to a box a terminal frames `ring` outside
2405/// it on each side ([`Core::outside_frame`]): what its layout, the size it
2406/// is measured at and the `available` it is told all keep to, so its frame
2407/// fits where the box is placed.
2408fn framed_room(room: Size<Points>, ring: Size<Points>) -> Size<Points> {
2409    Size {
2410        width: (room.width - ring.width * 2.0).max(Points::ZERO),
2411        height: (room.height - ring.height * 2.0).max(Points::ZERO),
2412    }
2413}
2414
2415/// The view an overlay is anchored to.
2416fn anchor_node(state: &OverlayState) -> Option<NodeId> {
2417    match state.config.anchor {
2418        OverlayAnchor::Node(id)
2419        | OverlayAnchor::Content(id)
2420        | OverlayAnchor::Beside { node: id, .. } => Some(id),
2421        _ => None,
2422    }
2423}