teksilo_core/overlay.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Overlay system for tooltips, dropdown menus, context menus, and popovers.
5//!
6//! Overlays render outside the normal layout hierarchy. They float above the
7//! main content, positioned relative to an anchor widget or the pointer.
8//! The `OverlayManager` coordinates creation, positioning, stacking, dismissal,
9//! event routing, and accessibility.
10
11use std::rc::Rc;
12use std::time::{Duration, Instant};
13
14use teksilo_canvas::{Point, Rect, Size, Vec2};
15use teksilo_tokens::Corner;
16
17use crate::environment::LayoutDirection;
18use crate::pointer::PointerId;
19use crate::signal::Signal;
20use crate::widget_id::WidgetId;
21
22pub mod direction;
23mod placement_impl;
24mod safe_triangle;
25pub mod text_affordance;
26mod viewport;
27
28pub use direction::{HorizontalSide, InlineDirection, inline_band_at, inline_edge_band};
29pub use text_affordance::{OverlayBand, SelectionHandleKind};
30pub use viewport::OverlayViewport;
31
32pub(crate) use safe_triangle::point_in_safe_triangle;
33
34/// How long a submenu's safe region stays armed after the pointer
35/// leaves the trigger row.
36///
37/// The region suppresses both dismissal paths (the sibling
38/// hover-switch and the overlay's own pointer-leave grace), so it
39/// needs a ceiling: a pointer that stops inside the cone is no longer
40/// travelling, and the menu must go back to behaving normally. 600 ms
41/// is long enough for a deliberate, slow diagonal across a tall
42/// submenu and short enough that a parked pointer resolves before the
43/// user notices anything is stuck.
44pub(crate) const SAFE_REGION_BUDGET: Duration = Duration::from_millis(600);
45
46/// Why an overlay went away.
47///
48/// The dismissal routes were previously indistinguishable at the callback,
49/// which is what made a dismissed `MessageBox` unable to say whether the user
50/// had pressed Escape, clicked outside, or been closed out from under by an
51/// ancestor — three answers an application owes its caller and could not tell
52/// apart. Five of the manager's dismissal entry points already encode the
53/// reason in their own identity; this carries it the rest of the way.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55#[non_exhaustive]
56pub enum DismissReason {
57 /// The user pressed Escape.
58 Escape,
59 /// The user pressed outside the overlay's bounds — the scrim, or simply
60 /// the rest of the window.
61 OutsidePress,
62 /// The pointer left the overlay and its anchor, under
63 /// [`DismissBehavior::PointerLeave`].
64 PointerLeave,
65 /// An ancestor overlay was dismissed and took this one with it. The
66 /// ancestor's own callback receives the reason that actually happened;
67 /// only the descendants it drags along see this.
68 Cascade,
69 /// The application asked: an explicit `dismiss`, `ctx.dismiss_modal()`, a
70 /// widget closing its own overlay, or a sibling replacing it.
71 Programmatic,
72}
73
74/// Callback invoked by the framework when an overlay is dismissed —
75/// regardless of the dismiss path (Escape, click outside, pointer
76/// leave, explicit API call, cascade). The anchor widget uses this
77/// hook to reset its own interaction state so that SR-facing
78/// properties like `set_expanded` on a `ComboBox` or a submenu
79/// trigger stay consistent with the actual overlay-visible state.
80///
81/// Fired exactly once per overlay lifetime, at the point the
82/// overlay is removed from the stack. `Fn` rather than `FnOnce`
83/// simply because it's easier to pass around by `Rc`; the
84/// framework only invokes it once.
85///
86/// # Why it takes an `EventContext`
87///
88/// It did not, and that cost a dismissed modal its result: `MessageBox` and
89/// `InputDialog` both report through a `Fn(.., &mut EventContext)`, so a
90/// callback with no context could not deliver one and the user's answer was
91/// dropped on every route except a button press. The manager cannot mint a
92/// context — it has no tree — so it no longer invokes these itself: it parks
93/// them (`OverlayManager::take_pending_dismiss`, crate-private) and the tree
94/// runs them at the point it already holds a `WindowOps`, still before focus
95/// is restored to the trigger.
96pub type OverlayDismissCallback = Rc<dyn Fn(DismissReason, &mut crate::widget::EventContext)>;
97
98/// Where an overlay goes, as a function of its anchor's bounds (in window
99/// coordinates, as the layout pass that is placing the overlay left them) and
100/// the layout direction.
101///
102/// Installed with
103/// [`EventContext::track_overlay_placement_by_content`](crate::widget::EventContext::track_overlay_placement_by_content),
104/// for an overlay that hangs off a part of its anchor no placement names.
105pub type OverlayPlacementSource = Rc<dyn Fn(Rect, LayoutDirection) -> OverlayPlacement>;
106
107impl OverlayPlacement {
108 /// Whether this is a modal's placement: [`Centered`](Self::Centered), the
109 /// dialog's, or [`TopCenter`](Self::TopCenter), a command palette's. The
110 /// tree reads modality off the placement, so these are the overlays it
111 /// treats as modal: focus stays inside them, the page behind them refuses
112 /// assistive-technology requests, and an overlay opened inside one never
113 /// dismisses it.
114 pub fn is_modal(&self) -> bool {
115 matches!(self, Self::Centered | Self::TopCenter { .. })
116 }
117}
118
119/// Unique identifier for an active overlay.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121pub struct OverlayId(u64);
122
123impl OverlayId {
124 pub(crate) fn new(id: u64) -> Self {
125 Self(id)
126 }
127}
128
129/// How an overlay is positioned relative to its anchor.
130#[derive(Debug, Clone)]
131pub enum OverlayPlacement {
132 /// Below the anchor, leading-edge aligned (dropdown).
133 ///
134 /// The panel is made **at least as wide as the anchor** (the drop-down
135 /// convention: a list hanging off a field spans the field) and may be
136 /// wider when its content asks for more. Content that must keep its own
137 /// width, such as a small popover off a wide trigger, wants
138 /// [`NearAnchor`](Self::NearAnchor) or [`TrailingEdge`](Self::TrailingEdge).
139 Below,
140 /// Above the anchor (fallback when no space below).
141 ///
142 /// A panel taller than the room above its anchor is pinned to the top of
143 /// the usable area and **shrunk to that room**, not slid down onto the
144 /// anchor: the control that opened a panel has to stay visible, or the
145 /// user is choosing blind. Where there is no room at all to shrink into,
146 /// the ideal position is kept — an empty panel is not an improvement on a
147 /// badly placed one.
148 ///
149 /// The panel is made **at least as wide as the anchor** (the drop-down
150 /// convention: a list hanging off a field spans the field) and may be
151 /// wider when its content asks for more. Content that must keep its own
152 /// width, such as a small popover off a wide trigger, wants
153 /// [`NearAnchor`](Self::NearAnchor) or [`TrailingEdge`](Self::TrailingEdge).
154 Above,
155 /// To the trailing side of the anchor (submenu).
156 TrailingEdge,
157 /// At the pointer position (context menu).
158 AtPointer(Point),
159 /// At the pointer, but never *under* it: the panel is placed in a quadrant
160 /// that clears `avoid` entirely.
161 ///
162 /// The touch form of [`AtPointer`](Self::AtPointer). A mouse cursor is an
163 /// arrow drawn *beside* the pixel it names, so a menu whose corner lands on
164 /// that pixel is fully visible; a finger is an opaque disc centred on it,
165 /// so the same menu opens with its first two rows underneath the hand. The
166 /// fix is not an offset — an offset large enough for a thumb is absurd for
167 /// a stylus — but a rectangle to keep clear, which the caller sizes from
168 /// the contact patch the digitiser reported.
169 ///
170 /// Quadrant preference is **inline-start first** (left of the contact under
171 /// LTR, right of it under RTL), then above-versus-below, then the mirrored
172 /// side: a hand approaches from the reader's own side, so the far side is
173 /// the one that stays visible. Every candidate clears `avoid` outright; the
174 /// viewport clamp is applied on the axis that is already clear, so clamping
175 /// can never push the panel back under the contact.
176 AtPointerAvoiding {
177 /// Where the contact was reported.
178 point: Point,
179 /// The rectangle the panel must not overlap — the contact patch,
180 /// centred on `point`.
181 avoid: Rect,
182 },
183 /// Above a text selection, centred on it, flipping below when the selection
184 /// is against the top of the usable area.
185 ///
186 /// The selection toolbar's placement. Anchor bounds are ignored: the thing
187 /// it hangs off is a range of text, whose rectangle the editor supplies and
188 /// updates as the selection changes, not a widget.
189 AboveSelection {
190 /// The selection's bounding rectangle, in window coordinates.
191 selection: Rect,
192 },
193 /// Below a rectangle, centred on it, flipping above when the rectangle is
194 /// against the bottom of the usable area.
195 ///
196 /// The mirror of [`AboveSelection`](Self::AboveSelection), and like it
197 /// anchor-independent: the caller supplies the rectangle in window
198 /// coordinates and keeps it current, as a slider's value readout does
199 /// with the strip its thumb occupies.
200 BelowSelection {
201 /// The rectangle to hang below, in window coordinates.
202 selection: Rect,
203 },
204 /// Near the anchor with a preferred alignment and offset (tooltip).
205 NearAnchor { offset: Vec2 },
206 /// Centered within the viewport (dialog).
207 Centered,
208 /// Bottom-centered within the viewport (snackbar/toast).
209 BottomCenter,
210 /// Horizontally centred, with the top edge `offset` below the top of the
211 /// usable area (a command palette). Anchor bounds are ignored. The top
212 /// edge stays put while the content's height changes, which is the point:
213 /// a centred surface that shrinks as its list narrows moves everything
214 /// above the list with it. When the content would run past the bottom,
215 /// it is raised, and then shrunk, to fit.
216 TopCenter { offset: f32 },
217 /// Below the anchor if space allows, otherwise above (combo box dropdown).
218 /// The viewport height is supplied by `position_overlays()` at layout time.
219 ///
220 /// When the panel fits on neither side it takes whichever side has more
221 /// room and is shrunk to it — a tie keeps the flip upward. It is never slid
222 /// over the anchor; see [`Above`](Self::Above).
223 ///
224 /// The panel is made **at least as wide as the anchor** (the drop-down
225 /// convention: a list hanging off a field spans the field) and may be
226 /// wider when its content asks for more. Content that must keep its own
227 /// width, such as a small popover off a wide trigger, wants
228 /// [`NearAnchor`](Self::NearAnchor) or [`TrailingEdge`](Self::TrailingEdge).
229 BelowPreferred,
230 /// Snaps content to a viewport corner with a per-axis margin
231 /// (used by `ToastHost` for stacked toast notifications, also
232 /// suitable for picture-in-picture, floating action overlays).
233 /// Anchor bounds are ignored. The leading/trailing axis honours
234 /// `LayoutDirection`: `TopTrailing` is top-right under LTR and
235 /// top-left under RTL.
236 ViewportCorner { corner: Corner, margin: Vec2 },
237 /// Fills the entire viewport, anchor-independent. Used by the
238 /// modal-presentation pipeline to mount a dialog scrim behind a
239 /// centered modal panel — the scrim covers the full window so the
240 /// content behind dims uniformly. Anchor bounds are ignored.
241 FullViewport,
242}
243
244/// The contact patch assumed for a coarse pointer whose backend reports none.
245///
246/// 24 dp is the size of the smallest thing a finger is ever asked to hit, so it
247/// is the smallest rectangle a finger can be assumed to cover. Backends that do
248/// report a patch (Windows `WM_POINTER`, Wayland `wp_touch` with the shape
249/// extension) usually report a larger one, and that number is preferred — this
250/// is the floor, not the answer.
251pub const ASSUMED_CONTACT_PATCH: Size = Size {
252 width: 24.0,
253 height: 24.0,
254};
255
256impl OverlayPlacement {
257 /// The placement a point-anchored panel — a context menu, a drop-down
258 /// raised from a long press — should use for the pointer that opened it.
259 ///
260 /// **One branch, every menu.** A coarse pointer gets
261 /// [`AtPointerAvoiding`](Self::AtPointerAvoiding) with the contact patch as
262 /// the rectangle to clear; everything else gets the
263 /// [`AtPointer`](Self::AtPointer) it has always had, byte for byte. Putting
264 /// the decision here rather than at each call site is the point: a menu
265 /// that forgot to ask opens under the finger, and there is no way to notice
266 /// that from a mouse.
267 pub fn at_pointer_for(point: Point, pointer: &crate::pointer::PointerInfo) -> Self {
268 if !pointer.kind.is_coarse() {
269 return OverlayPlacement::AtPointer(point);
270 }
271 let contact = pointer.axes.contact.unwrap_or(ASSUMED_CONTACT_PATCH);
272 let patch = Size::new(
273 contact.width.max(ASSUMED_CONTACT_PATCH.width),
274 contact.height.max(ASSUMED_CONTACT_PATCH.height),
275 );
276 OverlayPlacement::AtPointerAvoiding {
277 point,
278 avoid: rect_centred_on(point, patch),
279 }
280 }
281}
282
283/// `size`, centred on `point`. `Rect` has no such constructor and the two
284/// places that need one must agree exactly, since one computes the rectangle a
285/// menu must clear and the other asserts that it did.
286pub(crate) fn rect_centred_on(point: Point, size: Size) -> Rect {
287 Rect::new(
288 point.x - size.width / 2.0,
289 point.y - size.height / 2.0,
290 size.width,
291 size.height,
292 )
293}
294
295/// Placement preference for a tooltip relative to its anchor. Resolved to
296/// a concrete [`OverlayPlacement`] at show time (see
297/// `WidgetTree::tooltip_overlay_placement`).
298///
299/// `Below` is the default (drop below the anchor, flip above near the
300/// viewport edge). `Side` opens to the anchor's trailing side (RTL-aware,
301/// with a leading fallback) — for anchors stacked **vertically** (menu
302/// items, a vertical tab strip, list/tree rows, a docking activity rail,
303/// a vertical `RadioTileGroup`) where a `Below` tooltip would cover the
304/// next sibling.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
306pub enum TooltipPlacement {
307 /// Below the anchor (flips above near the viewport edge). The default.
308 #[default]
309 Below,
310 /// To the anchor's trailing side (RTL-aware, leading fallback).
311 Side,
312}
313
314/// When an overlay is dismissed.
315#[derive(Debug, Clone)]
316pub enum DismissBehavior {
317 /// Dismiss when the user clicks outside the overlay.
318 ClickOutside,
319 /// Dismiss when the user presses Escape.
320 EscapeKey,
321 /// Dismiss on either Escape or an outside click.
322 EscapeOrClickOutside,
323 /// Dismiss when the pointer leaves both anchor and overlay.
324 PointerLeave { delay: Duration },
325 /// Dismiss only via explicit API call.
326 Manual,
327}
328
329/// Where the overlay renders.
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub enum OverlayLayer {
332 /// Rendered within the application window's wgpu surface.
333 InTree,
334 /// Rendered in a separate native OS window.
335 NativePopup,
336 /// Framework decides based on content size.
337 Auto,
338}
339
340/// A request to show an overlay.
341///
342/// Built with [`new`](Self::new), which takes what every overlay has to
343/// decide, and the builder methods for the rest. The fields stay public, so a
344/// request can still be adjusted after it is built: that is how a value that
345/// is already an `Option` is set, since the builders take the bare value.
346///
347/// Non-exhaustive, so that a field added later reaches every caller as its
348/// default instead of breaking each struct literal.
349#[non_exhaustive]
350pub struct OverlayRequest {
351 /// The root widget of the overlay content.
352 pub content_id: WidgetId,
353 /// The widget this overlay is anchored to.
354 pub anchor: WidgetId,
355 /// Positioning relative to the anchor.
356 pub placement: OverlayPlacement,
357 /// How the overlay is dismissed.
358 pub dismiss: DismissBehavior,
359 /// Rendering layer.
360 pub layer: OverlayLayer,
361 /// Parent overlay (for submenu cascading).
362 pub parent_overlay: Option<OverlayId>,
363 /// Invoked when the overlay is dismissed by any path. Use this
364 /// to reset anchor-side state (e.g. `ComboBox.interaction`)
365 /// when the framework tears down the overlay without going
366 /// through the anchor's own key/tap handlers.
367 pub on_dismiss: Option<OverlayDismissCallback>,
368 /// Optional fade-in / fade-out duration. When `Some`, the
369 /// framework attaches an animated opacity scope to `content_id`
370 /// at show time (using the existing `set_opacity` rendering
371 /// pipeline — no `Fade` widget required from the caller), tweens
372 /// the opacity from 0 → 1 over `duration`, and on dismiss
373 /// reverses the tween and defers the actual stack removal by
374 /// `duration`. Set with [`OverlayRequest::with_fade`].
375 pub fade_duration: Option<Duration>,
376 /// The overlay takes no input. Set with [`OverlayRequest::inert`], which
377 /// says what that means.
378 pub inert: bool,
379 /// Where a command chosen in this overlay is sent from, when that is not
380 /// where the overlay gives focus back. Set with
381 /// [`OverlayRequest::command_source`].
382 #[doc(hidden)]
383 pub command_source: Option<WidgetId>,
384}
385
386impl OverlayRequest {
387 /// A request to show `content_id` at `placement` relative to `anchor`,
388 /// taken down the way `dismiss` says.
389 ///
390 /// `dismiss` is an argument rather than a default because no one value
391 /// suits most overlays, and the likeliest default is the worst one to
392 /// inherit unawares: a [`Manual`](DismissBehavior::Manual) overlay that
393 /// takes input is opaque to Escape, for itself and for every overlay
394 /// beneath it (see [`OverlayManager::try_dismiss_top_on_escape`]).
395 ///
396 /// Everything else starts at the value nearly every overlay uses:
397 ///
398 /// - [`layer`](Self::layer()): [`OverlayLayer::InTree`].
399 /// - [`parent_overlay`](Self::parent_overlay()): `None`, a top-level
400 /// overlay.
401 /// - [`on_dismiss`](Self::on_dismiss()): `None`.
402 /// - [`with_fade`](Self::with_fade): `None`, so the overlay appears and
403 /// goes without a fade.
404 /// - [`inert`](Self::inert()): `false`, an overlay that takes input.
405 ///
406 /// ```
407 /// use std::time::Duration;
408 /// use teksilo_core::WidgetId;
409 /// use teksilo_core::overlay::{DismissBehavior, OverlayPlacement, OverlayRequest};
410 /// # let (popup, trigger) = (WidgetId::default(), WidgetId::default());
411 ///
412 /// let request = OverlayRequest::new(
413 /// popup,
414 /// trigger,
415 /// OverlayPlacement::BelowPreferred,
416 /// DismissBehavior::EscapeOrClickOutside,
417 /// )
418 /// .with_fade(Duration::from_millis(150));
419 /// assert_eq!(request.fade_duration, Some(Duration::from_millis(150)));
420 /// ```
421 pub fn new(
422 content_id: WidgetId,
423 anchor: WidgetId,
424 placement: OverlayPlacement,
425 dismiss: DismissBehavior,
426 ) -> Self {
427 Self {
428 content_id,
429 anchor,
430 placement,
431 dismiss,
432 layer: OverlayLayer::InTree,
433 parent_overlay: None,
434 on_dismiss: None,
435 fade_duration: None,
436 inert: false,
437 command_source: None,
438 }
439 }
440
441 /// Where a command chosen in this overlay is sent from, and so what
442 /// `WidgetTree::can_handle` answers for while it is open, when that is
443 /// not the widget the overlay gives focus back to. A menu bar's menu
444 /// opened from the keyboard gives focus back to its title, and its
445 /// command goes to the widget focused before the bar took focus, which
446 /// the bar names here. Default: `None`, where focus goes back.
447 #[doc(hidden)]
448 pub fn command_source(mut self, id: WidgetId) -> Self {
449 self.command_source = Some(id);
450 self
451 }
452
453 /// Render the overlay on `layer`. Default: [`OverlayLayer::InTree`].
454 pub fn layer(mut self, layer: OverlayLayer) -> Self {
455 self.layer = layer;
456 self
457 }
458
459 /// Nest the overlay under `parent`, so that dismissing `parent` takes this
460 /// one down with it, the way a menu takes its submenu. Default: `None`, a
461 /// top-level overlay.
462 ///
463 /// A parent that is already an `Option` is assigned to the
464 /// [`parent_overlay`](field@Self::parent_overlay) field instead.
465 pub fn parent_overlay(mut self, parent: OverlayId) -> Self {
466 self.parent_overlay = Some(parent);
467 self
468 }
469
470 /// Run `callback` when the overlay is dismissed, whatever the path.
471 /// Default: `None`.
472 ///
473 /// It takes the shared [`OverlayDismissCallback`] rather than a closure
474 /// because an anchor usually installs one callback on every route that
475 /// opens its overlay; a one-off closure is wrapped in `Rc::new`.
476 pub fn on_dismiss(mut self, callback: OverlayDismissCallback) -> Self {
477 self.on_dismiss = Some(callback);
478 self
479 }
480
481 /// Attach a fade-in / fade-out animation to this request.
482 /// `duration` controls both directions. The framework wires
483 /// everything internally — caller does not create a `Fade`
484 /// widget or manage a signal. Default: no fade.
485 ///
486 /// A duration that is already an `Option` (no fade under reduced motion,
487 /// say) is assigned to the [`fade_duration`](Self::fade_duration) field
488 /// instead.
489 pub fn with_fade(mut self, duration: Duration) -> Self {
490 self.fade_duration = Some(duration);
491 self
492 }
493
494 /// Make the overlay inert: something to look at, never to work. Default:
495 /// not inert.
496 ///
497 /// An inert overlay:
498 ///
499 /// - lets **pointer input** through to what is under it, whether that is
500 /// another overlay or the window: a press or a hover over it is the
501 /// press or the hover of the widget beneath, and a press there is
502 /// outside every overlay it is outside of, so it still closes a
503 /// click-outside popover;
504 /// - is **closed by Escape without consuming the key**, if its
505 /// [`dismiss`](field@Self::dismiss) is one Escape closes
506 /// ([`EscapeKey`](DismissBehavior::EscapeKey),
507 /// [`EscapeOrClickOutside`](DismissBehavior::EscapeOrClickOutside),
508 /// [`PointerLeave`](DismissBehavior::PointerLeave)); whatever its
509 /// `dismiss`, [`Manual`](DismissBehavior::Manual) included, the key goes
510 /// on to what it would have reached with the overlay gone;
511 /// - **never records or restores focus**: focus stays where it is when
512 /// the overlay appears and when it goes;
513 /// - **does not close when focus leaves its anchor**: the code that raised
514 /// it decides when it goes.
515 ///
516 /// For an overlay that only reports, such as a slider's value readout. It
517 /// is a property of the request, read once when the overlay is shown. The
518 /// content root's [`hit_transparent`](crate::widget_builder::WidgetBuilder::hit_transparent)
519 /// and [`event_pass_through`](crate::widget_builder::WidgetBuilder::event_pass_through)
520 /// keep their own meanings and play no part in it: an inert overlay needs
521 /// neither, and setting both does not make an overlay inert.
522 pub fn inert(mut self) -> Self {
523 self.inert = true;
524 self
525 }
526}
527
528/// Fade-on-show / fade-on-dismiss state for an overlay. Populated by
529/// the framework when an [`OverlayRequest`] carries `fade_duration`.
530/// The framework owns the `Signal<f32>` (an animated 0..1 opacity)
531/// and applies it to the overlay's content via `set_opacity`, so the
532/// caller doesn't need to wrap the content in a `Fade` widget — the
533/// rendering walker's opacity scope (Item 1) does the work.
534///
535/// Mirrors the `pointer_leave_started_real/_sim` and
536/// `shown_at_real/_sim` dual-clock pattern used elsewhere in
537/// `ActiveOverlay`: the real-clock field drives the live event loop;
538/// the sim-clock field drives the headless `tick_animations` /
539/// `advance_time` test path so deterministic tests can advance the
540/// fade-out window without `std::thread::sleep`.
541#[derive(Clone)]
542pub(crate) struct OverlayFadeState {
543 /// Animated opacity (0..1) bound to the overlay's content via
544 /// `WidgetTree::set_opacity`. The framework starts the tween at
545 /// 0 and animates to 1 on show, then animates back to 0 on
546 /// dismiss before the deferred removal fires.
547 pub opacity: Signal<f32>,
548 /// Tween duration on both directions. Picked from
549 /// `theme.motion.duration_fast` for tooltip / popover and
550 /// `duration_normal` for snackbar / dialog.
551 pub duration: Duration,
552 /// `Some(start_real)` when a dismiss has been requested and the
553 /// fade-out tween has started. The real-clock processor
554 /// considers the overlay ready for removal once
555 /// `Instant::now() - start_real >= duration`.
556 pub dismissing_started_real: Option<Instant>,
557 /// Why the dismissal that started this fade-out happened. Read when the
558 /// tween completes, so a faded overlay reports the reason the user
559 /// produced rather than the bookkeeping that removed it a frame later.
560 pub dismiss_reason: Option<DismissReason>,
561 /// `Some(start_sim)` set in lockstep with `dismissing_started_real`
562 /// using the tree's `sim_clock`. The sim-clock processor uses
563 /// it for deterministic headless tests.
564 pub dismissing_started_sim: Option<Instant>,
565}
566
567/// An active overlay in the stack.
568pub(crate) struct ActiveOverlay {
569 pub id: OverlayId,
570 pub content_id: WidgetId,
571 pub anchor: WidgetId,
572 pub placement: OverlayPlacement,
573 pub dismiss: DismissBehavior,
574 pub layer: OverlayLayer,
575 /// Which z-band this overlay sits in. See [`OverlayBand`]; the stack is
576 /// kept sorted by it, so this is also the overlay's position class within
577 /// `stack`.
578 pub band: OverlayBand,
579 pub parent_overlay: Option<OverlayId>,
580 /// Computed bounds after positioning.
581 pub bounds: Rect,
582 /// Widget that had focus before this overlay was shown.
583 /// Used to restore focus when the overlay is dismissed.
584 pub focus_restore: Option<WidgetId>,
585 /// [`OverlayRequest::command_source`].
586 pub command_source: Option<WidgetId>,
587 /// When pointer-leave dismissal started (real time).
588 pub pointer_leave_started_real: Option<std::time::Instant>,
589 /// When pointer-leave dismissal started (simulated time).
590 pub pointer_leave_started_sim: Option<std::time::Instant>,
591 /// Apex of the "safe triangle" — the point at which the pointer
592 /// left the anchor, armed by [`OverlayManager::arm_safe_region`].
593 /// While it is set and unexpired, a pointer inside the triangle
594 /// spanned by it and this overlay's near edge counts as still
595 /// inside the overlay's region, so the pointer-leave grace does
596 /// not run — and a pointer that strays back out only starts that
597 /// grace, keeping the apex so a course correction can stop it
598 /// again. See [`safe_triangle`].
599 pub safe_apex: Option<Point>,
600 /// When the safe region was armed (real time). Bounds it by
601 /// [`SAFE_REGION_BUDGET`].
602 pub safe_apex_started_real: Option<std::time::Instant>,
603 /// When the safe region was armed (simulated time).
604 pub safe_apex_started_sim: Option<std::time::Instant>,
605 /// Dismiss automatically after this duration, if set.
606 pub auto_dismiss_after: Option<Duration>,
607 /// While the auto-dismiss timer is paused (via
608 /// [`OverlayManager::pause_auto_dismiss`]), `auto_dismiss_after`
609 /// is cleared and the time that *would have remained* is stashed
610 /// here. [`OverlayManager::resume_auto_dismiss`] restores
611 /// `auto_dismiss_after = Some(this)` and stamps a fresh
612 /// `shown_at_*`. `None` whenever the overlay is not paused.
613 pub paused_remaining: Option<Duration>,
614 /// When the overlay was shown (real time).
615 pub shown_at_real: std::time::Instant,
616 /// When the overlay was shown (simulated time).
617 pub shown_at_sim: std::time::Instant,
618 /// Dismiss callback supplied by the show request. Invoked
619 /// exactly once when the overlay is removed from the stack,
620 /// regardless of dismiss path.
621 pub on_dismiss: Option<OverlayDismissCallback>,
622 /// Optional fade-in / fade-out state. Installed post-show by the
623 /// crate-internal `OverlayManager::attach_fade`, which
624 /// `WidgetTree::attach_overlay_fade` calls whenever the show
625 /// request carried a `fade_duration`; read back from outside
626 /// through [`OverlayManager::fade_duration`]. When `Some`, all
627 /// dismiss paths (auto, escape, click-outside, pointer-leave,
628 /// manual) defer the actual removal until the fade-out tween
629 /// completes.
630 pub fade: Option<OverlayFadeState>,
631 /// The request's [`inert`](OverlayRequest::inert) flag, copied when the
632 /// overlay is shown and never changed after. Such an overlay is skipped by
633 /// every question the manager answers about the pointer —
634 /// [`hit_test`](OverlayManager::hit_test), outside-press dismissal,
635 /// [`interactive_rects`](OverlayManager::interactive_rects) — so a press or
636 /// a hover over it belongs to what is beneath it, an overlay included, and
637 /// a press there is outside every overlay it is outside of. It is never
638 /// the Escape walk's target and never records a focus to restore.
639 pub inert: bool,
640 /// Re-derives [`placement`](Self::placement) from the anchor's bounds on
641 /// every [`position_overlays`](OverlayManager::position_overlays). See
642 /// [`EventContext::track_overlay_placement_by_content`](crate::widget::EventContext::track_overlay_placement_by_content).
643 pub placement_source: Option<OverlayPlacementSource>,
644}
645
646impl ActiveOverlay {
647 /// Whether this overlay is already on its way out — dismissed, but still
648 /// on the stack while its fade-out tween runs.
649 ///
650 /// Such an overlay still answers every stack query, so anything that
651 /// *targets* an overlay has to step over it: dismissing it a second time
652 /// collapses the tween it is in the middle of, and (for input) spends the
653 /// keystroke on a corpse while leaving whatever sits underneath
654 /// unreachable.
655 pub(crate) fn is_dismissing(&self) -> bool {
656 self.fade
657 .as_ref()
658 .is_some_and(|fade| fade.dismissing_started_real.is_some())
659 }
660}
661
662// Manual Debug impl: `Rc<dyn Fn()>` doesn't derive Debug, but the
663// surrounding systems (tests, logging) want ActiveOverlay to be
664// printable. Skip the callback field and tag it with a placeholder.
665impl std::fmt::Debug for ActiveOverlay {
666 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
667 f.debug_struct("ActiveOverlay")
668 .field("id", &self.id)
669 .field("content_id", &self.content_id)
670 .field("anchor", &self.anchor)
671 .field("placement", &self.placement)
672 .field("dismiss", &self.dismiss)
673 .field("layer", &self.layer)
674 .field("band", &self.band)
675 .field("parent_overlay", &self.parent_overlay)
676 .field("bounds", &self.bounds)
677 .field("focus_restore", &self.focus_restore)
678 .field(
679 "pointer_leave_started_real",
680 &self.pointer_leave_started_real,
681 )
682 .field("pointer_leave_started_sim", &self.pointer_leave_started_sim)
683 .field("safe_apex", &self.safe_apex)
684 .field("auto_dismiss_after", &self.auto_dismiss_after)
685 .field("shown_at_real", &self.shown_at_real)
686 .field("shown_at_sim", &self.shown_at_sim)
687 .field(
688 "on_dismiss",
689 &self.on_dismiss.as_ref().map(|_| "<callback>"),
690 )
691 .field("fading", &self.fade.is_some())
692 .field("inert", &self.inert)
693 .field("tracks_placement", &self.placement_source.is_some())
694 .finish()
695 }
696}
697
698/// Maximum overlay nesting depth. Bounds runaway cascades: a rich-tooltip
699/// `[label](:key)` link loop (A→B→A) keeps minting fresh nested overlays
700/// (and dormant widgets) on each hop with no natural ceiling. A real
701/// menu-submenu or tooltip cascade never gets close to this — once a new
702/// overlay would exceed it, `OverlayManager::show*` drops the request
703/// instead of growing the stack without bound.
704pub(crate) const MAX_OVERLAY_NESTING_DEPTH: usize = 12;
705
706/// What an outside press owes the tree, decided on the arming
707/// [`PointerDown`](crate::event::WidgetEvent::PointerDown) and answered again
708/// on the release.
709///
710/// Two questions, asked on two different samples, which is why they are two
711/// fields rather than one bool: the `Down` needs to know whether to withhold
712/// itself from the widget beneath, and the `Up` needs to know whether anything
713/// is still waiting to close.
714#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
715pub struct DismissArm {
716 /// At least one overlay is armed to close when this press completes.
717 pub will_dismiss: bool,
718 /// The arming press must not be delivered to the widget under it.
719 ///
720 /// This is the whole point of arming. Today's press-time dismissal *falls
721 /// through*, so one tap closes a menu **and** actuates whatever the menu was
722 /// covering — a destructive button, a list row, a tab. With a mouse the user
723 /// sees the menu vanish under a cursor they aimed deliberately; with a
724 /// finger the menu is what they were looking at and the control beneath is
725 /// one they never saw.
726 pub suppress_beneath: bool,
727}
728
729/// The anchor of a click-opened overlay an outside press dismissed, and
730/// whether that overlay is a modal ([`OverlayPlacement::is_modal`]).
731///
732/// The dispatcher asks it whether the press would open the overlay again. A
733/// popover's anchor is its trigger; a modal's is whatever presented it, which
734/// may be the whole page.
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736pub(crate) struct ToggleAnchor {
737 pub(crate) anchor: WidgetId,
738 pub(crate) modal: bool,
739}
740
741/// An outside press that has not completed yet.
742struct ArmedDismiss {
743 pointer: PointerId,
744 /// The overlays the arming press selected. Re-checked at commit time
745 /// against the live stack, so an overlay that closed in the meantime is
746 /// simply absent rather than an error.
747 overlays: Vec<OverlayId>,
748 /// The click-opened overlays' anchors, carried so the commit can report
749 /// them exactly as the press-time path does.
750 anchors: Vec<ToggleAnchor>,
751}
752
753fn anchors_of(toggles: Vec<ToggleAnchor>) -> Vec<WidgetId> {
754 toggles.into_iter().map(|toggle| toggle.anchor).collect()
755}
756
757pub struct OverlayManager {
758 pub(crate) stack: Vec<ActiveOverlay>,
759 /// Outside presses awaiting their release, one per contact. Almost always
760 /// empty, and never longer than the number of live contacts.
761 arms: Vec<ArmedDismiss>,
762 next_id: u64,
763 /// Latest known sim-clock value, mirrored from
764 /// `WidgetTree::sim_clock` via [`Self::set_sim_clock`]. Read by
765 /// `dismiss` to stamp `dismissing_started_sim` in lockstep with
766 /// `dismissing_started_real`. Defaults to `Instant::now()` so
767 /// constructions outside a tree (tests of OverlayManager in
768 /// isolation) still produce sensible values.
769 sim_clock: Instant,
770 /// Monotonic counter bumped on every stack mutation (show /
771 /// dismiss). External observers — notably the inspector's Overlays
772 /// tab — bind to this signal to know when the visible overlay set
773 /// has changed without polling. Mirrors the
774 /// `ShortcutRegistry::version` pattern.
775 version: Signal<u64>,
776 /// Callbacks whose overlays have already left the stack but which have
777 /// not run yet, because they need an `EventContext` this type cannot
778 /// build. Drained by `WidgetTree::run_pending_dismiss_callbacks`, which
779 /// is called before the dismissed content is parked — so the ordering
780 /// `on_dismiss` always had (fires during dismissal, before focus returns
781 /// to the trigger) is unchanged.
782 pending_dismiss: Vec<(OverlayDismissCallback, DismissReason)>,
783}
784
785impl OverlayManager {
786 pub fn new() -> Self {
787 Self {
788 stack: Vec::new(),
789 arms: Vec::new(),
790 next_id: 1,
791 sim_clock: Instant::now(),
792 version: Signal::new(0),
793 pending_dismiss: Vec::new(),
794 }
795 }
796
797 /// Reactive handle bumped on every overlay mutation (show /
798 /// dismiss / cascade). Cheap clone. Same shape as
799 /// [`crate::shortcut::ShortcutRegistry::version`].
800 pub fn version(&self) -> &Signal<u64> {
801 &self.version
802 }
803
804 /// Bump the version signal. Called from every stack-mutating path.
805 fn bump_version(&self) {
806 self.version.set(self.version.get().wrapping_add(1));
807 }
808
809 /// Mirror the tree's sim_clock onto the manager so the fade
810 /// dismiss path can stamp the sim-time start in lockstep with
811 /// real time. Called by `WidgetTree` whenever `sim_clock` is
812 /// advanced (e.g. from `tick_animations` and `advance_time`).
813 pub(crate) fn set_sim_clock(&mut self, now_sim: Instant) {
814 self.sim_clock = now_sim;
815 }
816
817 /// Show a new overlay. Returns the OverlayId.
818 pub fn show(&mut self, request: OverlayRequest) -> OverlayId {
819 self.show_with_auto_dismiss(request, None, OverlayBand::Standard)
820 }
821
822 /// Show a new overlay in an explicit z-band.
823 ///
824 /// [`show`](Self::show) is this with [`OverlayBand::Standard`]. The other
825 /// band exists for the touch text affordances — see
826 /// [`text_affordance`] — which must sit
827 /// under every menu and survive the presses that drive them.
828 ///
829 /// A band below the top is inserted **mid-stack**, so
830 /// [`set_top_focus_restore`](Self::set_top_focus_restore) — which addresses
831 /// the top of the stack — does not describe it. That is correct rather than
832 /// a limitation: an affordance in this band never takes focus from the
833 /// editor it belongs to, so it has no focus to restore.
834 pub fn show_in_band(&mut self, request: OverlayRequest, band: OverlayBand) -> OverlayId {
835 self.show_with_auto_dismiss(request, None, band)
836 }
837
838 /// Show a new overlay that dismisses automatically after `duration`.
839 pub fn show_for(&mut self, request: OverlayRequest, duration: Duration) -> OverlayId {
840 self.show_with_auto_dismiss(request, Some(duration), OverlayBand::Standard)
841 }
842
843 fn show_with_auto_dismiss(
844 &mut self,
845 request: OverlayRequest,
846 auto_dismiss_after: Option<Duration>,
847 band: OverlayBand,
848 ) -> OverlayId {
849 let id = OverlayId::new(self.next_id);
850 self.next_id += 1;
851
852 // push, and return the (now unused) id so an id-keyed follow-up
853 // (`set_shown_at_sim`, `attach_fade`) safely no-ops on the absent
854 // overlay — `set_top_focus_restore` takes no id, so it still lands
855 // on whatever is actually topmost. This is reachable by degenerate-but-real
856 if self.ancestor_depth(request.parent_overlay) >= MAX_OVERLAY_NESTING_DEPTH {
857 return id;
858 }
859
860 let now = std::time::Instant::now();
861
862 let overlay = ActiveOverlay {
863 id,
864 content_id: request.content_id,
865 anchor: request.anchor,
866 placement: request.placement,
867 dismiss: request.dismiss,
868 layer: request.layer,
869 band,
870 parent_overlay: request.parent_overlay,
871 bounds: Rect::ZERO,
872 focus_restore: None,
873 command_source: request.command_source,
874 pointer_leave_started_real: None,
875 pointer_leave_started_sim: None,
876 safe_apex: None,
877 safe_apex_started_real: None,
878 safe_apex_started_sim: None,
879 auto_dismiss_after,
880 paused_remaining: None,
881 shown_at_real: now,
882 shown_at_sim: now,
883 on_dismiss: request.on_dismiss,
884 fade: None,
885 inert: request.inert,
886 placement_source: None,
887 };
888 // Sorted insert, not a push: an overlay goes above everything in a
889 // lower band and below everything in a higher one, so a selection
890 // handle raised while a menu is open still lands under the menu. Within
891 // a band the historical push order stands — a `Standard` overlay in a
892 // tree that raises no text affordance is appended, exactly as before.
893 let at = self
894 .stack
895 .iter()
896 .position(|existing| existing.band > band)
897 .unwrap_or(self.stack.len());
898 self.stack.insert(at, overlay);
899 self.bump_version();
900 id
901 }
902
903 /// Internal: install a framework-managed opacity signal as the
904 /// overlay's fade state. Called by `WidgetTree::show_overlay`
905 /// when [`OverlayRequest::fade_duration`] is `Some`. The
906 /// framework also applies the same signal to `content_id` via
907 /// `set_opacity` (so the rendering walker emits the per-frame
908 /// opacity scope) and kicks off the 0→1 fade-in tween.
909 pub(crate) fn attach_fade(&mut self, id: OverlayId, opacity: Signal<f32>, duration: Duration) {
910 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
911 overlay.fade = Some(OverlayFadeState {
912 opacity,
913 duration,
914 dismissing_started_real: None,
915 dismiss_reason: None,
916 dismissing_started_sim: None,
917 });
918 }
919 }
920
921 /// Public read-only accessor for the fade state. Returns the
922 /// duration if fade is configured, `None` otherwise. Used by
923 /// `WidgetTree::dismiss_overlay` to know whether to leave the
924 /// content active for the fade-out window.
925 pub fn fade_duration(&self, id: OverlayId) -> Option<Duration> {
926 self.stack
927 .iter()
928 .find(|o| o.id == id)
929 .and_then(|o| o.fade.as_ref().map(|f| f.duration))
930 }
931
932 pub fn next_auto_dismiss_deadline(&self) -> Option<std::time::Instant> {
933 self.stack
934 .iter()
935 .filter_map(|overlay| {
936 overlay
937 .auto_dismiss_after
938 .map(|delay| overlay.shown_at_real + delay)
939 })
940 .min()
941 }
942
943 /// Earliest instant at which a [`DismissBehavior::PointerLeave`] overlay
944 /// whose leave-grace is already running becomes due for dismissal.
945 ///
946 /// The counterpart of
947 /// [`next_auto_dismiss_deadline`](Self::next_auto_dismiss_deadline) for the
948 /// hover-opened overlays (tooltips, hover submenus). Without it the event
949 /// loop has no reason to wake between the pointer's last motion event and
950 /// the end of the grace window: `next_timer_deadline` would return `None`,
951 /// winit would sit in `ControlFlow::Wait`, and the overlay would stay on
952 /// screen until some unrelated input happened to redraw the window.
953 pub fn next_pointer_leave_deadline(&self) -> Option<std::time::Instant> {
954 self.stack
955 .iter()
956 .filter_map(|overlay| {
957 let DismissBehavior::PointerLeave { delay } = overlay.dismiss else {
958 return None;
959 };
960 Some(overlay.pointer_leave_started_real? + delay)
961 })
962 .min()
963 }
964
965 /// Pause the auto-dismiss timer for an overlay shown with
966 /// [`show_for`](Self::show_for). The remaining time
967 /// (`auto_dismiss_after - elapsed`) is stashed; subsequent calls
968 /// to [`next_auto_dismiss_deadline`](Self::next_auto_dismiss_deadline)
969 /// ignore this overlay until [`resume_auto_dismiss`](Self::resume_auto_dismiss)
970 /// is called. Idempotent — pausing an already-paused overlay is
971 /// a no-op (the originally-stashed remaining time is preserved).
972 ///
973 /// Used by `ToastHost` to implement hover-pause: when the user
974 /// is hovering over any live toast, all live toasts pause their
975 /// timers so the user can read each one without losing the
976 /// notification they're about to act on.
977 ///
978 /// No-op on overlays without `auto_dismiss_after` (persistent
979 /// overlays don't have a timer to pause) and on unknown ids.
980 pub fn pause_auto_dismiss(&mut self, id: OverlayId) {
981 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id)
982 && overlay.paused_remaining.is_none()
983 && let Some(delay) = overlay.auto_dismiss_after.take()
984 {
985 let elapsed = overlay.shown_at_real.elapsed();
986 overlay.paused_remaining = Some(delay.saturating_sub(elapsed));
987 }
988 }
989
990 /// Resume an auto-dismiss timer paused via
991 /// [`pause_auto_dismiss`](Self::pause_auto_dismiss). The stashed
992 /// remaining time becomes the new `auto_dismiss_after`, and
993 /// `shown_at_real` / `shown_at_sim` are reset to now so the
994 /// deadline computation works correctly. Idempotent — resuming
995 /// an un-paused overlay is a no-op.
996 pub fn resume_auto_dismiss(&mut self, id: OverlayId) {
997 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id)
998 && let Some(remaining) = overlay.paused_remaining.take()
999 {
1000 overlay.auto_dismiss_after = Some(remaining);
1001 let now = std::time::Instant::now();
1002 overlay.shown_at_real = now;
1003 overlay.shown_at_sim = self.sim_clock;
1004 }
1005 }
1006
1007 /// Whether the auto-dismiss timer for an overlay is currently paused.
1008 /// `false` for overlays without `auto_dismiss_after`, unknown ids,
1009 /// and overlays whose timer is running.
1010 pub fn is_auto_dismiss_paused(&self, id: OverlayId) -> bool {
1011 self.stack
1012 .iter()
1013 .find(|o| o.id == id)
1014 .is_some_and(|o| o.paused_remaining.is_some())
1015 }
1016
1017 pub(crate) fn set_shown_at_sim(&mut self, id: OverlayId, shown_at_sim: std::time::Instant) {
1018 if let Some(overlay) = self.stack.iter_mut().find(|overlay| overlay.id == id) {
1019 overlay.shown_at_sim = shown_at_sim;
1020 }
1021 }
1022
1023 /// Count the ancestor chain length for an overlay whose parent is
1024 /// `parent` — i.e. the nesting depth the *new* overlay would have.
1025 /// A root (`parent == None`) is depth 0; a child of a root is depth
1026 /// 1; and so on. The walk is bounded by the stack length so a
1027 /// malformed parent cycle can't loop forever.
1028 fn ancestor_depth(&self, parent: Option<OverlayId>) -> usize {
1029 let mut depth = 0;
1030 let mut current = parent;
1031 while let Some(p) = current {
1032 depth += 1;
1033 if depth > self.stack.len() {
1034 // Defensive: malformed parent cycle. Report a depth that
1035 // trips the guard rather than spinning.
1036 break;
1037 }
1038 current = self
1039 .stack
1040 .iter()
1041 .find(|overlay| overlay.id == p)
1042 .and_then(|overlay| overlay.parent_overlay);
1043 }
1044 depth
1045 }
1046
1047 pub(crate) fn is_descendant_of(&self, child: OverlayId, ancestor: OverlayId) -> bool {
1048 let mut current = self
1049 .stack
1050 .iter()
1051 .find(|overlay| overlay.id == child)
1052 .and_then(|overlay| overlay.parent_overlay);
1053
1054 while let Some(parent) = current {
1055 if parent == ancestor {
1056 return true;
1057 }
1058 current = self
1059 .stack
1060 .iter()
1061 .find(|overlay| overlay.id == parent)
1062 .and_then(|overlay| overlay.parent_overlay);
1063 }
1064
1065 false
1066 }
1067
1068 pub(crate) fn overlay(&self, id: OverlayId) -> Option<&ActiveOverlay> {
1069 self.stack.iter().find(|overlay| overlay.id == id)
1070 }
1071
1072 /// Public accessor for an overlay's currently-laid-out screen
1073 /// rect. Returns `None` for unknown ids and for overlays that
1074 /// have not yet been through a layout pass (`bounds == Rect::ZERO`
1075 /// in that case, but we still hand it back — callers should not
1076 /// trust a zero-sized rect for hit-test geometry).
1077 ///
1078 /// Used by [`MenuList`](../../teksilo_widgets/menu_list/struct.MenuList.html)'s
1079 /// safe-triangle submenu hover gate, which needs the open
1080 /// submenu's near-edge to test whether the cursor trajectory is
1081 /// still headed toward the submenu.
1082 pub fn bounds_for(&self, id: OverlayId) -> Option<Rect> {
1083 self.overlay(id).map(|o| o.bounds)
1084 }
1085
1086 pub(crate) fn topmost_modal(&self) -> Option<&ActiveOverlay> {
1087 self.stack
1088 .iter()
1089 .rev()
1090 .find(|overlay| overlay.placement.is_modal())
1091 }
1092
1093 /// Whether `overlay` is a modal's scrim: a full-viewport layer whose
1094 /// parent is a modal, the dim the page sits under while it is open. The
1095 /// window's own chrome stays live above it.
1096 pub(crate) fn is_modal_scrim(&self, overlay: &ActiveOverlay) -> bool {
1097 matches!(overlay.placement, OverlayPlacement::FullViewport)
1098 && overlay
1099 .parent_overlay
1100 .and_then(|parent| self.overlay(parent))
1101 .is_some_and(|parent| parent.placement.is_modal())
1102 }
1103
1104 /// Whether a modal overlay is open and not on its way out.
1105 pub(crate) fn has_open_modal(&self) -> bool {
1106 self.stack
1107 .iter()
1108 .any(|overlay| overlay.placement.is_modal() && !overlay.is_dismissing())
1109 }
1110
1111 /// Dismiss an overlay and all its children (cascade), returning the
1112 /// dismissed content widget IDs and the overlay's focus_restore target.
1113 pub fn dismiss_with_focus_restore(
1114 &mut self,
1115 id: OverlayId,
1116 ) -> (Vec<WidgetId>, Option<WidgetId>) {
1117 self.dismiss_with_focus_restore_because(id, DismissReason::Programmatic)
1118 }
1119
1120 /// [`dismiss_with_focus_restore`](Self::dismiss_with_focus_restore),
1121 /// saying why.
1122 pub fn dismiss_with_focus_restore_because(
1123 &mut self,
1124 id: OverlayId,
1125 reason: DismissReason,
1126 ) -> (Vec<WidgetId>, Option<WidgetId>) {
1127 let focus_restore = self
1128 .stack
1129 .iter()
1130 .find(|overlay| overlay.id == id)
1131 .and_then(|overlay| overlay.focus_restore);
1132 let dismissed = self.dismiss_because(id, reason);
1133 (dismissed, focus_restore)
1134 }
1135
1136 /// Dismiss all descendant overlays of `parent`, optionally preserving the
1137 /// subtree rooted at `preserve`.
1138 pub fn dismiss_descendants_of(
1139 &mut self,
1140 parent: OverlayId,
1141 preserve: Option<OverlayId>,
1142 ) -> (Vec<WidgetId>, Option<WidgetId>) {
1143 let mut to_dismiss = Vec::new();
1144
1145 for overlay in &self.stack {
1146 if !self.is_descendant_of(overlay.id, parent) {
1147 continue;
1148 }
1149 if preserve
1150 .is_some_and(|keep| overlay.id == keep || self.is_descendant_of(overlay.id, keep))
1151 {
1152 continue;
1153 }
1154 to_dismiss.push(overlay.id);
1155 }
1156
1157 if to_dismiss.is_empty() {
1158 return (Vec::new(), None);
1159 }
1160
1161 let focus_restore = self
1162 .stack
1163 .iter()
1164 .rev()
1165 .find(|overlay| to_dismiss.contains(&overlay.id))
1166 .and_then(|overlay| overlay.focus_restore);
1167
1168 let dismissed_content: Vec<WidgetId> = self
1169 .stack
1170 .iter()
1171 .filter(|overlay| to_dismiss.contains(&overlay.id))
1172 .map(|overlay| overlay.content_id)
1173 .collect();
1174 let callbacks: Vec<OverlayDismissCallback> = self
1175 .stack
1176 .iter()
1177 .filter(|overlay| to_dismiss.contains(&overlay.id))
1178 .filter_map(|overlay| overlay.on_dismiss.clone())
1179 .collect();
1180 self.stack
1181 .retain(|overlay| !to_dismiss.contains(&overlay.id));
1182 // Everything here is, by construction, a descendant going away with
1183 // its parent.
1184 self.pending_dismiss
1185 .extend(callbacks.into_iter().map(|cb| (cb, DismissReason::Cascade)));
1186
1187 (dismissed_content, focus_restore)
1188 }
1189
1190 /// Update the placement of an existing overlay.
1191 pub fn update_placement(&mut self, id: OverlayId, placement: OverlayPlacement) {
1192 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
1193 overlay.placement = placement;
1194 }
1195 }
1196
1197 /// Re-derive an existing overlay's placement from its anchor on every
1198 /// positioning pass, for as long as it is up.
1199 pub(crate) fn set_placement_source(&mut self, id: OverlayId, source: OverlayPlacementSource) {
1200 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
1201 overlay.placement_source = Some(source);
1202 }
1203 }
1204
1205 /// Update the parent-overlay link of an existing overlay. Used by the
1206 /// modal-presentation pipeline to retroactively attach the dialog
1207 /// scrim (pushed first, below the modal in the stack) to the modal
1208 /// (pushed second) so that dismissing the modal cascades through
1209 /// `dismiss_immediate` and also dismisses the scrim.
1210 pub fn set_parent_overlay(&mut self, id: OverlayId, parent: Option<OverlayId>) {
1211 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
1212 overlay.parent_overlay = parent;
1213 }
1214 }
1215
1216 /// Dismiss an overlay and all its children (cascade).
1217 /// Returns the content widget IDs of all dismissed overlays.
1218 ///
1219 /// owned opacity signal and stamps `dismissing_started_real` /
1220 /// `dismissing_started_sim`, returning an
1221 /// Cascaded descendants vanish with the leaf's fade-out (they're
1222 /// typically submenus the user dismissed *via* the leaf, and a
1223 /// per-descendant tween would compete with the leaf's).
1224 pub fn dismiss(&mut self, id: OverlayId) -> Vec<WidgetId> {
1225 self.dismiss_because(id, DismissReason::Programmatic)
1226 }
1227
1228 /// [`dismiss`](Self::dismiss), saying why — which is what the overlay's
1229 /// `on_dismiss` is handed.
1230 pub fn dismiss_because(&mut self, id: OverlayId, reason: DismissReason) -> Vec<WidgetId> {
1231 // Fade gate: if the target overlay has fade and isn't
1232 // already fading out, kick off the fade-out and defer the
1233 // entire cascade. Stamps both real and sim start times in
1234 // lockstep — the sim time uses the manager's mirrored
1235 // `sim_clock`, kept in sync by `WidgetTree::set_sim_clock`.
1236 let sim_now = self.sim_clock;
1237 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id)
1238 && let Some(fade) = &mut overlay.fade
1239 && fade.dismissing_started_real.is_none()
1240 {
1241 // Animate opacity 1 → 0 over `duration`. Uses the same
1242 // try_animate_with_options path the rest of the
1243 // animation system uses; the scheduler picks it up next
1244 // frame and ticks the signal, dirty-marking the
1245 // content's opacity binding for repaint.
1246 let _ = fade
1247 .opacity
1248 .try_animate_with_options(crate::animation::AnimationRequest {
1249 target: 0.0,
1250 duration: fade.duration,
1251 easing: teksilo_tokens::Easing::EaseOut,
1252 frame_interval: None,
1253 looping: false,
1254 epsilon: 0.0,
1255 max_duration: None,
1256 });
1257 let now_real = Instant::now();
1258 fade.dismissing_started_real = Some(now_real);
1259 fade.dismissing_started_sim = Some(sim_now);
1260 fade.dismiss_reason = Some(reason);
1261 return Vec::new();
1262 }
1263 self.dismiss_immediate(id, reason)
1264 }
1265
1266 /// Internal: same shape as the original `dismiss`, but bypasses
1267 /// the fade gate. Used both by `dismiss` (no fade configured /
1268 /// already fading out) and by `process_pending_fade_dismissals`
1269 /// when a fade-out tween has completed. Also used by the orphaned-
1270 /// overlay GC (`WidgetTree::gc_orphaned_overlays`), where fading is
1271 /// impossible because the content widget is already destroyed.
1272 pub(crate) fn dismiss_immediate(
1273 &mut self,
1274 id: OverlayId,
1275 reason: DismissReason,
1276 ) -> Vec<WidgetId> {
1277 // Collect IDs to dismiss: the target + all descendants
1278 let mut to_dismiss = vec![id];
1279 let mut i = 0;
1280 while i < to_dismiss.len() {
1281 let parent = to_dismiss[i];
1282 for overlay in &self.stack {
1283 if overlay.parent_overlay == Some(parent) && !to_dismiss.contains(&overlay.id) {
1284 to_dismiss.push(overlay.id);
1285 }
1286 }
1287 i += 1;
1288 }
1289 let dismissed_content: Vec<WidgetId> = self
1290 .stack
1291 .iter()
1292 .filter(|o| to_dismiss.contains(&o.id))
1293 .map(|o| o.content_id)
1294 .collect();
1295 // Collect dismiss callbacks (via Rc::clone) before retain
1296 // so we can invoke them AFTER the borrow is released.
1297 // Callbacks may do anything, including touching the arena,
1298 // so running them mid-retain would risk re-entrancy.
1299 let callbacks: Vec<OverlayDismissCallback> = self
1300 .stack
1301 .iter()
1302 .filter(|o| to_dismiss.contains(&o.id))
1303 .filter_map(|o| o.on_dismiss.clone())
1304 .collect();
1305 self.stack.retain(|o| !to_dismiss.contains(&o.id));
1306 if !to_dismiss.is_empty() {
1307 self.bump_version();
1308 }
1309 // The overlay that was actually asked to go gets the real reason; the
1310 // descendants it drags with it get `Cascade`, which is the only thing
1311 // that is true of them.
1312 let mut callbacks = callbacks.into_iter();
1313 if let Some(first) = callbacks.next() {
1314 self.pending_dismiss.push((first, reason));
1315 }
1316 self.pending_dismiss
1317 .extend(callbacks.map(|cb| (cb, DismissReason::Cascade)));
1318 dismissed_content
1319 }
1320
1321 /// Drain overlays whose real-clock fade-out tween has completed.
1322 /// Call from the live layout pass; the framework dormants the
1323 /// returned content widget IDs and restores focus where
1324 /// appropriate. Each entry is
1325 /// `(overlay_id, dismissed_content_ids, focus_restore)` so the
1326 /// layout pass can run the same dormant-and-restore-focus flow
1327 /// it uses for
1328 /// [`dismiss_with_focus_restore`](Self::dismiss_with_focus_restore).
1329 pub fn process_pending_fade_dismissals(
1330 &mut self,
1331 now: Instant,
1332 ) -> Vec<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
1333 self.process_pending_fade_dismissals_with(|fade| {
1334 let started = fade.dismissing_started_real?;
1335 Some(now.saturating_duration_since(started) >= fade.duration)
1336 })
1337 }
1338
1339 /// Sim-clock variant for deterministic headless tests. Same
1340 /// shape as [`process_pending_fade_dismissals`](Self::process_pending_fade_dismissals)
1341 /// but reads `dismissing_started_sim`.
1342 pub fn process_pending_fade_dismissals_sim(
1343 &mut self,
1344 now_sim: Instant,
1345 ) -> Vec<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
1346 self.process_pending_fade_dismissals_with(|fade| {
1347 let started = fade.dismissing_started_sim?;
1348 Some(now_sim.saturating_duration_since(started) >= fade.duration)
1349 })
1350 }
1351
1352 fn process_pending_fade_dismissals_with(
1353 &mut self,
1354 mut elapsed_done: impl FnMut(&OverlayFadeState) -> Option<bool>,
1355 ) -> Vec<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
1356 let ready: Vec<(OverlayId, Option<WidgetId>, Option<DismissReason>)> = self
1357 .stack
1358 .iter()
1359 .filter_map(|o| {
1360 let fade = o.fade.as_ref()?;
1361 if elapsed_done(fade)? {
1362 Some((o.id, o.focus_restore, fade.dismiss_reason))
1363 } else {
1364 None
1365 }
1366 })
1367 .collect();
1368 ready
1369 .into_iter()
1370 .map(|(id, focus_restore, reason)| {
1371 let dismissed =
1372 self.dismiss_immediate(id, reason.unwrap_or(DismissReason::Programmatic));
1373 (id, dismissed, focus_restore)
1374 })
1375 .collect()
1376 }
1377
1378 /// Earliest real-clock deadline at which a fading-out overlay
1379 /// wants to finish its dismissal. Used by the event-loop wakeup
1380 /// logic to schedule the next frame.
1381 pub fn next_fade_dismiss_deadline(&self) -> Option<Instant> {
1382 self.stack
1383 .iter()
1384 .filter_map(|o| {
1385 let fade = o.fade.as_ref()?;
1386 let started = fade.dismissing_started_real?;
1387 Some(started + fade.duration)
1388 })
1389 .min()
1390 }
1391
1392 /// Dismiss the topmost overlay unconditionally (e.g., ArrowLeft for submenu cascading).
1393 /// Returns the overlay ID, content widget IDs, and focus_restore target.
1394 pub fn dismiss_top(&mut self) -> Option<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
1395 self.dismiss_top_because(DismissReason::Programmatic)
1396 }
1397
1398 /// [`dismiss_top`](Self::dismiss_top), saying why.
1399 pub fn dismiss_top_because(
1400 &mut self,
1401 reason: DismissReason,
1402 ) -> Option<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
1403 if let Some(overlay) = self.stack.last() {
1404 let id = overlay.id;
1405 let focus_restore = overlay.focus_restore;
1406 let content_ids = self.dismiss_because(id, reason);
1407 Some((id, content_ids, focus_restore))
1408 } else {
1409 None
1410 }
1411 }
1412
1413 /// Try to dismiss an overlay on Escape, respecting `DismissBehavior`.
1414 ///
1415 /// Scans the stack top-down for the first overlay that Escape may close,
1416 /// rather than consulting only `stack.last()`. Two reasons:
1417 ///
1418 /// - A hover-opened overlay (`PointerLeave` — every shown tooltip) is
1419 /// Escape-dismissible. WCAG 2.2 SC 1.4.13(a) requires content shown on
1420 /// hover to be dismissible *without moving the pointer*, and Escape is
1421 /// that mechanism; previously no key could close a plain tooltip.
1422 /// - A tooltip lives on the same stack as whatever it is anchored inside.
1423 /// Hovering a menu item long enough to raise its tooltip put a
1424 /// non-Escape overlay on top, so Escape silently did nothing at all
1425 /// until the tooltip's own 100 ms leave-grace expired — the keystroke
1426 /// was swallowed, not forwarded to the menu underneath.
1427 ///
1428 /// `Manual` overlays still block the scan: they are modal-ish by
1429 /// construction and own the keystroke. An
1430 /// [inert](OverlayRequest::inert) one owns nothing and is stepped over;
1431 /// the tree retires the inert overlays Escape may close beforehand,
1432 /// without spending the key.
1433 pub fn try_dismiss_top_on_escape(
1434 &mut self,
1435 ) -> Option<(OverlayId, Vec<WidgetId>, Option<WidgetId>)> {
1436 let target = self
1437 .stack
1438 .iter()
1439 .rev()
1440 // An overlay already fading out stays on the stack until its tween
1441 // finishes, but it is on its way out and no longer owns the
1442 // keystroke — targeting it again would spend an Escape on a corpse
1443 // and leave whatever is underneath unreachable.
1444 .filter(|o| !o.is_dismissing() && !o.inert)
1445 .find_map(|o| match o.dismiss {
1446 DismissBehavior::EscapeKey
1447 | DismissBehavior::EscapeOrClickOutside
1448 | DismissBehavior::PointerLeave { .. } => Some(Some(o.id)),
1449 // Opaque to Escape and to everything under it.
1450 DismissBehavior::Manual => Some(None),
1451 DismissBehavior::ClickOutside => None,
1452 })??;
1453 let focus_restore = self
1454 .stack
1455 .iter()
1456 .find(|o| o.id == target)
1457 .and_then(|o| o.focus_restore);
1458 let content_ids = self.dismiss_because(target, DismissReason::Escape);
1459 Some((target, content_ids, focus_restore))
1460 }
1461
1462 /// Dismiss every [inert](ActiveOverlay::inert) overlay Escape may close,
1463 /// returning the content ids that went.
1464 ///
1465 /// The plain tooltip's rule, for overlays that are not tooltip entries: an
1466 /// overlay nothing can be done in is never what an Escape is *for*, so it
1467 /// goes and the key carries on to the field, menu or dialog the user meant
1468 /// it for. No focus is restored: nothing in such an overlay took any.
1469 pub(crate) fn dismiss_inert_on_escape(&mut self) -> Vec<WidgetId> {
1470 let targets: Vec<OverlayId> = self
1471 .stack
1472 .iter()
1473 .filter(|o| o.inert && !o.is_dismissing())
1474 .filter(|o| {
1475 matches!(
1476 o.dismiss,
1477 DismissBehavior::EscapeKey
1478 | DismissBehavior::EscapeOrClickOutside
1479 | DismissBehavior::PointerLeave { .. }
1480 )
1481 })
1482 .map(|o| o.id)
1483 .collect();
1484 targets
1485 .into_iter()
1486 .flat_map(|id| self.dismiss_because(id, DismissReason::Escape))
1487 .collect()
1488 }
1489
1490 /// Set the focus_restore target for the topmost overlay.
1491 ///
1492 /// Does nothing when that overlay is [inert](OverlayRequest::inert): it
1493 /// takes no focus, so it has none to give back, and a target recorded
1494 /// here would hand focus, when it went, to whatever held it when it
1495 /// appeared, however long ago and wherever focus has been since. Every
1496 /// show path records its restore target through this, so the rule is
1497 /// kept here rather than at each of them.
1498 pub fn set_top_focus_restore(&mut self, focus_restore: WidgetId) {
1499 if let Some(overlay) = self.stack.last_mut()
1500 && !overlay.inert
1501 {
1502 overlay.focus_restore = Some(focus_restore);
1503 }
1504 }
1505
1506 /// Dismiss all overlays.
1507 /// Returns the content widget IDs of all dismissed overlays.
1508 /// Fires every dismissed overlay's `on_dismiss` callback after the
1509 /// stack is cleared — same contract as [`dismiss`](Self::dismiss),
1510 /// so wrappers like [`PopoverButton`](crate::widget::EventContext)'s
1511 /// `popover_open` signal flip back to `false` when a `MenuItem`
1512 /// fires `ctx.dismiss_all_overlays()`. Without this, the trigger's
1513 /// next click would observe stale-true and silently retoggle
1514 /// instead of reopening the menu.
1515 pub fn dismiss_all(&mut self) -> Vec<WidgetId> {
1516 self.dismiss_all_because(DismissReason::Programmatic)
1517 }
1518
1519 /// [`dismiss_all`](Self::dismiss_all), saying why.
1520 pub fn dismiss_all_because(&mut self, reason: DismissReason) -> Vec<WidgetId> {
1521 let content_ids: Vec<WidgetId> = self.stack.iter().map(|o| o.content_id).collect();
1522 if content_ids.is_empty() {
1523 return content_ids;
1524 }
1525 // Collect dismiss callbacks (via Rc::clone) before clear so we
1526 // can invoke them AFTER the borrow is released. Callbacks may
1527 // do anything, including touching the arena, so running them
1528 // mid-clear would risk re-entrancy. Mirrors the pattern in
1529 // [`dismiss_immediate`](Self::dismiss_immediate).
1530 let callbacks: Vec<OverlayDismissCallback> = self
1531 .stack
1532 .iter()
1533 .filter_map(|o| o.on_dismiss.clone())
1534 .collect();
1535 self.stack.clear();
1536 self.bump_version();
1537 self.pending_dismiss
1538 .extend(callbacks.into_iter().map(|cb| (cb, reason)));
1539 content_ids
1540 }
1541
1542 /// Dismiss every overlay whose content is **not** in `keep`, parking each
1543 /// dismissed overlay's `on_dismiss` for the tree to run. Used when opening a
1544 /// context menu: any
1545 pub fn dismiss_except(&mut self, keep: &std::collections::HashSet<WidgetId>) -> Vec<WidgetId> {
1546 self.dismiss_except_because(keep, DismissReason::Programmatic)
1547 }
1548
1549 /// [`dismiss_except`](Self::dismiss_except), saying why.
1550 pub fn dismiss_except_because(
1551 &mut self,
1552 keep: &std::collections::HashSet<WidgetId>,
1553 reason: DismissReason,
1554 ) -> Vec<WidgetId> {
1555 let dismissed: Vec<WidgetId> = self
1556 .stack
1557 .iter()
1558 .filter(|o| !keep.contains(&o.content_id))
1559 .map(|o| o.content_id)
1560 .collect();
1561 if dismissed.is_empty() {
1562 return dismissed;
1563 }
1564 // Clone callbacks before mutating the stack, then run them after the
1565 // borrow is released (they may touch the arena) — mirrors `dismiss_all`.
1566 let callbacks: Vec<OverlayDismissCallback> = self
1567 .stack
1568 .iter()
1569 .filter(|o| !keep.contains(&o.content_id))
1570 .filter_map(|o| o.on_dismiss.clone())
1571 .collect();
1572 self.stack.retain(|o| keep.contains(&o.content_id));
1573 self.bump_version();
1574 self.pending_dismiss
1575 .extend(callbacks.into_iter().map(|cb| (cb, reason)));
1576 dismissed
1577 }
1578
1579 /// Take the dismissal callbacks parked by the dismissal methods.
1580 ///
1581 /// The manager removes an overlay from the stack and collects its
1582 /// `on_dismiss` before mutating (the re-entrancy discipline the collect
1583 /// loops already had); it cannot *run* it, because the callback now needs
1584 /// an `EventContext` and this type has no tree. So it parks it here and
1585 /// `WidgetTree::run_pending_dismiss_callbacks` drains it.
1586 ///
1587 /// Draining is idempotent: a second call returns nothing.
1588 pub(crate) fn take_pending_dismiss(&mut self) -> Vec<(OverlayDismissCallback, DismissReason)> {
1589 std::mem::take(&mut self.pending_dismiss)
1590 }
1591
1592 /// Whether there are any active overlays.
1593 pub fn is_empty(&self) -> bool {
1594 self.stack.is_empty()
1595 }
1596
1597 /// Number of active overlays.
1598 pub fn len(&self) -> usize {
1599 self.stack.len()
1600 }
1601
1602 /// Get all active overlay content widget IDs (for rendering).
1603 pub fn active_content_ids(&self) -> Vec<WidgetId> {
1604 self.stack.iter().map(|o| o.content_id).collect()
1605 }
1606
1607 /// Get all active overlay IDs (for testing/querying). Excludes
1608 /// overlays currently fading out — once a dismiss has been
1609 /// requested the overlay is conceptually gone (the visible
1610 /// opacity tween is on the way to 0 and the deferred removal
1611 /// will fire on the next layout pass after the fade-out
1612 /// completes), so user code asking "is this overlay still up?"
1613 /// gets the expected answer.
1614 pub fn active_ids(&self) -> Vec<OverlayId> {
1615 self.stack
1616 .iter()
1617 .filter(|o| {
1618 o.fade
1619 .as_ref()
1620 .is_none_or(|f| f.dismissing_started_real.is_none())
1621 })
1622 .map(|o| o.id)
1623 .collect()
1624 }
1625
1626 /// Get the anchor widget for an overlay.
1627 pub fn anchor_for(&self, id: OverlayId) -> Option<WidgetId> {
1628 self.stack.iter().find(|o| o.id == id).map(|o| o.anchor)
1629 }
1630
1631 /// Screen rects of every overlay that is currently *interactive* —
1632 /// open, not yet fading out and not [inert](OverlayRequest::inert), the
1633 /// same predicate [`hit_test`](Self::hit_test) uses to route pointer
1634 /// events.
1635 /// Zero-area entries are skipped: an overlay shown this frame has
1636 /// not been through its first layout pass yet (`bounds ==
1637 /// Rect::ZERO`), and a degenerate rect must not be mistaken for a
1638 /// hit at the origin.
1639 ///
1640 /// Consumed by the paint pass, which hands the list to
1641 /// [`Widget::after_paint`](crate::widget::Widget::after_paint) via
1642 /// `WidgetTreeView` so chrome aggregators can subtract floating
1643 /// content from the regions they publish — `TitleBar` carves these
1644 /// out of the OS caption so an overlay above the title bar (the
1645 /// hamburger `MenuBar`'s revealed bar, a tall modal) stays
1646 /// clickable on Windows instead of dragging the window.
1647 pub fn interactive_rects(&self) -> Vec<Rect> {
1648 self.interactive()
1649 .map(|o| o.bounds)
1650 .filter(|r| r.width > 0.0 && r.height > 0.0)
1651 .collect()
1652 }
1653
1654 /// The overlays open and not fading out: what
1655 /// [`interactive_rects`](Self::interactive_rects) measures.
1656 pub(crate) fn interactive(&self) -> impl Iterator<Item = &ActiveOverlay> {
1657 self.stack.iter().filter(|o| {
1658 !o.inert
1659 && o.fade
1660 .as_ref()
1661 .is_none_or(|f| f.dismissing_started_real.is_none())
1662 })
1663 }
1664
1665 /// Get the topmost overlay.
1666 #[allow(dead_code)] // used for overlay z-ordering and focus management
1667 pub(crate) fn topmost(&self) -> Option<&ActiveOverlay> {
1668 self.stack.last()
1669 }
1670
1671 /// Check if a point hits any overlay (topmost first).
1672 /// Returns the overlay ID if hit, None if the point is outside all overlays.
1673 ///
1674 /// Overlays whose fade-out has begun are skipped — the same predicate
1675 /// [`active_ids`](Self::active_ids) uses. A dismissed-but-still-fading
1676 /// overlay lingers in the stack until
1677 /// [`process_pending_fade_dismissals`](Self::process_pending_fade_dismissals)
1678 /// removes it; treating it as hittable would route clicks into the
1679 /// vanishing content (and suppress outside-click dismissal of the
1680 /// overlays beneath it) for the whole fade duration.
1681 ///
1682 /// An [inert](OverlayRequest::inert) overlay is skipped for the same
1683 /// reason, permanently: nothing in it takes the point, so the point is
1684 /// asked of whatever is beneath it, the next overlay down included.
1685 pub fn hit_test(&self, point: Point) -> Option<OverlayId> {
1686 for overlay in self.stack.iter().rev() {
1687 let fading_out = overlay
1688 .fade
1689 .as_ref()
1690 .is_some_and(|f| f.dismissing_started_real.is_some());
1691 if !fading_out && !overlay.inert && overlay.bounds.contains(point) {
1692 return Some(overlay.id);
1693 }
1694 }
1695 None
1696 }
1697
1698 /// Handle a click-outside event: if the click is outside all overlays
1699 /// with ClickOutside dismiss behavior, dismiss them.
1700 /// Returns the content widget IDs of dismissed overlays (empty if none)
1701 /// and the focus-restore target — the widget that was focused before
1702 /// the *bottommost* dismissed overlay opened. Topmost overlays'
1703 /// `focus_restore` would point inside an overlay that's also being
1704 /// dismissed in the same pass, which would leave focus on a
1705 /// dormant widget; the bottommost target represents focus before
1706 /// any of the dismissed overlays opened. Aligns the click-outside
1707 /// path with the Esc / ArrowLeft-cascade paths, both of which
1708 /// already restore focus from the dismissed overlay.
1709 ///
1710 /// The third return value lists the anchor widgets of the dismissed
1711 /// *click-opened* overlays (`ClickOutside` / `EscapeOrClickOutside`).
1712 /// The dispatcher consumes a primary press that lands on one of these
1713 /// anchors so the trigger merely closes its overlay rather than
1714 /// reopening it; every other dismiss-press falls through to the widget
1715 /// under the cursor (so one click both dismisses the overlay and
1716 /// activates the control beneath). Hover-opened (`PointerLeave`)
1717 /// overlays contribute no anchor — a press on their anchor passes
1718 /// through, e.g. clicking a button that still has its tooltip up.
1719 pub fn handle_click_outside(
1720 &mut self,
1721 point: Point,
1722 ) -> (Vec<WidgetId>, Option<WidgetId>, Vec<WidgetId>) {
1723 self.dismiss_outside_press(point, &[])
1724 }
1725
1726 /// [`handle_click_outside`](Self::handle_click_outside) with the points at
1727 /// which *other* contacts are holding a live press.
1728 ///
1729 /// A press is only "outside" relative to the overlays nobody else is
1730 /// working in. A second finger landing on the page while the first is
1731 /// dragging a menu's scrollbar is not a dismissal gesture; it is the second
1732 /// finger of a two-finger interaction, and closing the menu under the first
1733 /// one takes the interaction away mid-flight. Each busy point raises the
1734 /// floor of the layered rule to the overlay it is inside, so overlays at or
1735 /// below any busy contact survive and everything above still closes.
1736 ///
1737 /// An empty `busy` is the historical behaviour exactly, which is what a
1738 /// mouse-only tree always passes.
1739 pub fn dismiss_outside_press(
1740 &mut self,
1741 point: Point,
1742 busy: &[Point],
1743 ) -> (Vec<WidgetId>, Option<WidgetId>, Vec<WidgetId>) {
1744 let (dismissed, focus_restore, toggles) = self.dismiss_outside_press_toggles(point, busy);
1745 (dismissed, focus_restore, anchors_of(toggles))
1746 }
1747
1748 /// [`dismiss_outside_press`](Self::dismiss_outside_press), with each
1749 /// anchor saying whether its overlay is a modal.
1750 pub(crate) fn dismiss_outside_press_toggles(
1751 &mut self,
1752 point: Point,
1753 busy: &[Point],
1754 ) -> (Vec<WidgetId>, Option<WidgetId>, Vec<ToggleAnchor>) {
1755 let (to_dismiss, toggle_anchors) = self.outside_press_targets(point, busy);
1756 self.apply_outside_press(to_dismiss, toggle_anchors)
1757 }
1758
1759 /// The overlays an outside press at `point` selects, and the click-opened
1760 /// ones' anchors. Pure: nothing is dismissed.
1761 fn outside_press_targets(
1762 &self,
1763 point: Point,
1764 busy: &[Point],
1765 ) -> (Vec<OverlayId>, Vec<ToggleAnchor>) {
1766 if self.stack.is_empty() {
1767 return (Vec::new(), Vec::new());
1768 }
1769
1770 // Dismissal is *layered*, not stack-wide. A press that lands inside
1771 // overlay `k` is still *outside* every overlay stacked above `k`, so
1772 // those upper overlays with a click-outside policy must close — e.g. a
1773 // sticky tooltip (or a combo dropdown) floating above a modal is
1774 // dismissed when the user clicks elsewhere in the modal. Overlays at
1775 // or below `k` keep their content: the press landed within the stack,
1776 // not outside it.
1777 //
1778 // `hit_index` is the topmost non-fading overlay containing the point,
1779 // or `None` for a press on the bare background (then nothing is
1780 // "below" the press and every dismissable overlay closes — the
1781 // classic outside-click). This replaces an earlier stack-wide
1782 // short-circuit that returned as soon as the press hit *any* overlay:
1783 // once a modal — or its full-viewport scrim — was open, that guard
1784 // made *no* click-outside overlay dismissable at all.
1785 // An inert overlay is not somewhere a press can land "inside": the
1786 // press belongs to what is beneath it, so an overlay under it is
1787 // outside the press exactly when it would be with the inert one gone.
1788 let index_at = |p: Point| {
1789 self.stack.iter().enumerate().rev().find_map(|(i, o)| {
1790 let fading_out = o
1791 .fade
1792 .as_ref()
1793 .is_some_and(|f| f.dismissing_started_real.is_some());
1794 (!fading_out && !o.inert && o.bounds.contains(p)).then_some(i)
1795 })
1796 };
1797 // The press's own floor, raised by every contact already working inside
1798 // an overlay — see `dismiss_outside_press`.
1799 let hit_index = std::iter::once(point)
1800 .chain(busy.iter().copied())
1801 .filter_map(index_at)
1802 .max();
1803
1804 // Collect the overlays this outside-click should close, and — for
1805 // the *click-opened* ones — their anchor widgets. The anchors let
1806 // the dispatcher decide whether the same press may fall through to
1807 // the widget beneath: a press on a click-opened overlay's own
1808 // anchor is consumed, since the anchor's tap handler would
1809 // otherwise reopen what this press just dismissed. Hover-opened
1810 // overlays (`PointerLeave`) are not click toggles, so their
1811 // anchors are omitted and a press there falls through.
1812 let mut to_dismiss: Vec<OverlayId> = Vec::new();
1813 let mut toggle_anchors: Vec<ToggleAnchor> = Vec::new();
1814 for (i, o) in self.stack.iter().enumerate() {
1815 // Skip the hit overlay and everything beneath it — the press
1816 // landed inside them (or was covered by them), so they survive.
1817 if hit_index.is_some_and(|k| i <= k) {
1818 continue;
1819 }
1820 // The text-affordance band is not part of anyone's outside-press
1821 // dismissal: every tap that moves a caret is outside a selection
1822 // handle, so this rule would retire the handles on the first tap
1823 // that used them. Their lifetime belongs to the controller that
1824 // raised them.
1825 if !o.band.dismissed_by_outside_press() {
1826 continue;
1827 }
1828 match o.dismiss {
1829 DismissBehavior::ClickOutside | DismissBehavior::EscapeOrClickOutside => {
1830 to_dismiss.push(o.id);
1831 toggle_anchors.push(ToggleAnchor {
1832 anchor: o.anchor,
1833 modal: o.placement.is_modal(),
1834 });
1835 }
1836 DismissBehavior::PointerLeave { .. } => to_dismiss.push(o.id),
1837 DismissBehavior::EscapeKey | DismissBehavior::Manual => {}
1838 }
1839 }
1840
1841 (to_dismiss, toggle_anchors)
1842 }
1843
1844 /// Close a selected set and report what the dispatcher needs.
1845 fn apply_outside_press(
1846 &mut self,
1847 to_dismiss: Vec<OverlayId>,
1848 toggle_anchors: Vec<ToggleAnchor>,
1849 ) -> (Vec<WidgetId>, Option<WidgetId>, Vec<ToggleAnchor>) {
1850 if to_dismiss.is_empty() {
1851 return (Vec::new(), None, Vec::new());
1852 }
1853
1854 let focus_restore = self
1855 .stack
1856 .iter()
1857 .find(|o| to_dismiss.contains(&o.id))
1858 .and_then(|o| o.focus_restore);
1859
1860 let mut all_dismissed = Vec::new();
1861 for id in to_dismiss {
1862 all_dismissed.extend(self.dismiss_because(id, DismissReason::OutsidePress));
1863 }
1864 (all_dismissed, focus_restore, toggle_anchors)
1865 }
1866
1867 // -----------------------------------------------------------------
1868 // Release dismissal
1869 // -----------------------------------------------------------------
1870
1871 /// Arm an outside press for `pointer` at `point`, to be committed on its
1872 /// release.
1873 ///
1874 /// The direct-pointer half of outside-press dismissal. A mouse dismisses on
1875 /// the press and falls through, because a cursor names one pixel and the
1876 /// user aimed at it; a finger covers what it is about to actuate, so a tap
1877 /// that closes a menu must close only the menu. Arming defers the decision
1878 /// to the release and, while it stands, withholds the `Down` from whatever
1879 /// is beneath — so if the press is cancelled, or slid onto the very overlay
1880 /// it would have closed, the whole gesture delivers nothing at all.
1881 ///
1882 /// Returns a zeroed [`DismissArm`] and stores nothing when the press would
1883 /// close no overlay: an arm that has nothing to commit must not suppress
1884 /// the press beneath it.
1885 pub fn arm_dismiss(&mut self, pointer: PointerId, point: Point, busy: &[Point]) -> DismissArm {
1886 self.abort_dismiss(pointer);
1887 let (overlays, anchors) = self.outside_press_targets(point, busy);
1888 if overlays.is_empty() {
1889 return DismissArm::default();
1890 }
1891 self.arms.push(ArmedDismiss {
1892 pointer,
1893 overlays,
1894 anchors,
1895 });
1896 DismissArm {
1897 will_dismiss: true,
1898 suppress_beneath: true,
1899 }
1900 }
1901
1902 /// Complete `pointer`'s armed dismissal at its release point.
1903 ///
1904 /// Returns the same triple as
1905 /// [`handle_click_outside`](Self::handle_click_outside), empty when the
1906 /// pointer holds no arm.
1907 ///
1908 /// The release point is re-tested, and only overlays the release is *still*
1909 /// outside are closed. That is the slide-off case: a finger that lands
1910 /// beside a menu, drags onto it and lifts there has changed its mind, and
1911 /// the menu it is now touching must not be the thing it closes. The
1912 /// suppressed `Down` means nothing beneath ever saw the press either, so an
1913 /// aborted commit leaves the tree exactly as it found it.
1914 pub fn commit_dismiss(
1915 &mut self,
1916 pointer: PointerId,
1917 point: Point,
1918 ) -> (Vec<WidgetId>, Option<WidgetId>, Vec<WidgetId>) {
1919 let Some(index) = self.arms.iter().position(|a| a.pointer == pointer) else {
1920 return (Vec::new(), None, Vec::new());
1921 };
1922 let arm = self.arms.remove(index);
1923 let (still_outside, _) = self.outside_press_targets(point, &[]);
1924 let to_dismiss: Vec<OverlayId> = arm
1925 .overlays
1926 .into_iter()
1927 .filter(|id| still_outside.contains(id))
1928 .collect();
1929 let anchors = if to_dismiss.is_empty() {
1930 Vec::new()
1931 } else {
1932 arm.anchors
1933 };
1934 let (dismissed, focus_restore, toggles) = self.apply_outside_press(to_dismiss, anchors);
1935 (dismissed, focus_restore, anchors_of(toggles))
1936 }
1937
1938 /// Drop `pointer`'s arm without dismissing anything. Returns whether there
1939 /// was one — a cancelled press, or a contact that ended without a release.
1940 pub fn abort_dismiss(&mut self, pointer: PointerId) -> bool {
1941 let before = self.arms.len();
1942 self.arms.retain(|a| a.pointer != pointer);
1943 self.arms.len() != before
1944 }
1945
1946 /// Whether `pointer` is holding an armed dismissal.
1947 pub fn has_armed_dismiss(&self, pointer: PointerId) -> bool {
1948 self.arms.iter().any(|a| a.pointer == pointer)
1949 }
1950
1951 /// Every pointer currently holding an arm. Used by the dispatcher to drop
1952 /// arms whose contact has gone away without either releasing or cancelling.
1953 pub fn armed_pointers(&self) -> Vec<PointerId> {
1954 self.arms.iter().map(|a| a.pointer).collect()
1955 }
1956
1957 /// Set the content bounds for an overlay (after its content has been laid out).
1958 pub fn set_content_bounds(&mut self, id: OverlayId, size: Size) {
1959 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
1960 overlay.bounds = Rect::new(overlay.bounds.x, overlay.bounds.y, size.width, size.height);
1961 }
1962 }
1963
1964 /// Get overlay by content widget ID (for routing events to the correct overlay).
1965 pub fn find_by_content(&self, content_id: WidgetId) -> Option<OverlayId> {
1966 self.stack
1967 .iter()
1968 .find(|o| o.content_id == content_id)
1969 .map(|o| o.id)
1970 }
1971
1972 /// Convenience accessor for the safe-triangle hover gate: returns
1973 /// the bounds rect of the open overlay whose root content widget
1974 /// id matches `content_id`, or `None` when no such overlay is
1975 /// active. Equivalent to `find_by_content` + `bounds_for` chained.
1976 pub fn bounds_for_content(&self, content_id: WidgetId) -> Option<Rect> {
1977 self.stack
1978 .iter()
1979 .find(|o| o.content_id == content_id)
1980 .map(|o| o.bounds)
1981 }
1982
1983 // -------------------- Safe region (submenu traversal) --------------------
1984
1985 /// Arm the safe triangle for the overlay whose root content widget
1986 /// is `content_id`, with its apex at `apex` — the point the pointer
1987 /// left the anchor at.
1988 ///
1989 /// While armed and unexpired, a pointer inside the triangle
1990 /// spanned by the apex and this overlay's near vertical edge is
1991 /// treated as still inside the overlay's region, so neither the
1992 /// pointer-leave grace nor a sibling's hover-switch dismisses it.
1993 /// Re-arming an already-armed region restarts its budget.
1994 /// No-ops when no such overlay is open.
1995 pub(crate) fn arm_safe_region(
1996 &mut self,
1997 content_id: WidgetId,
1998 apex: Point,
1999 real_now: Instant,
2000 sim_now: Instant,
2001 ) {
2002 if let Some(overlay) = self
2003 .stack
2004 .iter_mut()
2005 .find(|o| o.content_id == content_id && !o.is_dismissing())
2006 {
2007 overlay.safe_apex = Some(apex);
2008 overlay.safe_apex_started_real = Some(real_now);
2009 overlay.safe_apex_started_sim = Some(sim_now);
2010 }
2011 }
2012
2013 /// Disarm the safe triangle on the overlay with the given id. Called
2014 /// when the pointer arrives (or returns) and when the budget is
2015 /// spent — after which the overlay dismisses on the ordinary
2016 /// schedule. Straying out of the cone does **not** disarm: it only
2017 /// starts the pointer-leave grace, which a re-entry cancels. See
2018 /// [`safe_triangle`].
2019 pub(crate) fn clear_safe_region(&mut self, id: OverlayId) {
2020 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
2021 overlay.safe_apex = None;
2022 overlay.safe_apex_started_real = None;
2023 overlay.safe_apex_started_sim = None;
2024 }
2025 }
2026
2027 /// The armed apex of the overlay rooted at `content_id`, if any —
2028 /// without regard to the budget, which only the tree's clocks can
2029 /// judge. Callers wanting the answer a widget may act on go through
2030 /// `WidgetTree::unexpired_safe_apex_for_content`, which is what
2031 /// fills the per-dispatch `EventContext` snapshot.
2032 pub(crate) fn safe_apex_for_content(&self, content_id: WidgetId) -> Option<Point> {
2033 self.stack
2034 .iter()
2035 .find(|o| o.content_id == content_id)
2036 .and_then(|o| o.safe_apex)
2037 }
2038
2039 /// Whether `point` currently sits inside the armed safe triangle of
2040 /// the overlay with the given id. `false` when the region is not
2041 /// armed or the overlay has no bounds yet.
2042 pub(crate) fn point_in_safe_region(&self, id: OverlayId, point: Point) -> bool {
2043 self.stack
2044 .iter()
2045 .find(|o| o.id == id)
2046 .and_then(|o| o.safe_apex.map(|apex| (apex, o.bounds)))
2047 .is_some_and(|(apex, bounds)| point_in_safe_triangle(point, apex, bounds))
2048 }
2049
2050 /// Change the dismiss behavior of an active overlay in place.
2051 ///
2052 /// Used by rich tooltips that promote from "ephemeral hover" to
2053 /// "sticky panel" after a dwell timer: at t=2s the tooltip calls
2054 /// this to swap `PointerLeave` for `EscapeOrClickOutside`, so the
2055 /// overlay stops vanishing the moment the pointer leaves the
2056 /// anchor. Also cancels any in-flight pointer-leave countdown.
2057 pub fn set_dismiss(&mut self, id: OverlayId, behavior: DismissBehavior) {
2058 if let Some(overlay) = self.stack.iter_mut().find(|o| o.id == id) {
2059 overlay.dismiss = behavior;
2060 overlay.pointer_leave_started_real = None;
2061 overlay.pointer_leave_started_sim = None;
2062 }
2063 }
2064}
2065
2066impl Default for OverlayManager {
2067 fn default() -> Self {
2068 Self::new()
2069 }
2070}
2071
2072impl std::fmt::Debug for OverlayManager {
2073 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2074 f.debug_struct("OverlayManager")
2075 .field("active_count", &self.stack.len())
2076 .finish()
2077 }
2078}
2079
2080#[cfg(test)]
2081mod tests {
2082 use super::*;
2083 use slotmap::KeyData;
2084
2085 pub(super) fn fake_id(n: u64) -> WidgetId {
2086 KeyData::from_ffi(n).into()
2087 }
2088
2089 #[test]
2090 fn a_new_request_takes_the_documented_defaults_and_each_builder_sets_its_field() {
2091 let request = OverlayRequest::new(
2092 fake_id(10),
2093 fake_id(1),
2094 OverlayPlacement::TrailingEdge,
2095 DismissBehavior::EscapeKey,
2096 );
2097 assert_eq!(request.content_id, fake_id(10));
2098 assert_eq!(request.anchor, fake_id(1));
2099 assert!(matches!(request.placement, OverlayPlacement::TrailingEdge));
2100 assert!(matches!(request.dismiss, DismissBehavior::EscapeKey));
2101 assert_eq!(request.layer, OverlayLayer::InTree);
2102 assert_eq!(request.parent_overlay, None);
2103 assert!(request.on_dismiss.is_none());
2104 assert_eq!(request.fade_duration, None);
2105 assert!(!request.inert);
2106
2107 let callback: OverlayDismissCallback = Rc::new(|_, _| {});
2108 let request = request.layer(OverlayLayer::NativePopup);
2109 assert_eq!(request.layer, OverlayLayer::NativePopup);
2110 let request = request.parent_overlay(OverlayId::new(7));
2111 assert_eq!(request.parent_overlay, Some(OverlayId::new(7)));
2112 let request = request.on_dismiss(callback.clone());
2113 assert!(
2114 request
2115 .on_dismiss
2116 .as_ref()
2117 .is_some_and(|installed| Rc::ptr_eq(installed, &callback)),
2118 );
2119 let request = request.with_fade(Duration::from_millis(150));
2120 assert_eq!(request.fade_duration, Some(Duration::from_millis(150)));
2121 let request = request.inert();
2122 assert!(request.inert);
2123
2124 // No builder reaches past its own field.
2125 assert_eq!(request.content_id, fake_id(10));
2126 assert_eq!(request.anchor, fake_id(1));
2127 assert!(matches!(request.placement, OverlayPlacement::TrailingEdge));
2128 assert!(matches!(request.dismiss, DismissBehavior::EscapeKey));
2129 assert_eq!(request.layer, OverlayLayer::NativePopup);
2130 assert_eq!(request.parent_overlay, Some(OverlayId::new(7)));
2131 assert!(request.on_dismiss.is_some());
2132 assert_eq!(request.fade_duration, Some(Duration::from_millis(150)));
2133 }
2134
2135 #[test]
2136 fn dismiss_all_fires_on_dismiss_callbacks() {
2137 // Regression: a `MenuItem`'s tap handler calls
2138 // `ctx.dismiss_all_overlays()` to close the menu after firing
2139 // its action. The dismiss callback set on the parent
2140 // `PopoverButton`/`PopoverIconButton`'s `OverlayRequest`
2141 // (which flips `popover_open` back to `false`) must fire so
2142 // the next trigger click reopens the menu instead of
2143 // observing stale-true and silently retoggling.
2144 //
2145 // The manager no longer *runs* these — a dismissal callback takes an
2146 // `EventContext` and the manager has no tree — so what it owes is
2147 // that every dismissed overlay's callback is parked for the tree to
2148 // run. Losing one here loses it everywhere.
2149 use std::rc::Rc;
2150 let mut mgr = OverlayManager::new();
2151 let cb_a: OverlayDismissCallback = Rc::new(|_, _| {});
2152 let cb_b: OverlayDismissCallback = Rc::new(|_, _| {});
2153 mgr.show(
2154 OverlayRequest::new(
2155 fake_id(10),
2156 fake_id(1),
2157 OverlayPlacement::Below,
2158 DismissBehavior::ClickOutside,
2159 )
2160 .on_dismiss(cb_a),
2161 );
2162 mgr.show(
2163 OverlayRequest::new(
2164 fake_id(11),
2165 fake_id(2),
2166 OverlayPlacement::Below,
2167 DismissBehavior::ClickOutside,
2168 )
2169 .on_dismiss(cb_b),
2170 );
2171 let dismissed = mgr.dismiss_all();
2172 assert_eq!(dismissed.len(), 2);
2173 assert!(mgr.is_empty());
2174 let parked = mgr.take_pending_dismiss();
2175 assert_eq!(
2176 parked.len(),
2177 2,
2178 "both overlays' on_dismiss must be parked for the tree to run",
2179 );
2180 assert!(
2181 parked
2182 .iter()
2183 .all(|(_, reason)| *reason == DismissReason::Programmatic),
2184 "`dismiss_all` is the application asking, so that is what the \
2185 callbacks are told",
2186 );
2187 assert!(
2188 mgr.take_pending_dismiss().is_empty(),
2189 "draining is not repeatable — a second read must not re-run them",
2190 );
2191 }
2192
2193 #[test]
2194 fn show_and_dismiss() {
2195 let mut mgr = OverlayManager::new();
2196 let id = mgr.show(OverlayRequest::new(
2197 fake_id(10),
2198 fake_id(1),
2199 OverlayPlacement::Below,
2200 DismissBehavior::ClickOutside,
2201 ));
2202 assert_eq!(mgr.len(), 1);
2203
2204 mgr.dismiss(id);
2205 assert!(mgr.is_empty());
2206 }
2207
2208 #[test]
2209 fn cascade_dismissal() {
2210 let mut mgr = OverlayManager::new();
2211 let parent = mgr.show(OverlayRequest::new(
2212 fake_id(10),
2213 fake_id(1),
2214 OverlayPlacement::Below,
2215 DismissBehavior::ClickOutside,
2216 ));
2217 let _child = mgr.show(
2218 OverlayRequest::new(
2219 fake_id(11),
2220 fake_id(10),
2221 OverlayPlacement::TrailingEdge,
2222 DismissBehavior::ClickOutside,
2223 )
2224 .parent_overlay(parent),
2225 );
2226 assert_eq!(mgr.len(), 2);
2227
2228 // Dismissing parent cascades to child
2229 mgr.dismiss(parent);
2230 assert!(mgr.is_empty());
2231 }
2232
2233 #[test]
2234 fn cascade_depth_is_bounded() {
2235 // A cyclic tooltip `:key` cascade (A→B→A) keeps minting nested
2236 // overlays with no natural ceiling. `MAX_OVERLAY_NESTING_DEPTH`
2237 // bounds it: once a new overlay would nest at the cap, `show`
2238 // drops it rather than growing the stack forever — and must not
2239 // panic, since this is reachable by real user clicking.
2240 let mut mgr = OverlayManager::new();
2241 let mut parent = mgr.show(OverlayRequest::new(
2242 fake_id(100),
2243 fake_id(1),
2244 OverlayPlacement::Below,
2245 DismissBehavior::Manual,
2246 ));
2247 // Root is depth 0; fill the chain so MAX overlays exist, the
2248 // deepest at depth MAX-1.
2249 for i in 1..MAX_OVERLAY_NESTING_DEPTH {
2250 parent = mgr.show(
2251 OverlayRequest::new(
2252 fake_id(100 + i as u64),
2253 fake_id(1),
2254 OverlayPlacement::Below,
2255 DismissBehavior::Manual,
2256 )
2257 .parent_overlay(parent),
2258 );
2259 }
2260 assert_eq!(
2261 mgr.len(),
2262 MAX_OVERLAY_NESTING_DEPTH,
2263 "chain should fill exactly to the cap"
2264 );
2265
2266 // The next child would nest at depth == MAX → dropped.
2267 let dropped = mgr.show(
2268 OverlayRequest::new(
2269 fake_id(999),
2270 fake_id(1),
2271 OverlayPlacement::Below,
2272 DismissBehavior::Manual,
2273 )
2274 .parent_overlay(parent),
2275 );
2276 assert_eq!(
2277 mgr.len(),
2278 MAX_OVERLAY_NESTING_DEPTH,
2279 "over-cap overlay must not be pushed"
2280 );
2281 assert!(
2282 mgr.stack.iter().all(|o| o.id != dropped),
2283 "the dropped overlay id must not appear in the stack"
2284 );
2285 }
2286
2287 #[test]
2288 fn dismiss_top() {
2289 let mut mgr = OverlayManager::new();
2290 let _a = mgr.show(OverlayRequest::new(
2291 fake_id(10),
2292 fake_id(1),
2293 OverlayPlacement::Below,
2294 DismissBehavior::Manual,
2295 ));
2296 let b = mgr.show(OverlayRequest::new(
2297 fake_id(11),
2298 fake_id(2),
2299 OverlayPlacement::Below,
2300 DismissBehavior::Manual,
2301 ));
2302
2303 let dismissed = mgr.dismiss_top();
2304 assert_eq!(dismissed.map(|(id, _, _)| id), Some(b));
2305 assert_eq!(mgr.len(), 1);
2306 }
2307
2308 #[test]
2309 fn click_outside_dismisses() {
2310 let mut mgr = OverlayManager::new();
2311 mgr.show(OverlayRequest::new(
2312 fake_id(10),
2313 fake_id(1),
2314 OverlayPlacement::Below,
2315 DismissBehavior::ClickOutside,
2316 ));
2317
2318 // Set overlay bounds
2319 let id = mgr.active_ids()[0];
2320 mgr.set_content_bounds(id, Size::new(100.0, 50.0));
2321
2322 // Click inside — no dismiss
2323 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(50.0, 25.0));
2324 assert!(dismissed.is_empty());
2325 assert_eq!(mgr.len(), 1);
2326
2327 // Click outside — dismissed
2328 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
2329 assert!(!dismissed.is_empty());
2330 assert!(mgr.is_empty());
2331 }
2332
2333 #[test]
2334 fn click_outside_returns_focus_restore() {
2335 let mut mgr = OverlayManager::new();
2336 let trigger = fake_id(99);
2337 mgr.show(OverlayRequest::new(
2338 fake_id(10),
2339 fake_id(1),
2340 OverlayPlacement::Below,
2341 DismissBehavior::ClickOutside,
2342 ));
2343 let id = mgr.active_ids()[0];
2344 mgr.set_content_bounds(id, Size::new(100.0, 50.0));
2345 mgr.set_top_focus_restore(trigger);
2346
2347 let (dismissed, focus_restore, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
2348 assert_eq!(dismissed.len(), 1);
2349 assert_eq!(focus_restore, Some(trigger));
2350 }
2351
2352 #[test]
2353 fn click_outside_focus_restore_picks_bottommost() {
2354 // When click-outside dismisses several stacked top-level
2355 // overlays in one pass, focus should land on the *oldest*
2356 // overlay's restore target — the focus state from before any
2357 // overlay opened. The topmost overlay's restore target points
2358 // inside the (now-dismissed) overlay below it.
2359 let mut mgr = OverlayManager::new();
2360 let pre_overlay_focus = fake_id(99);
2361 let inside_a = fake_id(50);
2362 let a = mgr.show(OverlayRequest::new(
2363 fake_id(10),
2364 fake_id(1),
2365 OverlayPlacement::Below,
2366 DismissBehavior::ClickOutside,
2367 ));
2368 mgr.set_content_bounds(a, Size::new(100.0, 50.0));
2369 mgr.set_top_focus_restore(pre_overlay_focus);
2370 let b = mgr.show(OverlayRequest::new(
2371 fake_id(11),
2372 fake_id(2),
2373 OverlayPlacement::Below,
2374 DismissBehavior::ClickOutside,
2375 ));
2376 mgr.set_content_bounds(b, Size::new(100.0, 50.0));
2377 mgr.set_top_focus_restore(inside_a);
2378
2379 let (_, focus_restore, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
2380 assert_eq!(focus_restore, Some(pre_overlay_focus));
2381 }
2382
2383 #[test]
2384 fn manual_dismiss_ignores_click_outside() {
2385 let mut mgr = OverlayManager::new();
2386 mgr.show(OverlayRequest::new(
2387 fake_id(10),
2388 fake_id(1),
2389 OverlayPlacement::Below,
2390 DismissBehavior::Manual,
2391 ));
2392
2393 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
2394 assert!(dismissed.is_empty());
2395 assert_eq!(mgr.len(), 1);
2396 }
2397
2398 #[test]
2399 fn escape_dismisses_escape_or_click_outside() {
2400 let mut mgr = OverlayManager::new();
2401 let id = mgr.show(OverlayRequest::new(
2402 fake_id(10),
2403 fake_id(1),
2404 OverlayPlacement::Below,
2405 DismissBehavior::EscapeOrClickOutside,
2406 ));
2407
2408 let dismissed = mgr.try_dismiss_top_on_escape();
2409 assert_eq!(dismissed.map(|(oid, _, _)| oid), Some(id));
2410 assert!(mgr.is_empty());
2411 }
2412
2413 #[test]
2414 fn escape_dismisses_escape_key_only() {
2415 let mut mgr = OverlayManager::new();
2416 let id = mgr.show(OverlayRequest::new(
2417 fake_id(10),
2418 fake_id(1),
2419 OverlayPlacement::Below,
2420 DismissBehavior::EscapeKey,
2421 ));
2422
2423 // Escape should dismiss
2424 let dismissed = mgr.try_dismiss_top_on_escape();
2425 assert_eq!(dismissed.map(|(oid, _, _)| oid), Some(id));
2426 assert!(mgr.is_empty());
2427 }
2428
2429 #[test]
2430 fn escape_does_not_dismiss_click_outside_only() {
2431 let mut mgr = OverlayManager::new();
2432 mgr.show(OverlayRequest::new(
2433 fake_id(10),
2434 fake_id(1),
2435 OverlayPlacement::Below,
2436 DismissBehavior::ClickOutside,
2437 ));
2438
2439 assert!(mgr.try_dismiss_top_on_escape().is_none());
2440 assert_eq!(mgr.len(), 1);
2441 }
2442
2443 #[test]
2444 fn escape_does_not_dismiss_manual() {
2445 let mut mgr = OverlayManager::new();
2446 mgr.show(OverlayRequest::new(
2447 fake_id(10),
2448 fake_id(1),
2449 OverlayPlacement::Below,
2450 DismissBehavior::Manual,
2451 ));
2452
2453 assert!(mgr.try_dismiss_top_on_escape().is_none());
2454 assert_eq!(mgr.len(), 1);
2455 }
2456
2457 #[test]
2458 fn click_outside_dismisses_escape_or_click_outside() {
2459 let mut mgr = OverlayManager::new();
2460 mgr.show(OverlayRequest::new(
2461 fake_id(10),
2462 fake_id(1),
2463 OverlayPlacement::Below,
2464 DismissBehavior::EscapeOrClickOutside,
2465 ));
2466
2467 let id = mgr.active_ids()[0];
2468 mgr.set_content_bounds(id, Size::new(100.0, 50.0));
2469
2470 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
2471 assert!(!dismissed.is_empty());
2472 assert!(mgr.is_empty());
2473 }
2474
2475 #[test]
2476 fn click_outside_reports_click_opened_anchors_only() {
2477 // An outside click dismisses both a click-opened dropdown and a
2478 // hover-opened tooltip, but only the click-opened overlay's anchor
2479 // is reported as a re-toggle guard: clicking a tooltip's anchor
2480 // should still fall through to the widget beneath.
2481 let mut mgr = OverlayManager::new();
2482 let click_anchor = fake_id(1);
2483 let hover_anchor = fake_id(2);
2484
2485 let click_overlay = mgr.show(OverlayRequest::new(
2486 fake_id(10),
2487 click_anchor,
2488 OverlayPlacement::Below,
2489 DismissBehavior::EscapeOrClickOutside,
2490 ));
2491 mgr.set_content_bounds(click_overlay, Size::new(100.0, 50.0));
2492
2493 let hover_overlay = mgr.show(OverlayRequest::new(
2494 fake_id(11),
2495 hover_anchor,
2496 OverlayPlacement::Below,
2497 DismissBehavior::PointerLeave {
2498 delay: std::time::Duration::from_millis(150),
2499 },
2500 ));
2501 mgr.set_content_bounds(hover_overlay, Size::new(100.0, 50.0));
2502
2503 let (dismissed, _focus, toggle_anchors) =
2504 mgr.handle_click_outside(Point::new(500.0, 500.0));
2505
2506 // Both overlays close on the outside click...
2507 assert_eq!(dismissed.len(), 2);
2508 assert!(mgr.is_empty());
2509 // ...but only the click-opened dropdown contributes a guard anchor.
2510 assert_eq!(toggle_anchors, vec![click_anchor]);
2511 }
2512
2513 #[test]
2514 fn click_outside_does_not_dismiss_escape_key_only() {
2515 let mut mgr = OverlayManager::new();
2516 mgr.show(OverlayRequest::new(
2517 fake_id(10),
2518 fake_id(1),
2519 OverlayPlacement::Below,
2520 DismissBehavior::EscapeKey,
2521 ));
2522
2523 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(500.0, 500.0));
2524 assert!(dismissed.is_empty());
2525 assert_eq!(mgr.len(), 1);
2526 }
2527
2528 #[test]
2529 fn click_outside_is_layered_over_a_modal() {
2530 // A modal card with a sticky tooltip floating above it (as a rich
2531 // tooltip becomes after it dwells). Regression for: while any modal
2532 // (or its full-viewport scrim) was open, the old stack-wide `hit_test`
2533 // short-circuit made *no* click-outside overlay dismissable, so the
2534 // sticky tooltip never closed on a click elsewhere in the modal.
2535 fn set_bounds(mgr: &mut OverlayManager, id: OverlayId, r: Rect) {
2536 mgr.stack.iter_mut().find(|o| o.id == id).unwrap().bounds = r;
2537 }
2538 // Build a fresh [modal, tooltip] stack. The modal card spans
2539 // x∈[300,900], y∈[60,740]; the sticky tooltip sits near the card's
2540 // bottom and *overflows* below it (y∈[620,760]).
2541 fn build() -> (OverlayManager, OverlayId, OverlayId) {
2542 let mut mgr = OverlayManager::new();
2543 let modal = mgr.show(OverlayRequest::new(
2544 fake_id(10),
2545 fake_id(1),
2546 OverlayPlacement::Centered,
2547 DismissBehavior::EscapeOrClickOutside,
2548 ));
2549 set_bounds(&mut mgr, modal, Rect::new(300.0, 60.0, 600.0, 680.0));
2550 let tooltip = mgr.show(OverlayRequest::new(
2551 fake_id(11),
2552 fake_id(2),
2553 OverlayPlacement::Below,
2554 // A promoted sticky rich tooltip: EscapeOrClickOutside.
2555 DismissBehavior::EscapeOrClickOutside,
2556 ));
2557 set_bounds(&mut mgr, tooltip, Rect::new(400.0, 620.0, 200.0, 140.0));
2558 (mgr, modal, tooltip)
2559 }
2560
2561 // 1. Click elsewhere inside the modal card (outside the tooltip) →
2562 // the tooltip (stacked above) dismisses; the modal stays up.
2563 let (mut mgr, modal, _tooltip) = build();
2564 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(350.0, 100.0));
2565 assert!(dismissed.contains(&fake_id(11)), "tooltip should dismiss");
2566 assert!(
2567 mgr.active_ids().contains(&modal),
2568 "modal must survive a click inside itself"
2569 );
2570
2571 // 2. Click inside the tooltip — even the part overflowing below the
2572 // card — leaves BOTH standing (nothing is stacked above the hit).
2573 let (mut mgr, modal, tooltip) = build();
2574 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(450.0, 750.0));
2575 assert!(
2576 dismissed.is_empty(),
2577 "clicking the tooltip dismisses nothing"
2578 );
2579 assert!(mgr.active_ids().contains(&modal));
2580 assert!(mgr.active_ids().contains(&tooltip));
2581
2582 // 3. Click the bare background (outside both) → both dismiss, as
2583 // before (each per its own click-outside policy).
2584 let (mut mgr, _modal, _tooltip) = build();
2585 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(10.0, 10.0));
2586 assert!(dismissed.contains(&fake_id(10)));
2587 assert!(dismissed.contains(&fake_id(11)));
2588 assert!(mgr.is_empty());
2589 }
2590
2591 #[test]
2592 fn active_content_ids() {
2593 let mut mgr = OverlayManager::new();
2594 mgr.show(OverlayRequest::new(
2595 fake_id(10),
2596 fake_id(1),
2597 OverlayPlacement::Below,
2598 DismissBehavior::Manual,
2599 ));
2600 mgr.show(OverlayRequest::new(
2601 fake_id(20),
2602 fake_id(2),
2603 OverlayPlacement::Below,
2604 DismissBehavior::Manual,
2605 ));
2606
2607 let ids = mgr.active_content_ids();
2608 assert_eq!(ids.len(), 2);
2609 assert_eq!(ids[0], fake_id(10));
2610 assert_eq!(ids[1], fake_id(20));
2611 }
2612
2613 #[test]
2614 fn hit_test_topmost_first() {
2615 let mut mgr = OverlayManager::new();
2616 let a = mgr.show(OverlayRequest::new(
2617 fake_id(10),
2618 fake_id(1),
2619 OverlayPlacement::Below,
2620 DismissBehavior::Manual,
2621 ));
2622 let b = mgr.show(OverlayRequest::new(
2623 fake_id(11),
2624 fake_id(2),
2625 OverlayPlacement::Below,
2626 DismissBehavior::Manual,
2627 ));
2628
2629 // Both overlays at origin with same bounds
2630 mgr.set_content_bounds(a, Size::new(100.0, 50.0));
2631 mgr.set_content_bounds(b, Size::new(100.0, 50.0));
2632
2633 // Hit test should find topmost (b)
2634 assert_eq!(mgr.hit_test(Point::new(50.0, 25.0)), Some(b));
2635 }
2636
2637 #[test]
2638 fn hit_test_skips_a_fading_out_overlay() {
2639 // Regression: dismissing a faded overlay only starts the fade-out and
2640 // defers stack removal, so the overlay lingers in the stack (and its
2641 // content stays interactive) for the fade duration. `hit_test` must
2642 // treat it as gone — matching `active_ids` — so clicks reach the
2643 // widget underneath and outside-click dismissal of lower overlays
2644 // isn't suppressed by the ghost.
2645 let mut mgr = OverlayManager::new();
2646 let id = mgr.show(
2647 OverlayRequest::new(
2648 fake_id(10),
2649 fake_id(1),
2650 OverlayPlacement::Below,
2651 DismissBehavior::ClickOutside,
2652 )
2653 .with_fade(Duration::from_millis(150)),
2654 );
2655 mgr.set_content_bounds(id, Size::new(100.0, 50.0));
2656 let point = Point::new(50.0, 25.0);
2657
2658 // Live overlay: hittable, and reported by active_ids.
2659 assert_eq!(mgr.hit_test(point), Some(id));
2660 assert!(mgr.active_ids().contains(&id));
2661
2662 // The fade machinery is populated post-show by the framework.
2663 mgr.attach_fade(id, Signal::new(1.0), Duration::from_millis(150));
2664
2665 // Dismissing only starts the fade-out — the overlay is still in the
2666 // stack until `process_pending_fade_dismissals` fires.
2667 let dismissed = mgr.dismiss(id);
2668 assert!(dismissed.is_empty(), "fade-out defers removal");
2669 assert_eq!(mgr.stack.len(), 1, "overlay lingers during the fade");
2670
2671 // Both predicates now agree it's gone.
2672 assert_eq!(
2673 mgr.hit_test(point),
2674 None,
2675 "fading overlay no longer eats clicks"
2676 );
2677 assert!(!mgr.active_ids().contains(&id));
2678 }
2679
2680 // --- Auto-dismiss pause / resume ---
2681
2682 #[test]
2683 fn pause_auto_dismiss_removes_overlay_from_deadline_set() {
2684 let mut mgr = OverlayManager::new();
2685 let id = mgr.show_for(
2686 OverlayRequest::new(
2687 fake_id(10),
2688 fake_id(1),
2689 OverlayPlacement::Centered,
2690 DismissBehavior::Manual,
2691 ),
2692 Duration::from_secs(10),
2693 );
2694 assert!(mgr.next_auto_dismiss_deadline().is_some());
2695 assert!(!mgr.is_auto_dismiss_paused(id));
2696
2697 mgr.pause_auto_dismiss(id);
2698 assert!(mgr.is_auto_dismiss_paused(id));
2699 assert!(
2700 mgr.next_auto_dismiss_deadline().is_none(),
2701 "paused overlay must drop out of the deadline-min query"
2702 );
2703
2704 mgr.resume_auto_dismiss(id);
2705 assert!(!mgr.is_auto_dismiss_paused(id));
2706 assert!(mgr.next_auto_dismiss_deadline().is_some());
2707 }
2708
2709 #[test]
2710 fn pause_then_resume_restores_remaining_time() {
2711 let mut mgr = OverlayManager::new();
2712 let id = mgr.show_for(
2713 OverlayRequest::new(
2714 fake_id(11),
2715 fake_id(1),
2716 OverlayPlacement::Centered,
2717 DismissBehavior::Manual,
2718 ),
2719 Duration::from_secs(10),
2720 );
2721
2722 mgr.pause_auto_dismiss(id);
2723 // Sleep equivalent: rely on the fact pausing right after show
2724 // captures ~10s remaining (elapsed is ~0).
2725 let overlay = mgr.stack.iter().find(|o| o.id == id).unwrap();
2726 let remaining = overlay.paused_remaining.unwrap();
2727 assert!(
2728 remaining >= Duration::from_secs(9),
2729 "remaining should be near the original 10s, got {remaining:?}"
2730 );
2731 assert!(remaining <= Duration::from_secs(10));
2732
2733 mgr.resume_auto_dismiss(id);
2734 let overlay = mgr.stack.iter().find(|o| o.id == id).unwrap();
2735 // After resume, auto_dismiss_after equals the previously-stashed
2736 // remaining, and shown_at_real has been refreshed so the new
2737 // deadline starts from "now + remaining".
2738 assert_eq!(overlay.auto_dismiss_after, Some(remaining));
2739 assert!(overlay.paused_remaining.is_none());
2740 }
2741
2742 #[test]
2743 fn pause_is_idempotent() {
2744 let mut mgr = OverlayManager::new();
2745 let id = mgr.show_for(
2746 OverlayRequest::new(
2747 fake_id(12),
2748 fake_id(1),
2749 OverlayPlacement::Centered,
2750 DismissBehavior::Manual,
2751 ),
2752 Duration::from_secs(10),
2753 );
2754 mgr.pause_auto_dismiss(id);
2755 let first_remaining = mgr.stack[0].paused_remaining;
2756 mgr.pause_auto_dismiss(id); // second pause must not overwrite
2757 let second_remaining = mgr.stack[0].paused_remaining;
2758 assert_eq!(
2759 first_remaining, second_remaining,
2760 "double-pause must preserve the original stashed remaining"
2761 );
2762 }
2763
2764 #[test]
2765 fn resume_on_unpaused_is_noop() {
2766 let mut mgr = OverlayManager::new();
2767 let id = mgr.show_for(
2768 OverlayRequest::new(
2769 fake_id(13),
2770 fake_id(1),
2771 OverlayPlacement::Centered,
2772 DismissBehavior::Manual,
2773 ),
2774 Duration::from_secs(10),
2775 );
2776 let before = mgr.stack[0].auto_dismiss_after;
2777 mgr.resume_auto_dismiss(id); // never paused
2778 let after = mgr.stack[0].auto_dismiss_after;
2779 assert_eq!(before, after);
2780 }
2781
2782 #[test]
2783 fn pause_on_persistent_overlay_is_noop() {
2784 let mut mgr = OverlayManager::new();
2785 let id = mgr.show(OverlayRequest::new(
2786 fake_id(14),
2787 fake_id(1),
2788 OverlayPlacement::Centered,
2789 DismissBehavior::Manual,
2790 ));
2791 // No auto_dismiss_after — pause should be a no-op.
2792 mgr.pause_auto_dismiss(id);
2793 assert!(!mgr.is_auto_dismiss_paused(id));
2794 assert!(mgr.stack[0].paused_remaining.is_none());
2795 }
2796
2797 #[test]
2798 fn pause_on_unknown_id_is_noop() {
2799 let mut mgr = OverlayManager::new();
2800 mgr.pause_auto_dismiss(OverlayId::new(9999)); // must not panic
2801 mgr.resume_auto_dismiss(OverlayId::new(9999));
2802 }
2803
2804 // -----------------------------------------------------------------
2805 // Bands
2806 // -----------------------------------------------------------------
2807
2808 fn show_at(
2809 mgr: &mut OverlayManager,
2810 content: u64,
2811 bounds: Rect,
2812 dismiss: DismissBehavior,
2813 band: OverlayBand,
2814 ) -> OverlayId {
2815 let id = mgr.show_in_band(
2816 OverlayRequest::new(
2817 fake_id(content),
2818 fake_id(content + 100),
2819 OverlayPlacement::Centered,
2820 dismiss,
2821 ),
2822 band,
2823 );
2824 if let Some(overlay) = mgr.stack.iter_mut().find(|o| o.id == id) {
2825 overlay.bounds = bounds;
2826 }
2827 id
2828 }
2829
2830 /// A selection handle raised while a menu is open must go **under** the
2831 /// menu. Show order alone would put it on top, and then the menu would be
2832 /// unreachable behind a 44 dp handle.
2833 #[test]
2834 fn a_text_affordance_is_inserted_below_the_menus_already_open() {
2835 let mut mgr = OverlayManager::new();
2836 let menu = show_at(
2837 &mut mgr,
2838 1,
2839 Rect::new(0.0, 0.0, 100.0, 100.0),
2840 DismissBehavior::ClickOutside,
2841 OverlayBand::Standard,
2842 );
2843 let handle = show_at(
2844 &mut mgr,
2845 2,
2846 Rect::new(200.0, 200.0, 44.0, 44.0),
2847 DismissBehavior::Manual,
2848 OverlayBand::TextAffordance,
2849 );
2850 let order: Vec<OverlayId> = mgr.stack.iter().map(|o| o.id).collect();
2851 assert_eq!(order, vec![handle, menu], "the handle sits under the menu");
2852 assert_eq!(mgr.topmost().map(|o| o.id), Some(menu));
2853 }
2854
2855 /// Every tap that moves a caret is "outside" a selection handle, so
2856 /// outside-press dismissal would retire the handles on the first tap that
2857 /// used them. The band is exempt; the menu above it still closes.
2858 #[test]
2859 fn an_outside_press_leaves_the_text_affordance_band_alone() {
2860 let mut mgr = OverlayManager::new();
2861 let handle = show_at(
2862 &mut mgr,
2863 2,
2864 Rect::new(200.0, 200.0, 44.0, 44.0),
2865 DismissBehavior::ClickOutside,
2866 OverlayBand::TextAffordance,
2867 );
2868 let menu = show_at(
2869 &mut mgr,
2870 1,
2871 Rect::new(0.0, 0.0, 100.0, 100.0),
2872 DismissBehavior::ClickOutside,
2873 OverlayBand::Standard,
2874 );
2875 let (dismissed, _, _) = mgr.handle_click_outside(Point::new(600.0, 600.0));
2876 assert_eq!(dismissed, vec![fake_id(1)], "only the menu closes");
2877 assert!(mgr.overlay(handle).is_some());
2878 assert!(mgr.overlay(menu).is_none());
2879 }
2880
2881 // -----------------------------------------------------------------
2882 // Release dismissal
2883 // -----------------------------------------------------------------
2884
2885 fn contact(n: u64) -> PointerId {
2886 crate::pointer::PointerIdAllocator::global()
2887 .begin(crate::pointer::BackendDeviceKey::new(0x0FA1), n)
2888 }
2889
2890 fn with_one_menu() -> (OverlayManager, OverlayId) {
2891 let mut mgr = OverlayManager::new();
2892 let menu = show_at(
2893 &mut mgr,
2894 1,
2895 Rect::new(100.0, 100.0, 200.0, 200.0),
2896 DismissBehavior::ClickOutside,
2897 OverlayBand::Standard,
2898 );
2899 (mgr, menu)
2900 }
2901
2902 #[test]
2903 fn an_armed_press_suppresses_the_down_and_dismisses_on_the_up() {
2904 let (mut mgr, menu) = with_one_menu();
2905 let finger = contact(1);
2906 let arm = mgr.arm_dismiss(finger, Point::new(500.0, 500.0), &[]);
2907 assert!(arm.will_dismiss && arm.suppress_beneath);
2908 assert!(mgr.overlay(menu).is_some(), "nothing closes on the press");
2909
2910 let (dismissed, _, anchors) = mgr.commit_dismiss(finger, Point::new(500.0, 500.0));
2911 assert_eq!(dismissed, vec![fake_id(1)]);
2912 assert_eq!(anchors, vec![fake_id(101)]);
2913 assert!(!mgr.has_armed_dismiss(finger));
2914 }
2915
2916 /// A press that would close nothing must not suppress itself — otherwise
2917 /// every touch anywhere in a window with no overlay open would be eaten.
2918 #[test]
2919 fn a_press_with_nothing_to_close_arms_nothing() {
2920 let mut mgr = OverlayManager::new();
2921 let finger = contact(2);
2922 assert_eq!(
2923 mgr.arm_dismiss(finger, Point::new(10.0, 10.0), &[]),
2924 DismissArm::default()
2925 );
2926 assert!(!mgr.has_armed_dismiss(finger));
2927 }
2928
2929 #[test]
2930 fn a_cancelled_press_aborts_the_arm() {
2931 let (mut mgr, menu) = with_one_menu();
2932 let finger = contact(3);
2933 assert!(
2934 mgr.arm_dismiss(finger, Point::new(500.0, 500.0), &[])
2935 .will_dismiss
2936 );
2937 assert!(mgr.abort_dismiss(finger));
2938 assert!(mgr.overlay(menu).is_some(), "the menu survives a cancel");
2939 assert!(!mgr.abort_dismiss(finger), "aborting twice is a no-op");
2940
2941 // And a commit after the abort finds nothing to do.
2942 let (dismissed, restore, anchors) = mgr.commit_dismiss(finger, Point::new(500.0, 500.0));
2943 assert!(dismissed.is_empty() && restore.is_none() && anchors.is_empty());
2944 }
2945
2946 /// Land beside the menu, drag onto it, lift there: the finger changed its
2947 /// mind, and the menu it is now touching is not the thing it closes.
2948 #[test]
2949 fn a_press_that_slides_onto_the_menu_dismisses_nothing() {
2950 let (mut mgr, menu) = with_one_menu();
2951 let finger = contact(4);
2952 assert!(
2953 mgr.arm_dismiss(finger, Point::new(500.0, 500.0), &[])
2954 .will_dismiss
2955 );
2956 let (dismissed, _, anchors) = mgr.commit_dismiss(finger, Point::new(150.0, 150.0));
2957 assert!(dismissed.is_empty(), "the release landed inside the menu");
2958 assert!(anchors.is_empty());
2959 assert!(mgr.overlay(menu).is_some());
2960 }
2961
2962 /// A second finger landing on the page while the first works inside the
2963 /// menu is not a dismissal gesture.
2964 #[test]
2965 fn a_second_contact_cannot_dismiss_what_the_first_is_manipulating() {
2966 let (mut mgr, menu) = with_one_menu();
2967 let second = contact(5);
2968 let busy = [Point::new(150.0, 150.0)]; // the first finger, inside the menu
2969 assert_eq!(
2970 mgr.arm_dismiss(second, Point::new(500.0, 500.0), &busy),
2971 DismissArm::default()
2972 );
2973 assert!(mgr.overlay(menu).is_some());
2974
2975 // With the first finger lifted the same press closes it.
2976 assert!(
2977 mgr.arm_dismiss(second, Point::new(500.0, 500.0), &[])
2978 .will_dismiss
2979 );
2980 let (dismissed, _, _) = mgr.commit_dismiss(second, Point::new(500.0, 500.0));
2981 assert_eq!(dismissed, vec![fake_id(1)]);
2982 }
2983
2984 /// Two contacts, each with its own arm: neither may commit the other's.
2985 #[test]
2986 fn arms_are_tracked_per_pointer() {
2987 let mut mgr = OverlayManager::new();
2988 let lower = show_at(
2989 &mut mgr,
2990 1,
2991 Rect::new(0.0, 0.0, 100.0, 100.0),
2992 DismissBehavior::ClickOutside,
2993 OverlayBand::Standard,
2994 );
2995 let upper = show_at(
2996 &mut mgr,
2997 2,
2998 Rect::new(400.0, 0.0, 100.0, 100.0),
2999 DismissBehavior::ClickOutside,
3000 OverlayBand::Standard,
3001 );
3002 let a = contact(6);
3003 let b = contact(7);
3004 // `a` lands inside the lower overlay: only the upper one is above it.
3005 assert!(mgr.arm_dismiss(a, Point::new(50.0, 50.0), &[]).will_dismiss);
3006 // `b` lands on the background: both are above it.
3007 assert!(
3008 mgr.arm_dismiss(b, Point::new(700.0, 700.0), &[])
3009 .will_dismiss
3010 );
3011 assert_eq!(mgr.armed_pointers().len(), 2);
3012
3013 let (dismissed, _, _) = mgr.commit_dismiss(a, Point::new(50.0, 50.0));
3014 assert_eq!(dismissed, vec![fake_id(2)], "only the overlay above `a`");
3015 assert!(mgr.overlay(lower).is_some());
3016 assert!(mgr.overlay(upper).is_none());
3017
3018 // `b`'s arm still names the upper overlay, which is gone; committing it
3019 // closes what is left and does not panic on the absent id.
3020 let (dismissed, _, _) = mgr.commit_dismiss(b, Point::new(700.0, 700.0));
3021 assert_eq!(dismissed, vec![fake_id(1)]);
3022 assert!(mgr.armed_pointers().is_empty());
3023 }
3024
3025 /// Re-arming the same pointer replaces its arm rather than stacking one.
3026 #[test]
3027 fn a_second_arm_for_one_pointer_replaces_the_first() {
3028 let (mut mgr, _menu) = with_one_menu();
3029 let finger = contact(8);
3030 assert!(
3031 mgr.arm_dismiss(finger, Point::new(500.0, 500.0), &[])
3032 .will_dismiss
3033 );
3034 assert!(
3035 mgr.arm_dismiss(finger, Point::new(600.0, 600.0), &[])
3036 .will_dismiss
3037 );
3038 assert_eq!(mgr.armed_pointers(), vec![finger]);
3039 }
3040}