Skip to main content

bhoo/systems/material/
overlay.rs

1use crate::*;
2
3/// Fades a modal out, optionally holding it to show an accepted choice first.
4#[derive(Clone, Copy, Debug)]
5pub struct SelectionDismiss {
6    choice: Option<u64>,
7    start: f64,
8    fade: f64,
9}
10
11impl SelectionDismiss {
12    const HOLD: f64 = 0.14;
13
14    pub fn new(choice: u64, now: f64, motion_scale: f64) -> Self {
15        Self {
16            choice: Some(choice),
17            ..Self::fade_out(now, motion_scale)
18        }
19    }
20
21    /// Start the exit fade immediately, for example after a tap on the scrim.
22    pub fn fade_out(now: f64, motion_scale: f64) -> Self {
23        Self {
24            choice: None,
25            start: now,
26            fade: 0.16 * motion_scale.max(0.0),
27        }
28    }
29
30    /// Return the modal's opacity, or None once it can be removed.
31    pub fn opacity(self, frame: &mut Frame<'_>, bounds: Rect, now: f64) -> Option<f32> {
32        let fade_start = self.start
33            + if self.choice.is_some() {
34                Self::HOLD
35            } else {
36                0.0
37            };
38        if now < fade_start {
39            frame.continuous(bounds);
40            return Some(1.0);
41        }
42        let fade = if frame.reduced_motion() {
43            0.0
44        } else {
45            self.fade
46        };
47        if fade <= 0.0 || now >= fade_start + fade {
48            return None;
49        }
50        frame.continuous(bounds);
51        Some(1.0 - ((now - fade_start) / fade) as f32)
52    }
53
54    /// Paint the transient highlight behind the option that was selected.
55    pub fn paint_feedback(
56        self,
57        frame: &mut Frame<'_>,
58        choice: u64,
59        bounds: Rect,
60        ink: Color,
61        now: f64,
62    ) {
63        if self.choice == Some(choice) {
64            let elapsed = ((now - self.start) / Self::HOLD).clamp(0.0, 1.0) as f32;
65            let opacity = if frame.reduced_motion() {
66                0.14
67            } else {
68                0.22 - 0.08 * elapsed
69            };
70            frame.paint_rect(bounds, 10.0, ink.opacity(opacity));
71        }
72    }
73}
74
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
76pub enum OverlayKind {
77    #[default]
78    Popover,
79    Menu,
80    Dialog,
81    BottomSheet,
82    SideSheet,
83    /// A modal surface entering from the left edge.
84    LeftSideSheet,
85}
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub enum OverlayStyle {
88    #[default]
89    Material3,
90    AngularMaterial,
91    AngularDatepicker,
92    AngularTimepicker,
93    /// Surface and content geometry for an expanded modal navigation rail.
94    NavigationRail,
95    /// Material modal navigation drawer, with leading edge attached to the viewport.
96    NavigationDrawer,
97    /// Android Material popup menu surface.
98    AndroidMenu,
99}
100
101/// Which implicit gestures may dismiss an overlay. Explicit actions may still
102/// close it regardless of this setting.
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104pub enum OverlayDismissPolicy {
105    #[default]
106    EscapeOrOutside,
107    EscapeOnly,
108    OutsideOnly,
109    ExplicitOnly,
110}
111impl OverlayDismissPolicy {
112    fn escape(self) -> bool {
113        matches!(self, Self::EscapeOrOutside | Self::EscapeOnly)
114    }
115    fn outside(self) -> bool {
116        matches!(self, Self::EscapeOrOutside | Self::OutsideOnly)
117    }
118}
119
120#[derive(Clone, Copy)]
121pub(crate) struct OverlayPhase {
122    id: u64,
123    open: bool,
124    kind: OverlayKind,
125}
126#[derive(Clone, Copy)]
127pub enum OverlaySection {
128    Headline,
129    Content,
130    Actions,
131}
132
133#[derive(Clone, Copy)]
134struct BottomSheetNestedTouch {
135    origin: f32,
136    last: f32,
137    last_time: f64,
138    velocity: f32,
139    claimed: bool,
140    moved_sheet: bool,
141}
142fn sheet_detent(current: f32, collapsed: f32, half: Option<f32>, xvel: f32, yvel: f32) -> f32 {
143    let mut detents = vec![0.0];
144    if let Some(value) = half {
145        detents.push(value);
146    }
147    detents.push(collapsed);
148    if yvel < -500.0 && yvel.abs() > xvel.abs() {
149        detents
150            .iter()
151            .rev()
152            .copied()
153            .find(|&v| v < current - 0.01)
154            .unwrap_or(0.0)
155    } else if yvel > 500.0 && yvel.abs() > xvel.abs() {
156        detents
157            .iter()
158            .copied()
159            .find(|&v| v > current + 0.01)
160            .unwrap_or(collapsed)
161    } else {
162        detents
163            .iter()
164            .copied()
165            .min_by(|a, b| (a - current).abs().total_cmp(&(b - current).abs()))
166            .unwrap_or(0.0)
167    }
168}
169// Material Android distinguishes handle release from nested-scroll stop.
170fn sheet_handle_detent(
171    current: f32,
172    collapsed: f32,
173    half: Option<f32>,
174    expanded_top: f32,
175    xvel: f32,
176    yvel: f32,
177) -> f32 {
178    if yvel < 0.0 {
179        return half.filter(|&h| current > h).unwrap_or(0.0);
180    }
181    if yvel == 0.0 || xvel.abs() > yvel.abs() {
182        if let Some(h) = half {
183            if current < h {
184                return if expanded_top + current < (current - collapsed).abs() {
185                    0.0
186                } else {
187                    h
188                };
189            }
190            return if (current - h).abs() < (current - collapsed).abs() {
191                h
192            } else {
193                collapsed
194            };
195        }
196        return if current < (current - collapsed).abs() {
197            0.0
198        } else {
199            collapsed
200        };
201    }
202    half.filter(|&h| (current - h).abs() < (current - collapsed).abs())
203        .unwrap_or(collapsed)
204}
205/// Caller-owned overlay lifetime and focus return point.
206#[derive(Default, Clone)]
207pub struct OverlayState {
208    pub open: bool,
209    pub kind: OverlayKind,
210    pub style: OverlayStyle,
211    pub initial_focus: Option<u64>,
212    pub dismiss_policy: OverlayDismissPolicy,
213    /// Accessible title and description for a modal dialog.
214    pub accessible_title: Option<String>,
215    pub accessible_description: Option<String>,
216    /// Fill the host viewport when this overlay is a dialog.
217    pub fullscreen: bool,
218    /// Temporarily suspend this overlay while a separately rendered child modal
219    /// owns input. The caller clears this when the child has closed.
220    pub suspended: bool,
221    pub transform_origin: Option<[f32; 2]>,
222    /// Allow dragging a Material bottom sheet from its top 32 logical pixels.
223    pub drag_to_dismiss: bool,
224    /// When set, a non-modal sheet settles between this visible peek height and full height.
225    pub bottom_sheet_peek: Option<f32>,
226    /// Current target detent for a sheet with a peek height.
227    pub bottom_sheet_expanded: bool,
228    /// Optional visible viewport-height fraction for an intermediate detent.
229    pub bottom_sheet_half_ratio: Option<f32>,
230    /// Whether the current target is the intermediate detent.
231    pub bottom_sheet_half_expanded: bool,
232    /// Offset of the scrollable region below the sheet's top; None disables nested scrolling.
233    pub bottom_sheet_content_top: Option<f32>,
234    /// Total scrollable content height in logical pixels.
235    pub bottom_sheet_content_height: f32,
236    /// Current nested content scroll position.
237    pub bottom_sheet_scroll_offset: f32,
238    nested_touch: Option<BottomSheetNestedTouch>,
239    nested_physics: crate::scroll::ScrollPhysics,
240    drag_origin: Option<(f32, f32)>,
241    side_drag_origin: Option<(f32, f32, f32, bool)>,
242    drag_last_motion: Option<(f64, [f32; 2])>,
243    drag_velocity: [f32; 2],
244    drag_displacement: f32,
245    drag_settle: Option<(f64, f32, f32)>,
246    drag_close_offset: f32,
247    geometry: crate::timing::Tween,
248    surface: crate::timing::Tween,
249    scrim: crate::timing::Tween,
250    content: crate::timing::Tween,
251    was_open: bool,
252    sampled_open: bool,
253    opened_with_keyboard: bool,
254    restore: Option<u64>,
255}
256
257impl OverlayState {
258    fn sample(&mut self, time: f64, reduced: bool) -> [f32; 4] {
259        use crate::timing::{Easing, TweenSpec};
260        let target = f32::from(self.open);
261        if self.style == OverlayStyle::AngularMaterial && self.kind == OverlayKind::BottomSheet {
262            let geometry = self.geometry.sample(
263                time,
264                target,
265                TweenSpec::new(0.195, Easing::Cubic([0.0, 0.0, 0.2, 1.0])),
266                TweenSpec::new(0.375, Easing::Cubic([0.4, 0.0, 1.0, 1.0])),
267                reduced,
268            );
269            let scrim = self.scrim.sample(
270                time,
271                target,
272                TweenSpec::new(0.4, Easing::Backdrop),
273                TweenSpec::new(0.4, Easing::Backdrop),
274                reduced,
275            );
276            let visible = f32::from(self.open || self.geometry.moving());
277            return [geometry, visible, scrim, visible];
278        }
279        if matches!(
280            self.style,
281            OverlayStyle::AngularDatepicker | OverlayStyle::AngularTimepicker
282        ) {
283            let spec = TweenSpec::new(0.120, Easing::StandardDecelerate);
284            if self.open != self.sampled_open {
285                if !self.open {
286                    self.geometry.sample(time, 1.0, spec, spec, reduced);
287                }
288                let interrupted = !self.open && self.geometry.moving();
289                let initial = if self.open || interrupted { 0.0 } else { 1.0 };
290                self.geometry = crate::timing::Tween::at(initial);
291                self.surface = crate::timing::Tween::at(initial);
292                self.sampled_open = self.open;
293            }
294            let geometry = self.geometry.sample(
295                time,
296                target,
297                spec,
298                TweenSpec::new(0.0, Easing::Linear),
299                reduced,
300            );
301            let alpha = self.surface.sample(
302                time,
303                target,
304                spec,
305                TweenSpec::new(0.100, Easing::Linear),
306                reduced,
307            );
308            return [if self.open { geometry } else { 1.0 }, alpha, 0.0, alpha];
309        }
310        if matches!(
311            self.style,
312            OverlayStyle::AngularMaterial | OverlayStyle::AndroidMenu
313        ) {
314            let menu = self.kind == OverlayKind::Menu;
315            if menu {
316                if self.open != self.sampled_open {
317                    let interrupted = if !self.open && self.sampled_open {
318                        let spec = TweenSpec::new(0.120, Easing::StandardDecelerate);
319                        self.geometry.sample(time, 1.0, spec, spec, reduced);
320                        self.geometry.moving()
321                    } else {
322                        false
323                    };
324                    // Angular's animationcancel notification detaches a panel
325                    // closed before its enter animation finishes.
326                    let initial = if self.open || interrupted { 0.0 } else { 1.0 };
327                    self.geometry = crate::timing::Tween::at(initial);
328                    self.surface = crate::timing::Tween::at(initial);
329                    self.sampled_open = self.open;
330                }
331                self.scrim = crate::timing::Tween::at(0.0);
332                self.content = crate::timing::Tween::at(0.0);
333            }
334            let enter = if menu { 0.120 } else { 0.150 };
335            let exit = if menu { 0.100 } else { 0.075 };
336            let g = self.geometry.sample(
337                time,
338                target,
339                TweenSpec::new(enter, Easing::StandardDecelerate),
340                TweenSpec::new(0.0, Easing::Linear),
341                reduced,
342            );
343            let a = self.surface.sample(
344                time,
345                target,
346                TweenSpec::new(
347                    enter,
348                    if menu {
349                        Easing::StandardDecelerate
350                    } else {
351                        Easing::Linear
352                    },
353                ),
354                TweenSpec {
355                    delay: if menu { 0.025 } else { 0.0 },
356                    duration: exit,
357                    easing: Easing::Linear,
358                },
359                reduced,
360            );
361            let scrim = if menu {
362                0.0
363            } else {
364                self.scrim.sample(
365                    time,
366                    target,
367                    TweenSpec::new(0.4, Easing::Backdrop),
368                    TweenSpec::new(0.4, Easing::Backdrop),
369                    reduced,
370                )
371            };
372            return [if self.open { g } else { 1.0 }, a, scrim, a];
373        }
374        let geometry = self.geometry.sample(
375            time,
376            target,
377            TweenSpec::new(0.5, Easing::Emphasized),
378            TweenSpec::new(0.15, Easing::EmphasizedAccelerate),
379            reduced,
380        );
381        let surface = self.surface.sample(
382            time,
383            target,
384            TweenSpec::new(0.05, Easing::Linear),
385            TweenSpec {
386                delay: 0.1,
387                duration: 0.05,
388                easing: Easing::Linear,
389            },
390            reduced,
391        );
392        let scrim = self.scrim.sample(
393            time,
394            target,
395            TweenSpec::new(0.5, Easing::Linear),
396            TweenSpec::new(0.15, Easing::Linear),
397            reduced,
398        );
399        let content = self.content.sample(
400            time,
401            target,
402            TweenSpec {
403                delay: 0.05,
404                duration: 0.2,
405                easing: Easing::Linear,
406            },
407            TweenSpec::new(0.1, Easing::Linear),
408            reduced,
409        );
410        [geometry, surface, scrim, content]
411    }
412    pub(crate) fn moving(&self) -> bool {
413        self.geometry.moving()
414            || self.surface.moving()
415            || self.scrim.moving()
416            || self.content.moving()
417    }
418}
419
420impl Frame<'_> {
421    /// Source Web menu entry/exit stagger; each item retargets from its presentation.
422    pub fn overlay_item(&mut self, index: usize, count: usize, build: impl FnOnce(&mut Self)) {
423        use crate::timing::{Easing, TweenSpec};
424        if let Some(phase) = self.overlay_phase.filter(|p| p.kind == OverlayKind::Menu) {
425            let count = count.clamp(1, 64);
426            let index = index.min(count - 1);
427            let enter = TweenSpec {
428                delay: 0.250 / count as f64 * index as f64,
429                duration: 0.250,
430                easing: Easing::Linear,
431            };
432            let exit = TweenSpec {
433                delay: 0.050 + 0.050 / count as f64 * (count - 1 - index) as f64,
434                duration: 0.050,
435                easing: Easing::Linear,
436            };
437            let alpha = self.ui.motion.tween(
438                phase.id,
439                100 + index as u8,
440                f32::from(phase.open),
441                0.0,
442                enter,
443                exit,
444            );
445            self.with_opacity(alpha, build);
446        } else {
447            build(self);
448        }
449    }
450    pub fn overlay_section(&mut self, section: OverlaySection, build: impl FnOnce(&mut Self)) {
451        use crate::timing::{Easing, TweenSpec};
452        if let Some(phase) = self.overlay_phase.filter(|p| p.kind == OverlayKind::Dialog) {
453            let (property, delay, duration, exit) = match section {
454                OverlaySection::Headline => (80, 0.050, 0.200, 0.100),
455                OverlaySection::Content => (81, 0.050, 0.200, 0.100),
456                OverlaySection::Actions => (82, 0.150, 0.150, 0.050),
457            };
458            let alpha = self.ui.motion.tween(
459                phase.id,
460                property,
461                f32::from(phase.open),
462                0.0,
463                TweenSpec {
464                    delay,
465                    duration,
466                    easing: Easing::Linear,
467                },
468                TweenSpec::new(exit, Easing::Linear),
469            );
470            self.with_opacity(alpha, build);
471        } else {
472            build(self);
473        }
474    }
475    /// Modal surface: disable background while `open`, then call this after the trigger.
476    /// Exit visuals never receive input; focus is restored immediately on dismissal.
477    pub fn overlay(
478        &mut self,
479        id: u64,
480        state: &mut OverlayState,
481        bounds: Rect,
482        modal: bool,
483        mut build: impl FnMut(&mut Self, &mut bool),
484    ) {
485        if state.open && !state.was_open {
486            state.opened_with_keyboard = self.ui.keyboard_focus || self.input.key.is_some();
487            state.restore = self.ui.focused;
488            self.ui.focused = None;
489        }
490        let timed = matches!(state.kind, OverlayKind::Menu | OverlayKind::Dialog)
491            || state.style == OverlayStyle::AngularMaterial
492                && state.kind == OverlayKind::BottomSheet
493            || matches!(
494                state.style,
495                OverlayStyle::AngularDatepicker | OverlayStyle::AngularTimepicker
496            );
497        let mut values = if timed {
498            state.sample(self.ui.time, self.reduced_motion())
499        } else {
500            let position = self.spatial(id, 21, f32::from(state.open), 0.0);
501            let alpha = self.animate(id, 20, f32::from(state.open), 0.0);
502            [position, alpha, alpha, alpha]
503        };
504        let kind = state.kind;
505        let fullscreen = kind == OverlayKind::Dialog && state.fullscreen;
506        let full = if fullscreen { self.viewport() } else { bounds };
507        let angular = matches!(
508            state.style,
509            OverlayStyle::AngularMaterial
510                | OverlayStyle::AndroidMenu
511                | OverlayStyle::AngularDatepicker
512                | OverlayStyle::AngularTimepicker
513        );
514        let datepicker = matches!(
515            state.style,
516            OverlayStyle::AngularDatepicker | OverlayStyle::AngularTimepicker
517        );
518        let timepicker = state.style == OverlayStyle::AngularTimepicker;
519        let draggable = state.drag_to_dismiss
520            && kind == OverlayKind::BottomSheet
521            && !angular
522            && !state.suspended;
523        let side_draggable = modal
524            && matches!(kind, OverlayKind::SideSheet | OverlayKind::LeftSideSheet)
525            && !angular
526            && !state.suspended
527            && (state.drag_to_dismiss || state.dismiss_policy.outside());
528        let side_dir = if kind == OverlayKind::SideSheet {
529            1.0
530        } else {
531            -1.0
532        };
533        let collapsed_offset = state
534            .bottom_sheet_peek
535            .filter(|v| v.is_finite())
536            .map(|peek| (full.height - peek.clamp(0.0, full.height)).max(0.0));
537        let viewport = self.viewport();
538        let half_offset = state
539            .bottom_sheet_half_ratio
540            .filter(|r| r.is_finite() && *r > 0.0 && *r < 1.0)
541            .and_then(|ratio| {
542                let offset = viewport.y + viewport.height * (1.0 - ratio) - full.y;
543                collapsed_offset
544                    .filter(|&collapsed| offset > 0.01 && offset < collapsed - 0.01)
545                    .map(|_| offset)
546            });
547        let target_detent = if state.bottom_sheet_expanded {
548            0.0
549        } else if state.bottom_sheet_half_expanded {
550            half_offset.unwrap_or(collapsed_offset.unwrap_or(0.0))
551        } else {
552            collapsed_offset.unwrap_or(0.0)
553        };
554        if draggable && !state.open && state.was_open && collapsed_offset.is_some() {
555            state.drag_close_offset = state.drag_displacement;
556        }
557        if draggable && state.open {
558            if !state.was_open
559                && state.drag_close_offset == 0.0
560                && let Some(collapsed) = collapsed_offset
561            {
562                state.drag_displacement = target_detent.min(collapsed);
563            }
564            if state.drag_close_offset > 0.0 {
565                state.drag_displacement = state.drag_close_offset * values[0].clamp(0.0, 1.0);
566                state.drag_close_offset = 0.0;
567                state.drag_settle = Some((self.ui.time, state.drag_displacement, target_detent));
568            }
569            // The caller can change the target or sheet geometry while it is open.
570            // Retarget from the current position without disturbing an active drag.
571            if collapsed_offset.is_some()
572                && state.was_open
573                && state.drag_origin.is_none()
574                && state.nested_touch.is_none()
575                && !self.input.pressed
576            {
577                match state.drag_settle {
578                    Some((_, _, target)) if (target - target_detent).abs() > 0.01 => {
579                        state.drag_settle =
580                            Some((self.ui.time, state.drag_displacement, target_detent));
581                    }
582                    None if (state.drag_displacement - target_detent).abs() > 0.01 => {
583                        state.drag_settle =
584                            Some((self.ui.time, state.drag_displacement, target_detent));
585                    }
586                    _ => {}
587                }
588            }
589            if let Some((started, from, target)) = state.drag_settle {
590                let elapsed = (self.ui.time - started).max(0.0);
591                let factor = if self.reduced_motion() {
592                    0.0
593                } else {
594                    ((1.0 + 18.0 * elapsed) * (-18.0 * elapsed).exp()) as f32
595                };
596                state.drag_displacement = target + (from - target) * factor;
597                if factor < 0.001 {
598                    state.drag_settle = None;
599                    state.drag_displacement = target;
600                } else {
601                    self.ui.continuous = true;
602                }
603            }
604            if self.input.pressed
605                && values[0] > 0.95
606                && let Some(point) = self.input.pointer
607            {
608                let top = full.y + full.height * (1.0 - values[0]) + state.drag_displacement;
609                if point[0] >= full.x
610                    && point[0] < full.x + full.width
611                    && point[1] >= top
612                    && point[1] < top + 32.0
613                {
614                    state.drag_origin = Some((point[1], state.drag_displacement));
615                    state.drag_last_motion = Some((self.ui.time, point));
616                    state.drag_velocity = [0.0; 2];
617                    state.drag_settle = None;
618                    self.ui.active = None;
619                }
620            }
621            if let Some((origin, initial)) = state.drag_origin {
622                if let Some(point) = self.input.pointer {
623                    state.drag_displacement = (initial + point[1] - origin)
624                        .clamp(0.0, collapsed_offset.unwrap_or(full.height));
625                    if let Some((last_time, last_point)) = state.drag_last_motion
626                        && point != last_point
627                    {
628                        let dt = self.ui.time - last_time;
629                        if dt > 0.0 {
630                            state.drag_velocity = [
631                                ((point[0] - last_point[0]) / dt as f32).clamp(-10000.0, 10000.0),
632                                ((point[1] - last_point[1]) / dt as f32).clamp(-10000.0, 10000.0),
633                            ];
634                        }
635                        state.drag_last_motion = Some((self.ui.time, point));
636                    }
637                }
638                if self.input.cancelled || self.input.blurred || self.input.released {
639                    state.drag_origin = None;
640                    self.ui.active = None;
641                    let [xvel, yvel] = if state
642                        .drag_last_motion
643                        .is_some_and(|(last, _)| self.ui.time - last <= 0.12)
644                    {
645                        state.drag_velocity
646                    } else {
647                        [0.0; 2]
648                    };
649                    state.drag_last_motion = None;
650                    state.drag_velocity = [0.0; 2];
651                    // Material Android's default significant velocity is 500 px/s; its
652                    // hide projection uses 0.1 s friction and a half-peek threshold.
653                    let flick = yvel > 500.0
654                        && yvel.abs() > xvel.abs()
655                        && state.drag_displacement + yvel * 0.1 > full.height * 0.5;
656                    let distance = state.drag_displacement >= full.height * 0.4 && yvel >= -50.0;
657                    if let Some(collapsed) = collapsed_offset {
658                        let current = state.drag_displacement;
659                        let target = if self.input.cancelled || self.input.blurred {
660                            target_detent
661                        } else {
662                            sheet_handle_detent(
663                                current,
664                                collapsed,
665                                half_offset,
666                                full.y - viewport.y,
667                                xvel,
668                                yvel,
669                            )
670                        };
671                        state.bottom_sheet_expanded = target <= 0.01;
672                        state.bottom_sheet_half_expanded =
673                            half_offset.is_some_and(|half| (target - half).abs() < 0.01);
674                        state.drag_settle = Some((self.ui.time, current, target));
675                        self.ui.continuous = true;
676                    } else if !self.input.cancelled && !self.input.blurred && (distance || flick) {
677                        state.open = false;
678                        state.drag_close_offset = state.drag_displacement;
679                        state.drag_displacement = 0.0;
680                        state.drag_settle = None;
681                        values = [
682                            self.spatial(id, 21, 0.0, 0.0),
683                            self.animate(id, 20, 0.0, 0.0),
684                            values[2],
685                            values[3],
686                        ];
687                        self.ui.continuous = true;
688                    } else {
689                        state.drag_settle = Some((self.ui.time, state.drag_displacement, 0.0));
690                        self.ui.continuous = true;
691                    }
692                }
693            }
694        }
695        let mut side_drag_claimed = false;
696        if side_draggable && state.open {
697            if state.drag_close_offset > 0.0 {
698                state.drag_displacement = state.drag_close_offset * values[0].clamp(0.0, 1.0);
699                state.drag_close_offset = 0.0;
700                state.drag_settle = Some((self.ui.time, state.drag_displacement, 0.0));
701            }
702            if let Some((started, from, target)) = state.drag_settle {
703                let elapsed = (self.ui.time - started).max(0.0);
704                let factor = if self.reduced_motion() {
705                    0.0
706                } else {
707                    ((1.0 + 18.0 * elapsed) * (-18.0 * elapsed).exp()) as f32
708                };
709                state.drag_displacement = target + (from - target) * factor;
710                if factor < 0.001 {
711                    state.drag_settle = None;
712                    state.drag_displacement = target;
713                } else {
714                    self.ui.continuous = true;
715                }
716            }
717            if self.input.pressed
718                && values[0] > 0.95
719                && let Some(point) = self.input.pointer
720            {
721                let cur_x = if kind == OverlayKind::SideSheet {
722                    full.x + full.width * (1.0 - values[0]) + state.drag_displacement
723                } else {
724                    full.x - full.width * (1.0 - values[0]) - state.drag_displacement
725                };
726                let cur_rect = Rect { x: cur_x, ..full };
727                if cur_rect.contains(point) {
728                    let already_displaced = state.drag_displacement > 0.01;
729                    state.side_drag_origin = Some((
730                        point[0],
731                        point[1],
732                        state.drag_displacement,
733                        already_displaced,
734                    ));
735                    state.drag_last_motion = Some((self.ui.time, point));
736                    state.drag_velocity = [0.0; 2];
737                    state.drag_settle = None;
738                    if already_displaced {
739                        self.ui.active = None;
740                    }
741                }
742            }
743            if let Some((ox, oy, initial, mut claimed)) = state.side_drag_origin {
744                if let Some(point) = self.input.pointer {
745                    let dx = point[0] - ox;
746                    let dy = point[1] - oy;
747                    if !claimed && dx * side_dir > 6.0 && dx.abs() > dy.abs() {
748                        claimed = true;
749                        self.ui.active = None;
750                    }
751                    if claimed {
752                        state.drag_displacement = (initial + dx * side_dir).clamp(0.0, full.width);
753                        self.ui.continuous = true;
754                    }
755                    if let Some((last_time, last_point)) = state.drag_last_motion
756                        && point != last_point
757                    {
758                        let dt = self.ui.time - last_time;
759                        if dt > 0.0 {
760                            state.drag_velocity = [
761                                ((point[0] - last_point[0]) / dt as f32).clamp(-10000.0, 10000.0),
762                                ((point[1] - last_point[1]) / dt as f32).clamp(-10000.0, 10000.0),
763                            ];
764                        }
765                        state.drag_last_motion = Some((self.ui.time, point));
766                    }
767                }
768                side_drag_claimed = claimed;
769                if self.input.cancelled || self.input.blurred || self.input.released {
770                    state.side_drag_origin = None;
771                    let [xvel, yvel] = if state
772                        .drag_last_motion
773                        .is_some_and(|(last, _)| self.ui.time - last <= 0.12)
774                    {
775                        state.drag_velocity
776                    } else {
777                        [0.0; 2]
778                    };
779                    state.drag_last_motion = None;
780                    state.drag_velocity = [0.0; 2];
781                    if claimed {
782                        self.ui.active = None;
783                        let outward_vel = xvel * side_dir;
784                        let flick = outward_vel > 500.0
785                            && xvel.abs() > yvel.abs()
786                            && state.drag_displacement + outward_vel * 0.1 > full.width * 0.5;
787                        let distance =
788                            state.drag_displacement >= full.width * 0.4 && outward_vel >= -50.0;
789                        if !self.input.cancelled && !self.input.blurred && (distance || flick) {
790                            state.open = false;
791                            state.drag_close_offset = state.drag_displacement;
792                            state.drag_displacement = 0.0;
793                            state.drag_settle = None;
794                            values = [
795                                self.spatial(id, 21, 0.0, 0.0),
796                                self.animate(id, 20, 0.0, 0.0),
797                                values[2],
798                                values[3],
799                            ];
800                            self.ui.continuous = true;
801                        } else {
802                            state.drag_settle = Some((self.ui.time, state.drag_displacement, 0.0));
803                            self.ui.continuous = true;
804                        }
805                    }
806                } else {
807                    state.side_drag_origin = Some((ox, oy, initial, claimed));
808                }
809            }
810        }
811        let mut nested_claimed = false;
812        if draggable
813            && state.open
814            && let (Some(collapsed), Some(content_top)) = (
815                collapsed_offset,
816                state
817                    .bottom_sheet_content_top
818                    .filter(|v| v.is_finite() && *v >= 32.0 && *v < full.height),
819            )
820        {
821            let nested_height = (full.height - content_top).max(0.0);
822            let max = (state.bottom_sheet_content_height - nested_height).max(0.0);
823            if (state.nested_physics.offset - state.bottom_sheet_scroll_offset).abs() > 0.1
824                && state.nested_touch.is_none()
825            {
826                state.nested_physics.cancel();
827                state.nested_physics.offset = state.bottom_sheet_scroll_offset.clamp(0.0, max);
828            }
829            if state.nested_touch.is_none()
830                && state
831                    .nested_physics
832                    .advance(self.ui.time, max, self.reduced_motion())
833            {
834                self.ui.continuous = true;
835            }
836            state.bottom_sheet_scroll_offset = state.nested_physics.offset.clamp(0.0, max);
837            let sheet_top = full.y + full.height * (1.0 - values[0]) + state.drag_displacement;
838            if self.input.pressed
839                && values[0] > 0.95
840                && let Some(point) = self.input.pointer
841            {
842                if point[0] >= full.x
843                    && point[0] < full.x + full.width
844                    && point[1] >= sheet_top + content_top
845                    && point[1] < (sheet_top + full.height).min(viewport.y + viewport.height)
846                {
847                    state.nested_touch = Some(BottomSheetNestedTouch {
848                        origin: point[1],
849                        last: point[1],
850                        last_time: self.ui.time,
851                        velocity: 0.0,
852                        claimed: false,
853                        moved_sheet: false,
854                    });
855                    state.nested_physics.cancel();
856                    state.drag_settle = None;
857                }
858            }
859            if let Some(mut touch) = state.nested_touch {
860                if let Some(point) = self.input.pointer {
861                    let delta = touch.last - point[1];
862                    touch.claimed |= (point[1] - touch.origin).abs() > 6.0;
863                    if touch.claimed && delta.abs() > 0.01 {
864                        let dt = (self.ui.time - touch.last_time).clamp(0.001, 0.15) as f32;
865                        touch.velocity = (delta / dt).clamp(-8000.0, 8000.0);
866                        if delta > 0.0 {
867                            let sheet = delta.min(state.drag_displacement);
868                            state.drag_displacement -= sheet;
869                            touch.moved_sheet |= sheet > 0.0;
870                            state.bottom_sheet_scroll_offset =
871                                (state.bottom_sheet_scroll_offset + delta - sheet).clamp(0.0, max);
872                        } else {
873                            let scroll = (-delta).min(state.bottom_sheet_scroll_offset);
874                            state.bottom_sheet_scroll_offset -= scroll;
875                            let before = state.drag_displacement;
876                            state.drag_displacement = (before - delta - scroll).min(collapsed);
877                            touch.moved_sheet |= state.drag_displacement > before;
878                        }
879                        state.nested_physics.offset = state.bottom_sheet_scroll_offset;
880                        self.ui.active = None;
881                    }
882                    if delta.abs() > 0.01 {
883                        touch.last_time = self.ui.time;
884                    }
885                    touch.last = point[1];
886                }
887                nested_claimed = touch.claimed;
888                if self.input.released || self.input.cancelled || self.input.blurred {
889                    if touch.claimed {
890                        if touch.moved_sheet
891                            && (state.drag_displacement > 0.01
892                                || self.input.cancelled
893                                || self.input.blurred)
894                        {
895                            // BottomSheetBehavior.onStopNestedScroll uses the last touch
896                            // direction, not the child's later non-touch fling velocity.
897                            let current = state.drag_displacement;
898                            let target = if self.input.cancelled || self.input.blurred {
899                                target_detent
900                            } else if current <= 0.01 {
901                                0.0
902                            } else if touch.velocity > 0.0 {
903                                half_offset.filter(|half| current > *half).unwrap_or(0.0)
904                            } else if touch.velocity < 0.0 {
905                                half_offset
906                                    .filter(|half| {
907                                        (current - half).abs() < (current - collapsed).abs()
908                                    })
909                                    .unwrap_or(collapsed)
910                            } else {
911                                sheet_detent(current, collapsed, half_offset, 0.0, 0.0)
912                            };
913                            state.bottom_sheet_expanded = target <= 0.01;
914                            state.bottom_sheet_half_expanded =
915                                half_offset.is_some_and(|half| (target - half).abs() < 0.01);
916                            state.drag_settle =
917                                Some((self.ui.time, state.drag_displacement, target));
918                            self.ui.continuous = true;
919                        } else if !self.input.cancelled
920                            && !self.input.blurred
921                            && self.ui.time - touch.last_time <= 0.12
922                        {
923                            state.bottom_sheet_expanded = true;
924                            state.bottom_sheet_half_expanded = false;
925                            state.nested_physics.fling_from_velocity(
926                                touch.velocity,
927                                self.ui.time,
928                                self.reduced_motion(),
929                            );
930                            self.ui.continuous = true;
931                        }
932                    }
933                    state.nested_touch = None;
934                } else {
935                    state.nested_touch = Some(touch);
936                }
937            }
938        } else if !state.open {
939            state.nested_touch = None;
940            state.nested_physics.cancel();
941        }
942        let drag_offset = if draggable && state.open {
943            state.drag_displacement
944        } else if draggable {
945            state.drag_close_offset * values[0].clamp(0.0, 1.0)
946        } else {
947            0.0
948        };
949        let side_drag_offset = if side_draggable && state.open {
950            state.drag_displacement
951        } else if side_draggable {
952            state.drag_close_offset * values[0].clamp(0.0, 1.0)
953        } else {
954            0.0
955        };
956        if !state.open && values[0] < 0.001 {
957            state.drag_close_offset = 0.0;
958            state.drag_displacement = 0.0;
959            state.drag_settle = None;
960            state.drag_origin = None;
961            state.side_drag_origin = None;
962            state.drag_last_motion = None;
963            state.drag_velocity = [0.0; 2];
964        }
965        let posed = |position: f32| {
966            if fullscreen {
967                full
968            } else if angular && kind == OverlayKind::BottomSheet {
969                Rect {
970                    y: full.y + full.height * (1.0 - position),
971                    ..full
972                }
973            } else if angular {
974                full
975            } else {
976                match kind {
977                    OverlayKind::Menu => Rect {
978                        height: full.height * (0.35 + 0.65 * position),
979                        ..full
980                    },
981                    OverlayKind::Dialog => Rect {
982                        y: full.y - 50.0 * (1.0 - position),
983                        height: full.height * (0.35 + 0.65 * position),
984                        ..full
985                    },
986                    OverlayKind::BottomSheet => Rect {
987                        y: full.y + full.height * (1.0 - position) + drag_offset,
988                        ..full
989                    },
990                    OverlayKind::SideSheet => Rect {
991                        x: full.x + full.width * (1.0 - position) + side_drag_offset,
992                        ..full
993                    },
994                    OverlayKind::LeftSideSheet => Rect {
995                        x: full.x - full.width * (1.0 - position) - side_drag_offset,
996                        ..full
997                    },
998                    OverlayKind::Popover => Rect {
999                        y: full.y + 8.0 * (1.0 - position),
1000                        ..full
1001                    },
1002                }
1003            }
1004        };
1005        if state.open
1006            && !state.suspended
1007            && (state.dismiss_policy.escape() && self.pressed_key(Key::Escape)
1008                || angular && kind == OverlayKind::Menu && self.pressed_key(Key::Tab)
1009                || state.dismiss_policy.outside()
1010                    && self.input.pressed
1011                    && self
1012                        .input
1013                        .pointer
1014                        .is_some_and(|p| !posed(values[0]).contains(p)))
1015        {
1016            state.open = false;
1017            self.ui.active = None;
1018            self.ui.continuous = true;
1019            values = if timed {
1020                state.sample(self.ui.time, self.reduced_motion())
1021            } else {
1022                let position = self.spatial(id, 21, 0.0, 0.0);
1023                let alpha = self.animate(id, 20, 0.0, 0.0);
1024                [position, alpha, alpha, alpha]
1025            };
1026        }
1027        if timed {
1028            self.ui.continuous |= state.moving();
1029        }
1030        let bounds = posed(values[0]);
1031        let alpha = values[1];
1032        if timed && !angular {
1033            values[3] = 1.0;
1034        }
1035        if state.open || state.was_open {
1036            self.ui.next_focus_order.clear();
1037        }
1038        if alpha > 0.001 || state.open {
1039            let t = self.ui.theme;
1040            if modal {
1041                self.rect(
1042                    self.viewport(),
1043                    0.0,
1044                    Color(0, 0, 0, 255).opacity(0.32 * values[2]),
1045                );
1046                for node in &mut self.ui.semantics {
1047                    node.enabled = false;
1048                }
1049            }
1050            let start = self.commands.len();
1051            let semantics_start = self.ui.semantics.len();
1052            let previous_phase = self.overlay_phase;
1053            self.overlay_phase = if angular {
1054                None
1055            } else {
1056                Some(OverlayPhase {
1057                    id,
1058                    open: state.open,
1059                    kind: state.kind,
1060                })
1061            };
1062            let origin = if let Some(origin) = state
1063                .transform_origin
1064                .filter(|p| p.iter().all(|v| v.is_finite()))
1065            {
1066                origin
1067            } else if kind == OverlayKind::Menu {
1068                [bounds.x, bounds.y]
1069            } else {
1070                [
1071                    bounds.x + bounds.width / 2.0,
1072                    bounds.y + bounds.height / 2.0,
1073                ]
1074            };
1075            let scale = if angular
1076                && !fullscreen
1077                && !timepicker
1078                && matches!(kind, OverlayKind::Menu | OverlayKind::Dialog)
1079            {
1080                0.8 + 0.2 * values[0]
1081            } else {
1082                1.0
1083            };
1084            if datepicker {
1085                self.commands.push(DrawCommand::PushScaleY {
1086                    origin: bounds.y,
1087                    scale: 0.8 + 0.2 * values[0],
1088                });
1089            }
1090            let previous_nested_scroll = self.overlay_nested_scroll;
1091            self.overlay_nested_scroll = state.bottom_sheet_scroll_offset;
1092            self.with_scale(origin, scale, |f| {
1093                let radius = if fullscreen {
1094                    0.0
1095                } else if angular {
1096                    if kind == OverlayKind::Menu || timepicker {
1097                        4.0
1098                    } else if kind == OverlayKind::Popover {
1099                        16.0
1100                    } else if kind == OverlayKind::BottomSheet {
1101                        0.0
1102                    } else {
1103                        28.0
1104                    }
1105                } else if matches!(kind, OverlayKind::BottomSheet | OverlayKind::Dialog) {
1106                    28.0
1107                } else if matches!(kind, OverlayKind::SideSheet | OverlayKind::LeftSideSheet) {
1108                    16.0
1109                } else {
1110                    20.0
1111                };
1112                if angular
1113                    && (kind == OverlayKind::Menu || timepicker || kind == OverlayKind::BottomSheet)
1114                {
1115                    f.elevation(
1116                        bounds,
1117                        radius,
1118                        if state.style == OverlayStyle::AndroidMenu {
1119                            3
1120                        } else {
1121                            2
1122                        },
1123                    );
1124                }
1125                let surface_color = if state.style == OverlayStyle::AndroidMenu {
1126                    t.surface_high
1127                } else if angular {
1128                    if kind == OverlayKind::BottomSheet {
1129                        t.surface_low
1130                    } else if kind == OverlayKind::Menu || timepicker {
1131                        t.control
1132                    } else if kind == OverlayKind::Popover {
1133                        t.hovered
1134                    } else {
1135                        t.background
1136                    }
1137                } else if kind == OverlayKind::Dialog {
1138                    t.surface_high
1139                } else if state.style == OverlayStyle::NavigationRail {
1140                    t.background
1141                } else if state.style == OverlayStyle::NavigationDrawer
1142                    || matches!(
1143                        kind,
1144                        OverlayKind::BottomSheet
1145                            | OverlayKind::SideSheet
1146                            | OverlayKind::LeftSideSheet
1147                    )
1148                {
1149                    t.surface_low
1150                } else {
1151                    t.background.mix(t.secondary, 0.35)
1152                };
1153                if !angular && !fullscreen && kind == OverlayKind::BottomSheet {
1154                    // Extend the rounded shape past the bottom edge, then clip it so
1155                    // only the top two 28dp corners are rounded and the bottom sits flush.
1156                    f.within(bounds, |f| {
1157                        f.rect(
1158                            Rect {
1159                                height: (bounds.height + radius).max(radius * 2.0),
1160                                ..bounds
1161                            },
1162                            radius,
1163                            surface_color,
1164                        )
1165                    });
1166                } else if !angular
1167                    && !fullscreen
1168                    && state.style != OverlayStyle::NavigationRail
1169                    && kind == OverlayKind::SideSheet
1170                {
1171                    // Extend the rounded shape past the outer right edge, then clip it so
1172                    // only the inner (top-left & bottom-left) 16dp corners are rounded.
1173                    f.within(bounds, |f| {
1174                        f.rect(
1175                            Rect {
1176                                width: (bounds.width + 16.0).max(32.0),
1177                                ..bounds
1178                            },
1179                            16.0,
1180                            surface_color,
1181                        )
1182                    });
1183                } else if !angular
1184                    && !fullscreen
1185                    && state.style != OverlayStyle::NavigationRail
1186                    && kind == OverlayKind::LeftSideSheet
1187                {
1188                    // Extend the rounded shape past the outer left edge, then clip it so
1189                    // only the inner (top-right & bottom-right) 16dp corners are rounded.
1190                    f.within(bounds, |f| {
1191                        let extend = (bounds.width + 16.0).max(32.0) - bounds.width;
1192                        f.rect(
1193                            Rect {
1194                                x: bounds.x - extend,
1195                                width: bounds.width + extend,
1196                                ..bounds
1197                            },
1198                            16.0,
1199                            surface_color,
1200                        )
1201                    });
1202                } else {
1203                    f.rect(bounds, radius, surface_color);
1204                }
1205                let body = if fullscreen
1206                    || (kind == OverlayKind::BottomSheet && state.drag_to_dismiss)
1207                    || matches!(
1208                        state.style,
1209                        OverlayStyle::NavigationRail | OverlayStyle::NavigationDrawer
1210                    ) {
1211                    bounds
1212                } else if angular {
1213                    if kind == OverlayKind::Menu || timepicker {
1214                        Rect {
1215                            y: bounds.y + 8.0,
1216                            height: (bounds.height - 16.0).max(0.0),
1217                            ..bounds
1218                        }
1219                    } else {
1220                        bounds
1221                    }
1222                } else {
1223                    Rect {
1224                        height: full.height,
1225                        ..bounds
1226                    }
1227                    .inset(16.0)
1228                };
1229                if modal && kind == OverlayKind::Dialog && state.open {
1230                    if let Some(title) = state.accessible_title.as_deref() {
1231                        f.semantic(
1232                            Response {
1233                                id,
1234                                bounds,
1235                                enabled: true,
1236                                ..Response::default()
1237                            },
1238                            Role::Dialog,
1239                            title,
1240                            false,
1241                            None,
1242                            None,
1243                            None,
1244                        );
1245                    }
1246                    if let Some(description) = state.accessible_description.as_deref() {
1247                        f.semantic(
1248                            Response {
1249                                id,
1250                                bounds,
1251                                enabled: true,
1252                                ..Response::default()
1253                            },
1254                            Role::DialogDescription,
1255                            description,
1256                            false,
1257                            None,
1258                            None,
1259                            None,
1260                        );
1261                    }
1262                }
1263                if angular && kind == OverlayKind::Menu {
1264                    f.semantic(
1265                        Response {
1266                            id,
1267                            bounds,
1268                            enabled: state.open && f.enabled,
1269                            ..Response::default()
1270                        },
1271                        Role::Menu,
1272                        "Menu",
1273                        false,
1274                        None,
1275                        None,
1276                        None,
1277                    );
1278                }
1279                let entering_menu = angular && kind == OverlayKind::Menu && values[0] < 1.0;
1280                let input = f.input;
1281                if entering_menu {
1282                    f.input.pointer = None;
1283                    f.input.pressed = false;
1284                    f.input.released = false;
1285                    f.input.scroll = [0.0; 2];
1286                }
1287                f.without_input(
1288                    state.suspended || nested_claimed || side_drag_claimed,
1289                    |f| {
1290                        f.with_enabled(state.open && (alpha > 0.001 || entering_menu), |f| {
1291                            f.within(body, |f| build(f, &mut state.open))
1292                        })
1293                    },
1294                );
1295                f.input = input;
1296            });
1297            self.overlay_nested_scroll = previous_nested_scroll;
1298            if datepicker {
1299                self.commands.push(DrawCommand::PopScaleY);
1300            }
1301            self.overlay_phase = previous_phase;
1302            for (index, command) in self.commands[start..].iter_mut().enumerate() {
1303                match command {
1304                    DrawCommand::RoundedRect { color, .. }
1305                    | DrawCommand::Ellipse { color, .. }
1306                    | DrawCommand::Outline { color, .. }
1307                    | DrawCommand::Text { color, .. }
1308                    | DrawCommand::Shadow { color, .. }
1309                    | DrawCommand::Ripple { color, .. }
1310                    | DrawCommand::Loading { color, .. }
1311                    | DrawCommand::Shape { color, .. }
1312                    | DrawCommand::Image { color, .. }
1313                    | DrawCommand::Arc { color, .. }
1314                    | DrawCommand::Line { color, .. }
1315                    | DrawCommand::Polyline { color, .. } => {
1316                        *color = color.opacity(if !angular && index == 0 {
1317                            alpha
1318                        } else {
1319                            values[3]
1320                        })
1321                    }
1322                    _ => {}
1323                }
1324            }
1325            if !state.open {
1326                self.ui.semantics.truncate(semantics_start);
1327                if state.was_open {
1328                    self.ui.next_focus_order.clear();
1329                }
1330            }
1331        }
1332        if state.open && !state.suspended && self.ui.focused.is_none() {
1333            self.ui.focused = state
1334                .initial_focus
1335                .filter(|id| self.ui.next_focus_order.contains(id))
1336                .or_else(|| self.ui.next_focus_order.first().copied());
1337            self.ui.keyboard_focus =
1338                state.opened_with_keyboard || angular && kind == OverlayKind::BottomSheet;
1339            self.ui.continuous |= angular
1340                && matches!(kind, OverlayKind::Menu | OverlayKind::BottomSheet)
1341                && self.ui.focused.is_some();
1342        }
1343        if !state.open && state.was_open {
1344            // The background was built disabled earlier in this frame. Restore only
1345            // once its owner is enabled again, never to a disabled/removed control.
1346            self.ui.pending_focus = state.restore;
1347            self.ui.pending_focus_keyboard =
1348                self.input.key.is_some() || (self.ui.keyboard_focus && !self.input.pressed);
1349            self.ui.keyboard_focus = self.ui.pending_focus_keyboard;
1350            self.ui.continuous = true;
1351        }
1352        self.ui.overlay_active |= state.open;
1353        state.was_open = state.open;
1354    }
1355    /// Direct manipulation handle: pointer movement has no animation lag.
1356    #[allow(clippy::too_many_arguments)]
1357    pub fn drag_handle(
1358        &mut self,
1359        id: u64,
1360        b: Rect,
1361        track: Rect,
1362        label: &str,
1363        value: &mut f32,
1364        range: std::ops::RangeInclusive<f32>,
1365        vertical: bool,
1366    ) -> Response {
1367        let min = *range.start();
1368        let max = *range.end();
1369        assert!(min.is_finite() && max.is_finite() && min < max);
1370        *value = if value.is_finite() {
1371            value.clamp(min, max)
1372        } else {
1373            min
1374        };
1375        let before = *value;
1376        let mut r = self.interact(id, b, true);
1377        if r.enabled
1378            && r.pressed
1379            && self.ui.capture == Capture::Pointer
1380            && let Some(p) = self.input.pointer
1381        {
1382            let (position, start, size) = if vertical {
1383                (p[1], track.y, track.height)
1384            } else {
1385                (p[0], track.x, track.width)
1386            };
1387            *value = min + ((position - start) / size.max(1.0)).clamp(0.0, 1.0) * (max - min);
1388        }
1389        if let Some(key) = self.key_for(r) {
1390            *value = match key {
1391                Key::Left | Key::Up => (*value - 1.0).max(min),
1392                Key::Right | Key::Down => (*value + 1.0).min(max),
1393                Key::Home => min,
1394                Key::End => max,
1395                _ => *value,
1396            };
1397        }
1398        r.changed = before != *value;
1399        self.semantic(
1400            r,
1401            Role::Slider,
1402            label,
1403            false,
1404            None,
1405            Some(*value),
1406            Some([min, max]),
1407        );
1408        self.focus_ring(r);
1409        r
1410    }
1411    /// Material 3 coplanar adaptive Standard Side Sheet sharing horizontal bounds
1412    /// with main content, separated by a 1dp vertical divider, with animated width.
1413    pub fn standard_side_sheet(
1414        &mut self,
1415        id: u64,
1416        open: &mut bool,
1417        right_edge: bool,
1418        width: f32,
1419        build_content: impl FnOnce(&mut Self),
1420        build_sheet: impl FnOnce(&mut Self),
1421    ) {
1422        let avail = self.available();
1423        let area = self.allocate(avail.height);
1424        if area.width <= 0.0 || area.height <= 0.0 {
1425            return;
1426        }
1427        let target_width = if width.is_finite() {
1428            width.clamp(0.0, area.width)
1429        } else {
1430            0.0
1431        };
1432        let progress = self
1433            .spatial(id, 21, f32::from(*open), f32::from(*open))
1434            .clamp(0.0, 1.0);
1435        let sheet_width = (target_width * progress).min(area.width);
1436        let divider_width = if sheet_width > 0.5 && area.width > sheet_width {
1437            1.0
1438        } else {
1439            0.0
1440        };
1441        let content_width = (area.width - sheet_width - divider_width).max(0.0);
1442        let (content_rect, divider_rect, sheet_rect, inner_sheet_rect) = if right_edge {
1443            let content = Rect {
1444                x: area.x,
1445                y: area.y,
1446                width: content_width,
1447                height: area.height,
1448            };
1449            let divider = Rect {
1450                x: area.x + content_width,
1451                y: area.y,
1452                width: divider_width,
1453                height: area.height,
1454            };
1455            let sheet = Rect {
1456                x: area.x + content_width + divider_width,
1457                y: area.y,
1458                width: sheet_width,
1459                height: area.height,
1460            };
1461            let inner = Rect {
1462                x: sheet.x,
1463                y: sheet.y,
1464                width: target_width.max(sheet_width),
1465                height: sheet.height,
1466            };
1467            (content, divider, sheet, inner)
1468        } else {
1469            let sheet = Rect {
1470                x: area.x,
1471                y: area.y,
1472                width: sheet_width,
1473                height: area.height,
1474            };
1475            let divider = Rect {
1476                x: area.x + sheet_width,
1477                y: area.y,
1478                width: divider_width,
1479                height: area.height,
1480            };
1481            let content = Rect {
1482                x: area.x + sheet_width + divider_width,
1483                y: area.y,
1484                width: content_width,
1485                height: area.height,
1486            };
1487            let inner = Rect {
1488                x: sheet.x + sheet.width - target_width.max(sheet_width),
1489                y: sheet.y,
1490                width: target_width.max(sheet_width),
1491                height: sheet.height,
1492            };
1493            (content, divider, sheet, inner)
1494        };
1495
1496        if content_rect.width > 0.0 {
1497            self.within(content_rect, build_content);
1498        }
1499        if sheet_width > 0.5 {
1500            if divider_width > 0.0 {
1501                self.divider_at(divider_rect, DividerOrientation::Vertical, 0.0, 0.0);
1502            }
1503            let surface = self.ui.theme.background;
1504            self.rect(sheet_rect, 0.0, surface);
1505            let enabled = *open;
1506            self.within(sheet_rect, |f| {
1507                f.with_enabled(enabled, |f| {
1508                    f.within_unclipped(inner_sheet_rect, build_sheet);
1509                });
1510            });
1511        }
1512        if *open && !self.key_consumed && self.pressed_key(Key::Escape) {
1513            *open = false;
1514            self.key_consumed = true;
1515            self.ui.continuous = true;
1516        }
1517    }
1518
1519    /// Standard Material 3 dialog content layout (24sp title, body paragraph, Cancel/Confirm text actions).
1520    /// Returns `(cancel_clicked, confirm_clicked)`.
1521    pub fn dialog_chrome(
1522        &mut self,
1523        id: u64,
1524        title: &str,
1525        body: &str,
1526        cancel_label: Option<&str>,
1527        confirm_label: &str,
1528    ) -> (bool, bool) {
1529        let t = self.theme();
1530        let b = self.available();
1531        self.styled_text(
1532            Rect {
1533                x: b.x + 24.0,
1534                y: b.y + 16.0,
1535                width: (b.width - 48.0).max(0.0),
1536                height: 36.0,
1537            },
1538            title,
1539            t.text,
1540            TextStyle {
1541                size: 24.0,
1542                ..TextStyle::default()
1543            },
1544        );
1545        self.paragraph(
1546            Rect {
1547                x: b.x + 24.0,
1548                y: b.y + 60.0,
1549                width: (b.width - 48.0).max(0.0),
1550                height: (b.height - 124.0).max(24.0),
1551            },
1552            body,
1553            t.on_surface_variant,
1554            TextStyle {
1555                size: 14.0,
1556                ..TextStyle::default()
1557            },
1558            20.0,
1559        );
1560        let btn_y = (b.y + b.height - 56.0).max(b.y + 84.0);
1561        let conf_w = (self.text_width(confirm_label, TextStyle::LABEL) + 24.0).max(64.0);
1562        let conf_rect = Rect {
1563            x: (b.x + b.width - 20.0 - conf_w).max(b.x + 16.0),
1564            y: btn_y,
1565            width: conf_w,
1566            height: 40.0,
1567        };
1568        let confirm = self
1569            .action_at(
1570                id.wrapping_add(1),
1571                conf_rect,
1572                confirm_label,
1573                Options {
1574                    variant: ButtonVariant::Text,
1575                    ..Options::default()
1576                },
1577            )
1578            .clicked;
1579        let cancel = if let Some(c_label) = cancel_label {
1580            let canc_w = (self.text_width(c_label, TextStyle::LABEL) + 24.0).max(64.0);
1581            let canc_rect = Rect {
1582                x: (conf_rect.x - 8.0 - canc_w).max(b.x + 16.0),
1583                y: btn_y,
1584                width: canc_w,
1585                height: 40.0,
1586            };
1587            self.action_at(
1588                id,
1589                canc_rect,
1590                c_label,
1591                Options {
1592                    variant: ButtonVariant::Text,
1593                    ..Options::default()
1594                },
1595            )
1596            .clicked
1597        } else {
1598            false
1599        };
1600        (cancel, confirm)
1601    }
1602
1603    /// Material 3 Full-Screen Dialog header bar (Close X + 22sp title + Save action + divider).
1604    /// Returns `(close_clicked, action_clicked)`.
1605    pub fn fullscreen_dialog_header(
1606        &mut self,
1607        id: u64,
1608        title: &str,
1609        action_label: &str,
1610    ) -> (bool, bool) {
1611        let t = self.theme();
1612        let bar = self.reserve(56.0);
1613        let close_rect = Rect {
1614            x: bar.x + 4.0,
1615            y: bar.y + 4.0,
1616            width: 48.0,
1617            height: 48.0,
1618        };
1619        let close = self
1620            .material_icon_button_at(
1621                id,
1622                close_rect,
1623                MaterialIcon::Close,
1624                "Close",
1625                Options {
1626                    variant: ButtonVariant::Text,
1627                    ..Options::default()
1628                },
1629            )
1630            .clicked;
1631        let act_w = (self.text_width(action_label, TextStyle::LABEL) + 24.0)
1632            .clamp(64.0, (bar.width * 0.4).max(64.0));
1633        let act_rect = Rect {
1634            x: (bar.x + bar.width - act_w - 8.0).max(bar.x + 56.0),
1635            y: bar.y + 8.0,
1636            width: act_w,
1637            height: 40.0,
1638        };
1639        let action = self
1640            .action_at(
1641                id.wrapping_add(1),
1642                act_rect,
1643                action_label,
1644                Options {
1645                    variant: ButtonVariant::Text,
1646                    ..Options::default()
1647                },
1648            )
1649            .clicked;
1650        self.styled_text(
1651            Rect {
1652                x: bar.x + 64.0,
1653                y: bar.y,
1654                width: (act_rect.x - (bar.x + 64.0) - 8.0).max(0.0),
1655                height: bar.height,
1656            },
1657            title,
1658            t.text,
1659            TextStyle {
1660                size: 22.0,
1661                ..TextStyle::default()
1662            },
1663        );
1664        self.paint_line(
1665            [bar.x, bar.y + bar.height],
1666            [bar.x + bar.width, bar.y + bar.height],
1667            1.0,
1668            t.outline_variant,
1669        );
1670        (close, action)
1671    }
1672
1673    /// Centered Material 3 bottom sheet drag handle pill (`32dp × 4dp`, 22dp vertical touch margin).
1674    pub fn bottom_sheet_drag_handle(&mut self) {
1675        let row = self.reserve(28.0);
1676        let pill = Rect {
1677            x: row.x + (row.width - 32.0) * 0.5,
1678            y: row.y + (row.height - 4.0) * 0.5,
1679            width: 32.0,
1680            height: 4.0,
1681        };
1682        self.paint_rect(pill, 2.0, self.theme().on_surface_variant.opacity(0.4));
1683    }
1684
1685    /// Material 3 Side Sheet header row (22sp title + trailing Close icon button + bottom divider).
1686    /// Returns `true` when the close button is clicked.
1687    pub fn side_sheet_header(&mut self, id: u64, title: &str) -> bool {
1688        let t = self.theme();
1689        let bar = self.reserve(56.0);
1690        let close_rect = Rect {
1691            x: (bar.x + bar.width - 52.0).max(bar.x),
1692            y: bar.y + 4.0,
1693            width: 48.0,
1694            height: 48.0,
1695        };
1696        self.styled_text(
1697            Rect {
1698                x: bar.x + 24.0,
1699                y: bar.y,
1700                width: (close_rect.x - (bar.x + 24.0) - 8.0).max(0.0),
1701                height: bar.height,
1702            },
1703            title,
1704            t.text,
1705            TextStyle {
1706                size: 22.0,
1707                ..TextStyle::default()
1708            },
1709        );
1710        let closed = self
1711            .material_icon_button_at(
1712                id,
1713                close_rect,
1714                MaterialIcon::Close,
1715                "Close",
1716                Options {
1717                    variant: ButtonVariant::Text,
1718                    ..Options::default()
1719                },
1720            )
1721            .clicked;
1722        self.paint_line(
1723            [bar.x, bar.y + bar.height],
1724            [bar.x + bar.width, bar.y + bar.height],
1725            1.0,
1726            t.outline_variant,
1727        );
1728        closed
1729    }
1730}
1731
1732#[cfg(test)]
1733#[path = "overlay.spec.rs"]
1734mod tests;