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