Skip to main content

bhoo/systems/material/
overlay.rs

1use crate::*;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4pub enum OverlayKind {
5    #[default]
6    Popover,
7    Menu,
8    Dialog,
9    BottomSheet,
10    SideSheet,
11    /// A modal surface entering from the left edge.
12    LeftSideSheet,
13}
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum OverlayStyle {
16    #[default]
17    Material3,
18    AngularMaterial,
19    AngularDatepicker,
20    AngularTimepicker,
21    /// Surface and content geometry for an expanded modal navigation rail.
22    NavigationRail,
23    /// Material modal navigation drawer, with leading edge attached to the viewport.
24    NavigationDrawer,
25    /// Android Material popup menu surface.
26    AndroidMenu,
27}
28
29/// Which implicit gestures may dismiss an overlay. Explicit actions may still
30/// close it regardless of this setting.
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
32pub enum OverlayDismissPolicy {
33    #[default]
34    EscapeOrOutside,
35    EscapeOnly,
36    OutsideOnly,
37    ExplicitOnly,
38}
39impl OverlayDismissPolicy {
40    fn escape(self) -> bool { matches!(self, Self::EscapeOrOutside | Self::EscapeOnly) }
41    fn outside(self) -> bool { matches!(self, Self::EscapeOrOutside | Self::OutsideOnly) }
42}
43
44#[derive(Clone, Copy)]
45pub(crate) struct OverlayPhase {
46    id: u64,
47    open: bool,
48    kind: OverlayKind,
49}
50#[derive(Clone, Copy)]
51pub enum OverlaySection {
52    Headline,
53    Content,
54    Actions,
55}
56
57#[derive(Clone,Copy)]
58struct BottomSheetNestedTouch {origin:f32,last:f32,last_time:f64,velocity:f32,claimed:bool,moved_sheet:bool}
59fn sheet_detent(current:f32,collapsed:f32,half:Option<f32>,xvel:f32,yvel:f32)->f32 {
60    let mut detents=vec![0.0];if let Some(value)=half {detents.push(value);}detents.push(collapsed);
61    if yvel < -500.0 && yvel.abs()>xvel.abs() {detents.iter().rev().copied().find(|&v|v<current-0.01).unwrap_or(0.0)}
62    else if yvel>500.0 && yvel.abs()>xvel.abs() {detents.iter().copied().find(|&v|v>current+0.01).unwrap_or(collapsed)}
63    else {detents.iter().copied().min_by(|a,b|(a-current).abs().total_cmp(&(b-current).abs())).unwrap_or(0.0)}
64}
65// Material Android distinguishes handle release from nested-scroll stop.
66fn sheet_handle_detent(current:f32,collapsed:f32,half:Option<f32>,expanded_top:f32,xvel:f32,yvel:f32)->f32 {
67    if yvel<0.0 {
68        return half.filter(|&h|current>h).unwrap_or(0.0);
69    }
70    if yvel==0.0 || xvel.abs()>yvel.abs() {
71        if let Some(h)=half {
72            if current<h {
73                return if expanded_top+current < (current-collapsed).abs() {0.0} else {h};
74            }
75            return if (current-h).abs() < (current-collapsed).abs() {h} else {collapsed};
76        }
77        return if current < (current-collapsed).abs() {0.0} else {collapsed};
78    }
79    half.filter(|&h|(current-h).abs()<(current-collapsed).abs()).unwrap_or(collapsed)
80}
81/// Caller-owned overlay lifetime and focus return point.
82#[derive(Default,Clone)]
83pub struct OverlayState {
84    pub open: bool,
85    pub kind: OverlayKind,
86    pub style: OverlayStyle,
87    pub initial_focus: Option<u64>,
88    pub dismiss_policy: OverlayDismissPolicy,
89    /// Accessible title and description for a modal dialog.
90    pub accessible_title: Option<String>,
91    pub accessible_description: Option<String>,
92    /// Fill the host viewport when this overlay is a dialog.
93    pub fullscreen: bool,
94    /// Temporarily suspend this overlay while a separately rendered child modal
95    /// owns input. The caller clears this when the child has closed.
96    pub suspended: bool,
97    pub transform_origin: Option<[f32; 2]>,
98    /// Allow dragging a Material bottom sheet from its top 32 logical pixels.
99    pub drag_to_dismiss: bool,
100    /// When set, a non-modal sheet settles between this visible peek height and full height.
101    pub bottom_sheet_peek: Option<f32>,
102    /// Current target detent for a sheet with a peek height.
103    pub bottom_sheet_expanded: bool,
104    /// Optional visible viewport-height fraction for an intermediate detent.
105    pub bottom_sheet_half_ratio: Option<f32>,
106    /// Whether the current target is the intermediate detent.
107    pub bottom_sheet_half_expanded: bool,
108    /// Offset of the scrollable region below the sheet's top; None disables nested scrolling.
109    pub bottom_sheet_content_top: Option<f32>,
110    /// Total scrollable content height in logical pixels.
111    pub bottom_sheet_content_height: f32,
112    /// Current nested content scroll position.
113    pub bottom_sheet_scroll_offset: f32,
114    nested_touch: Option<BottomSheetNestedTouch>,
115    nested_physics: crate::scroll::ScrollPhysics,
116    drag_origin: Option<(f32,f32)>,
117    side_drag_origin: Option<(f32,f32,f32,bool)>,
118    drag_last_motion: Option<(f64,[f32;2])>,
119    drag_velocity: [f32;2],
120    drag_displacement: f32,
121    drag_settle: Option<(f64,f32,f32)>,
122    drag_close_offset: f32,
123    geometry: crate::timing::Tween,
124    surface: crate::timing::Tween,
125    scrim: crate::timing::Tween,
126    content: crate::timing::Tween,
127    was_open: bool,
128    sampled_open: bool,
129    opened_with_keyboard: bool,
130    restore: Option<u64>,
131}
132
133impl OverlayState {
134    fn sample(&mut self, time: f64, reduced: bool) -> [f32; 4] {
135        use crate::timing::{Easing, TweenSpec};
136        let target = f32::from(self.open);
137        if self.style == OverlayStyle::AngularMaterial && self.kind == OverlayKind::BottomSheet {
138            let geometry = self.geometry.sample(
139                time,
140                target,
141                TweenSpec::new(0.195, Easing::Cubic([0.0, 0.0, 0.2, 1.0])),
142                TweenSpec::new(0.375, Easing::Cubic([0.4, 0.0, 1.0, 1.0])),
143                reduced,
144            );
145            let scrim = self.scrim.sample(
146                time,
147                target,
148                TweenSpec::new(0.4, Easing::Backdrop),
149                TweenSpec::new(0.4, Easing::Backdrop),
150                reduced,
151            );
152            let visible = f32::from(self.open || self.geometry.moving());
153            return [geometry, visible, scrim, visible];
154        }
155        if matches!(
156            self.style,
157            OverlayStyle::AngularDatepicker | OverlayStyle::AngularTimepicker
158        ) {
159            let spec = TweenSpec::new(0.120, Easing::StandardDecelerate);
160            if self.open != self.sampled_open {
161                if !self.open {
162                    self.geometry.sample(time, 1.0, spec, spec, reduced);
163                }
164                let interrupted = !self.open && self.geometry.moving();
165                let initial = if self.open || interrupted { 0.0 } else { 1.0 };
166                self.geometry = crate::timing::Tween::at(initial);
167                self.surface = crate::timing::Tween::at(initial);
168                self.sampled_open = self.open;
169            }
170            let geometry = self.geometry.sample(
171                time,
172                target,
173                spec,
174                TweenSpec::new(0.0, Easing::Linear),
175                reduced,
176            );
177            let alpha = self.surface.sample(
178                time,
179                target,
180                spec,
181                TweenSpec::new(0.100, Easing::Linear),
182                reduced,
183            );
184            return [if self.open { geometry } else { 1.0 }, alpha, 0.0, alpha];
185        }
186        if matches!(self.style, OverlayStyle::AngularMaterial | OverlayStyle::AndroidMenu) {
187            let menu = self.kind == OverlayKind::Menu;
188            if menu {
189                if self.open != self.sampled_open {
190                    let interrupted = if !self.open && self.sampled_open {
191                        let spec = TweenSpec::new(0.120, Easing::StandardDecelerate);
192                        self.geometry.sample(time, 1.0, spec, spec, reduced);
193                        self.geometry.moving()
194                    } else {
195                        false
196                    };
197                    // Angular's animationcancel notification detaches a panel
198                    // closed before its enter animation finishes.
199                    let initial = if self.open || interrupted { 0.0 } else { 1.0 };
200                    self.geometry = crate::timing::Tween::at(initial);
201                    self.surface = crate::timing::Tween::at(initial);
202                    self.sampled_open = self.open;
203                }
204                self.scrim = crate::timing::Tween::at(0.0);
205                self.content = crate::timing::Tween::at(0.0);
206            }
207            let enter = if menu { 0.120 } else { 0.150 };
208            let exit = if menu { 0.100 } else { 0.075 };
209            let g = self.geometry.sample(
210                time,
211                target,
212                TweenSpec::new(enter, Easing::StandardDecelerate),
213                TweenSpec::new(0.0, Easing::Linear),
214                reduced,
215            );
216            let a = self.surface.sample(
217                time,
218                target,
219                TweenSpec::new(
220                    enter,
221                    if menu {
222                        Easing::StandardDecelerate
223                    } else {
224                        Easing::Linear
225                    },
226                ),
227                TweenSpec {
228                    delay: if menu { 0.025 } else { 0.0 },
229                    duration: exit,
230                    easing: Easing::Linear,
231                },
232                reduced,
233            );
234            let scrim = if menu {
235                0.0
236            } else {
237                self.scrim.sample(
238                    time,
239                    target,
240                    TweenSpec::new(0.4, Easing::Backdrop),
241                    TweenSpec::new(0.4, Easing::Backdrop),
242                    reduced,
243                )
244            };
245            return [if self.open { g } else { 1.0 }, a, scrim, a];
246        }
247        let geometry = self.geometry.sample(
248            time,
249            target,
250            TweenSpec::new(0.5, Easing::Emphasized),
251            TweenSpec::new(0.15, Easing::EmphasizedAccelerate),
252            reduced,
253        );
254        let surface = self.surface.sample(
255            time,
256            target,
257            TweenSpec::new(0.05, Easing::Linear),
258            TweenSpec {
259                delay: 0.1,
260                duration: 0.05,
261                easing: Easing::Linear,
262            },
263            reduced,
264        );
265        let scrim = self.scrim.sample(
266            time,
267            target,
268            TweenSpec::new(0.5, Easing::Linear),
269            TweenSpec::new(0.15, Easing::Linear),
270            reduced,
271        );
272        let content = self.content.sample(
273            time,
274            target,
275            TweenSpec {
276                delay: 0.05,
277                duration: 0.2,
278                easing: Easing::Linear,
279            },
280            TweenSpec::new(0.1, Easing::Linear),
281            reduced,
282        );
283        [geometry, surface, scrim, content]
284    }
285    pub(crate) fn moving(&self) -> bool {
286        self.geometry.moving()
287            || self.surface.moving()
288            || self.scrim.moving()
289            || self.content.moving()
290    }
291}
292
293impl Frame<'_> {
294    /// Source Web menu entry/exit stagger; each item retargets from its presentation.
295    pub fn overlay_item(&mut self, index: usize, count: usize, build: impl FnOnce(&mut Self)) {
296        use crate::timing::{Easing, TweenSpec};
297        if let Some(phase) = self.overlay_phase.filter(|p| p.kind == OverlayKind::Menu) {
298            let count = count.clamp(1, 64);
299            let index = index.min(count - 1);
300            let enter = TweenSpec {
301                delay: 0.250 / count as f64 * index as f64,
302                duration: 0.250,
303                easing: Easing::Linear,
304            };
305            let exit = TweenSpec {
306                delay: 0.050 + 0.050 / count as f64 * (count - 1 - index) as f64,
307                duration: 0.050,
308                easing: Easing::Linear,
309            };
310            let alpha = self.ui.motion.tween(
311                phase.id,
312                100 + index as u8,
313                f32::from(phase.open),
314                0.0,
315                enter,
316                exit,
317            );
318            self.with_opacity(alpha, build);
319        } else {
320            build(self);
321        }
322    }
323    pub fn overlay_section(&mut self, section: OverlaySection, build: impl FnOnce(&mut Self)) {
324        use crate::timing::{Easing, TweenSpec};
325        if let Some(phase) = self.overlay_phase.filter(|p| p.kind == OverlayKind::Dialog) {
326            let (property, delay, duration, exit) = match section {
327                OverlaySection::Headline => (80, 0.050, 0.200, 0.100),
328                OverlaySection::Content => (81, 0.050, 0.200, 0.100),
329                OverlaySection::Actions => (82, 0.150, 0.150, 0.050),
330            };
331            let alpha = self.ui.motion.tween(
332                phase.id,
333                property,
334                f32::from(phase.open),
335                0.0,
336                TweenSpec {
337                    delay,
338                    duration,
339                    easing: Easing::Linear,
340                },
341                TweenSpec::new(exit, Easing::Linear),
342            );
343            self.with_opacity(alpha, build);
344        } else {
345            build(self);
346        }
347    }
348    /// Modal surface: disable background while `open`, then call this after the trigger.
349    /// Exit visuals never receive input; focus is restored immediately on dismissal.
350    pub fn overlay(
351        &mut self,
352        id: u64,
353        state: &mut OverlayState,
354        bounds: Rect,
355        modal: bool,
356        mut build: impl FnMut(&mut Self, &mut bool),
357    ) {
358        if state.open && !state.was_open {
359            state.opened_with_keyboard = self.ui.keyboard_focus || self.input.key.is_some();
360            state.restore = self.ui.focused;
361            self.ui.focused = None;
362        }
363        let timed = matches!(state.kind, OverlayKind::Menu | OverlayKind::Dialog)
364            || state.style == OverlayStyle::AngularMaterial
365                && state.kind == OverlayKind::BottomSheet
366            || matches!(
367                state.style,
368                OverlayStyle::AngularDatepicker | OverlayStyle::AngularTimepicker
369            );
370        let mut values = if timed {
371            state.sample(self.ui.time, self.reduced_motion())
372        } else {
373            let position = self.spatial(id, 21, f32::from(state.open), 0.0);
374            let alpha = self.animate(id, 20, f32::from(state.open), 0.0);
375            [position, alpha, alpha, alpha]
376        };
377        let kind = state.kind;
378        let fullscreen = kind == OverlayKind::Dialog && state.fullscreen;
379        let full = if fullscreen { self.viewport() } else { bounds };
380        let angular = matches!(
381            state.style,
382            OverlayStyle::AngularMaterial
383                | OverlayStyle::AndroidMenu
384                | OverlayStyle::AngularDatepicker
385                | OverlayStyle::AngularTimepicker
386        );
387        let datepicker = matches!(
388            state.style,
389            OverlayStyle::AngularDatepicker | OverlayStyle::AngularTimepicker
390        );
391        let timepicker = state.style == OverlayStyle::AngularTimepicker;
392        let draggable=state.drag_to_dismiss && kind==OverlayKind::BottomSheet && !angular && !state.suspended;
393        let side_draggable=modal && matches!(kind,OverlayKind::SideSheet | OverlayKind::LeftSideSheet) && !angular && !state.suspended && (state.drag_to_dismiss || state.dismiss_policy.outside());
394        let side_dir=if kind==OverlayKind::SideSheet {1.0} else {-1.0};
395        let collapsed_offset=state.bottom_sheet_peek.filter(|v|v.is_finite()).map(|peek|(full.height-peek.clamp(0.0,full.height)).max(0.0));
396        let viewport=self.viewport();
397        let half_offset=state.bottom_sheet_half_ratio.filter(|r|r.is_finite() && *r>0.0 && *r<1.0).and_then(|ratio| {
398            let offset=viewport.y+viewport.height*(1.0-ratio)-full.y;
399            collapsed_offset.filter(|&collapsed|offset>0.01 && offset<collapsed-0.01).map(|_|offset)
400        });
401        let target_detent=if state.bottom_sheet_expanded {0.0} else if state.bottom_sheet_half_expanded {half_offset.unwrap_or(collapsed_offset.unwrap_or(0.0))} else {collapsed_offset.unwrap_or(0.0)};
402        if draggable && !state.open && state.was_open && collapsed_offset.is_some() {state.drag_close_offset=state.drag_displacement;}
403        if draggable && state.open {
404            if !state.was_open && state.drag_close_offset==0.0 && let Some(collapsed)=collapsed_offset {
405                state.drag_displacement=target_detent.min(collapsed);
406            }
407            if state.drag_close_offset>0.0 {
408                state.drag_displacement=state.drag_close_offset*values[0].clamp(0.0,1.0);
409                state.drag_close_offset=0.0;state.drag_settle=Some((self.ui.time,state.drag_displacement,target_detent));
410            }
411            // The caller can change the target or sheet geometry while it is open.
412            // Retarget from the current position without disturbing an active drag.
413            if collapsed_offset.is_some() && state.was_open && state.drag_origin.is_none() && state.nested_touch.is_none() && !self.input.pressed {
414                match state.drag_settle {
415                    Some((_,_,target)) if (target-target_detent).abs()>0.01 => {
416                        state.drag_settle=Some((self.ui.time,state.drag_displacement,target_detent));
417                    }
418                    None if (state.drag_displacement-target_detent).abs()>0.01 => {
419                        state.drag_settle=Some((self.ui.time,state.drag_displacement,target_detent));
420                    }
421                    _=>{}
422                }
423            }
424            if let Some((started,from,target))=state.drag_settle {
425                let elapsed=(self.ui.time-started).max(0.0);let factor=if self.reduced_motion() {0.0} else {((1.0+18.0*elapsed)*(-18.0*elapsed).exp()) as f32};
426                state.drag_displacement=target+(from-target)*factor;
427                if factor<0.001 {state.drag_settle=None;state.drag_displacement=target;} else {self.ui.continuous=true;}
428            }
429            if self.input.pressed && values[0]>0.95 && let Some(point)=self.input.pointer {
430                let top=full.y+full.height*(1.0-values[0])+state.drag_displacement;
431                if point[0]>=full.x && point[0]<full.x+full.width && point[1]>=top && point[1]<top+32.0 {
432                    state.drag_origin=Some((point[1],state.drag_displacement));state.drag_last_motion=Some((self.ui.time,point));state.drag_velocity=[0.0;2];state.drag_settle=None;self.ui.active=None;
433                }
434            }
435            if let Some((origin,initial))=state.drag_origin {
436                if let Some(point)=self.input.pointer {
437                    state.drag_displacement=(initial+point[1]-origin).clamp(0.0,collapsed_offset.unwrap_or(full.height));
438                    if let Some((last_time,last_point))=state.drag_last_motion && point!=last_point {
439                        let dt=self.ui.time-last_time;
440                        if dt>0.0 {state.drag_velocity=[((point[0]-last_point[0])/dt as f32).clamp(-10000.0,10000.0),((point[1]-last_point[1])/dt as f32).clamp(-10000.0,10000.0)];}
441                        state.drag_last_motion=Some((self.ui.time,point));
442                    }
443                }
444                if self.input.cancelled || self.input.blurred || self.input.released {
445                    state.drag_origin=None;self.ui.active=None;
446                    let [xvel,yvel]=if state.drag_last_motion.is_some_and(|(last,_)|self.ui.time-last<=0.12) {state.drag_velocity} else {[0.0;2]};
447                    state.drag_last_motion=None;state.drag_velocity=[0.0;2];
448                    // Material Android's default significant velocity is 500 px/s; its
449                    // hide projection uses 0.1 s friction and a half-peek threshold.
450                    let flick=yvel>500.0 && yvel.abs()>xvel.abs() && state.drag_displacement+yvel*0.1>full.height*0.5;
451                    let distance=state.drag_displacement>=full.height*0.4 && yvel>=-50.0;
452                    if let Some(collapsed)=collapsed_offset {
453                        let current=state.drag_displacement;
454                        let target=if self.input.cancelled || self.input.blurred {target_detent} else {sheet_handle_detent(current,collapsed,half_offset,full.y-viewport.y,xvel,yvel)};
455                        state.bottom_sheet_expanded=target<=0.01;state.bottom_sheet_half_expanded=half_offset.is_some_and(|half|(target-half).abs()<0.01);
456                        state.drag_settle=Some((self.ui.time,current,target));self.ui.continuous=true;
457                    } else if !self.input.cancelled && !self.input.blurred && (distance || flick) {
458                        state.open=false;state.drag_close_offset=state.drag_displacement;state.drag_displacement=0.0;state.drag_settle=None;
459                        values=[self.spatial(id,21,0.0,0.0),self.animate(id,20,0.0,0.0),values[2],values[3]];self.ui.continuous=true;
460                    } else {state.drag_settle=Some((self.ui.time,state.drag_displacement,0.0));self.ui.continuous=true;}
461                }
462            }
463        }
464        let mut side_drag_claimed=false;
465        if side_draggable && state.open {
466            if state.drag_close_offset>0.0 {
467                state.drag_displacement=state.drag_close_offset*values[0].clamp(0.0,1.0);
468                state.drag_close_offset=0.0;state.drag_settle=Some((self.ui.time,state.drag_displacement,0.0));
469            }
470            if let Some((started,from,target))=state.drag_settle {
471                let elapsed=(self.ui.time-started).max(0.0);let factor=if self.reduced_motion() {0.0} else {((1.0+18.0*elapsed)*(-18.0*elapsed).exp()) as f32};
472                state.drag_displacement=target+(from-target)*factor;
473                if factor<0.001 {state.drag_settle=None;state.drag_displacement=target;} else {self.ui.continuous=true;}
474            }
475            if self.input.pressed && values[0]>0.95 && let Some(point)=self.input.pointer {
476                let cur_x=if kind==OverlayKind::SideSheet {
477                    full.x+full.width*(1.0-values[0])+state.drag_displacement
478                } else {
479                    full.x-full.width*(1.0-values[0])-state.drag_displacement
480                };
481                let cur_rect=Rect {x:cur_x,..full};
482                if cur_rect.contains(point) {
483                    let already_displaced=state.drag_displacement>0.01;
484                    state.side_drag_origin=Some((point[0],point[1],state.drag_displacement,already_displaced));
485                    state.drag_last_motion=Some((self.ui.time,point));state.drag_velocity=[0.0;2];state.drag_settle=None;
486                    if already_displaced {self.ui.active=None;}
487                }
488            }
489            if let Some((ox,oy,initial,mut claimed))=state.side_drag_origin {
490                if let Some(point)=self.input.pointer {
491                    let dx=point[0]-ox;let dy=point[1]-oy;
492                    if !claimed && dx*side_dir>6.0 && dx.abs()>dy.abs() {claimed=true;self.ui.active=None;}
493                    if claimed {
494                        state.drag_displacement=(initial+dx*side_dir).clamp(0.0,full.width);
495                        self.ui.continuous=true;
496                    }
497                    if let Some((last_time,last_point))=state.drag_last_motion && point!=last_point {
498                        let dt=self.ui.time-last_time;
499                        if dt>0.0 {state.drag_velocity=[((point[0]-last_point[0])/dt as f32).clamp(-10000.0,10000.0),((point[1]-last_point[1])/dt as f32).clamp(-10000.0,10000.0)];}
500                        state.drag_last_motion=Some((self.ui.time,point));
501                    }
502                }
503                side_drag_claimed=claimed;
504                if self.input.cancelled || self.input.blurred || self.input.released {
505                    state.side_drag_origin=None;
506                    let [xvel,yvel]=if state.drag_last_motion.is_some_and(|(last,_)|self.ui.time-last<=0.12) {state.drag_velocity} else {[0.0;2]};
507                    state.drag_last_motion=None;state.drag_velocity=[0.0;2];
508                    if claimed {
509                        self.ui.active=None;
510                        let outward_vel=xvel*side_dir;
511                        let flick=outward_vel>500.0 && xvel.abs()>yvel.abs() && state.drag_displacement+outward_vel*0.1>full.width*0.5;
512                        let distance=state.drag_displacement>=full.width*0.4 && outward_vel>=-50.0;
513                        if !self.input.cancelled && !self.input.blurred && (distance || flick) {
514                            state.open=false;state.drag_close_offset=state.drag_displacement;state.drag_displacement=0.0;state.drag_settle=None;
515                            values=[self.spatial(id,21,0.0,0.0),self.animate(id,20,0.0,0.0),values[2],values[3]];self.ui.continuous=true;
516                        } else {
517                            state.drag_settle=Some((self.ui.time,state.drag_displacement,0.0));self.ui.continuous=true;
518                        }
519                    }
520                } else {
521                    state.side_drag_origin=Some((ox,oy,initial,claimed));
522                }
523            }
524        }
525        let mut nested_claimed=false;
526        if draggable && state.open && let (Some(collapsed),Some(content_top))=(collapsed_offset,state.bottom_sheet_content_top.filter(|v|v.is_finite() && *v>=32.0 && *v<full.height)) {
527            let nested_height=(full.height-content_top).max(0.0);let max=(state.bottom_sheet_content_height-nested_height).max(0.0);
528            if (state.nested_physics.offset-state.bottom_sheet_scroll_offset).abs()>0.1 && state.nested_touch.is_none() {state.nested_physics.cancel();state.nested_physics.offset=state.bottom_sheet_scroll_offset.clamp(0.0,max);}
529            if state.nested_touch.is_none() && state.nested_physics.advance(self.ui.time,max,self.reduced_motion()) {self.ui.continuous=true;}
530            state.bottom_sheet_scroll_offset=state.nested_physics.offset.clamp(0.0,max);
531            let sheet_top=full.y+full.height*(1.0-values[0])+state.drag_displacement;
532            if self.input.pressed && values[0]>0.95 && let Some(point)=self.input.pointer {
533                if point[0]>=full.x && point[0]<full.x+full.width && point[1]>=sheet_top+content_top && point[1]<(sheet_top+full.height).min(viewport.y+viewport.height) {
534                    state.nested_touch=Some(BottomSheetNestedTouch {origin:point[1],last:point[1],last_time:self.ui.time,velocity:0.0,claimed:false,moved_sheet:false});
535                    state.nested_physics.cancel();state.drag_settle=None;
536                }
537            }
538            if let Some(mut touch)=state.nested_touch {
539                if let Some(point)=self.input.pointer {
540                    let delta=touch.last-point[1];touch.claimed|=(point[1]-touch.origin).abs()>6.0;
541                    if touch.claimed && delta.abs()>0.01 {
542                        let dt=(self.ui.time-touch.last_time).clamp(0.001,0.15) as f32;touch.velocity=(delta/dt).clamp(-8000.0,8000.0);
543                        if delta>0.0 {
544                            let sheet=delta.min(state.drag_displacement);state.drag_displacement-=sheet;touch.moved_sheet|=sheet>0.0;
545                            state.bottom_sheet_scroll_offset=(state.bottom_sheet_scroll_offset+delta-sheet).clamp(0.0,max);
546                        } else {
547                            let scroll=(-delta).min(state.bottom_sheet_scroll_offset);state.bottom_sheet_scroll_offset-=scroll;
548                            let before=state.drag_displacement;state.drag_displacement=(before-delta-scroll).min(collapsed);touch.moved_sheet|=state.drag_displacement>before;
549                        }
550                        state.nested_physics.offset=state.bottom_sheet_scroll_offset;self.ui.active=None;
551                    }
552                    if delta.abs()>0.01 {touch.last_time=self.ui.time;}touch.last=point[1];
553                }
554                nested_claimed=touch.claimed;
555                if self.input.released || self.input.cancelled || self.input.blurred {
556                    if touch.claimed {
557                        if touch.moved_sheet && (state.drag_displacement>0.01 || self.input.cancelled || self.input.blurred) {
558                            // BottomSheetBehavior.onStopNestedScroll uses the last touch
559                            // direction, not the child's later non-touch fling velocity.
560                            let current=state.drag_displacement;
561                            let target=if self.input.cancelled || self.input.blurred {target_detent}
562                                else if current<=0.01 {0.0}
563                                else if touch.velocity>0.0 {half_offset.filter(|half|current>*half).unwrap_or(0.0)}
564                                else if touch.velocity<0.0 {half_offset.filter(|half|(current-half).abs()<(current-collapsed).abs()).unwrap_or(collapsed)}
565                                else {sheet_detent(current,collapsed,half_offset,0.0,0.0)};
566                            state.bottom_sheet_expanded=target<=0.01;state.bottom_sheet_half_expanded=half_offset.is_some_and(|half|(target-half).abs()<0.01);
567                            state.drag_settle=Some((self.ui.time,state.drag_displacement,target));self.ui.continuous=true;
568                        } else if !self.input.cancelled && !self.input.blurred && self.ui.time-touch.last_time<=0.12 {
569                            state.bottom_sheet_expanded=true;state.bottom_sheet_half_expanded=false;
570                            state.nested_physics.fling_from_velocity(touch.velocity,self.ui.time,self.reduced_motion());self.ui.continuous=true;
571                        }
572                    }
573                    state.nested_touch=None;
574                } else {state.nested_touch=Some(touch);}
575            }
576        } else if !state.open {state.nested_touch=None;state.nested_physics.cancel();}
577        let drag_offset=if draggable && state.open {state.drag_displacement} else if draggable {state.drag_close_offset*values[0].clamp(0.0,1.0)} else {0.0};
578        let side_drag_offset=if side_draggable && state.open {state.drag_displacement} else if side_draggable {state.drag_close_offset*values[0].clamp(0.0,1.0)} else {0.0};
579        if !state.open && values[0]<0.001 {state.drag_close_offset=0.0;state.drag_displacement=0.0;state.drag_settle=None;state.drag_origin=None;state.side_drag_origin=None;state.drag_last_motion=None;state.drag_velocity=[0.0;2];}
580        let posed = |position: f32| {
581            if fullscreen {
582                full
583            } else if angular && kind == OverlayKind::BottomSheet {
584                Rect {
585                    y: full.y + full.height * (1.0 - position),
586                    ..full
587                }
588            } else if angular {
589                full
590            } else {
591                match kind {
592                    OverlayKind::Menu => Rect {
593                        height: full.height * (0.35 + 0.65 * position),
594                        ..full
595                    },
596                    OverlayKind::Dialog => Rect {
597                        y: full.y - 50.0 * (1.0 - position),
598                        height: full.height * (0.35 + 0.65 * position),
599                        ..full
600                    },
601                    OverlayKind::BottomSheet => Rect {
602                        y: full.y + full.height * (1.0 - position) + drag_offset,
603                        ..full
604                    },
605                    OverlayKind::SideSheet => Rect {
606                        x: full.x + full.width * (1.0 - position) + side_drag_offset,
607                        ..full
608                    },
609                    OverlayKind::LeftSideSheet => Rect {
610                        x: full.x - full.width * (1.0 - position) - side_drag_offset,
611                        ..full
612                    },
613                    OverlayKind::Popover => Rect {
614                        y: full.y + 8.0 * (1.0 - position),
615                        ..full
616                    },
617                }
618            }
619        };
620        if state.open && !state.suspended
621            && (state.dismiss_policy.escape() && self.pressed_key(Key::Escape)
622                || angular && kind == OverlayKind::Menu && self.pressed_key(Key::Tab)
623                || state.dismiss_policy.outside() && self.input.pressed
624                    && self
625                        .input
626                        .pointer
627                        .is_some_and(|p| !posed(values[0]).contains(p)))
628        {
629            state.open = false;
630            self.ui.active = None;
631            self.ui.continuous = true;
632            values = if timed {
633                state.sample(self.ui.time, self.reduced_motion())
634            } else {
635                let position = self.spatial(id, 21, 0.0, 0.0);
636                let alpha = self.animate(id, 20, 0.0, 0.0);
637                [position, alpha, alpha, alpha]
638            };
639        }
640        if timed {
641            self.ui.continuous |= state.moving();
642        }
643        let bounds = posed(values[0]);
644        let alpha = values[1];
645        if timed && !angular {
646            values[3] = 1.0;
647        }
648        if state.open || state.was_open {
649            self.ui.next_focus_order.clear();
650        }
651        if alpha > 0.001 || state.open {
652            let t = self.ui.theme;
653            if modal {
654                self.rect(
655                    self.viewport(),
656                    0.0,
657                    Color(0, 0, 0, 255).opacity(0.32 * values[2]),
658                );
659                for node in &mut self.ui.semantics {
660                    node.enabled = false;
661                }
662            }
663            let start = self.commands.len();
664            let semantics_start = self.ui.semantics.len();
665            let previous_phase = self.overlay_phase;
666            self.overlay_phase = if angular {
667                None
668            } else {
669                Some(OverlayPhase {
670                    id,
671                    open: state.open,
672                    kind: state.kind,
673                })
674            };
675            let origin = if let Some(origin) = state
676                .transform_origin
677                .filter(|p| p.iter().all(|v| v.is_finite()))
678            {
679                origin
680            } else if kind == OverlayKind::Menu {
681                [bounds.x, bounds.y]
682            } else {
683                [
684                    bounds.x + bounds.width / 2.0,
685                    bounds.y + bounds.height / 2.0,
686                ]
687            };
688            let scale = if angular
689                && !fullscreen
690                && !timepicker
691                && matches!(kind, OverlayKind::Menu | OverlayKind::Dialog)
692            {
693                0.8 + 0.2 * values[0]
694            } else {
695                1.0
696            };
697            if datepicker {
698                self.commands.push(DrawCommand::PushScaleY {
699                    origin: bounds.y,
700                    scale: 0.8 + 0.2 * values[0],
701                });
702            }
703            let previous_nested_scroll=self.overlay_nested_scroll;
704            self.overlay_nested_scroll=state.bottom_sheet_scroll_offset;
705            self.with_scale(origin, scale, |f| {
706                let radius = if fullscreen {
707                    0.0
708                } else if angular {
709                    if kind == OverlayKind::Menu || timepicker {
710                        4.0
711                    } else if kind == OverlayKind::Popover {
712                        16.0
713                    } else if kind == OverlayKind::BottomSheet {
714                        0.0
715                    } else {
716                        28.0
717                    }
718                } else if matches!(kind, OverlayKind::BottomSheet | OverlayKind::Dialog) {
719                    28.0
720                } else if matches!(kind, OverlayKind::SideSheet | OverlayKind::LeftSideSheet) {
721                    16.0
722                } else {
723                    20.0
724                };
725                if angular
726                    && (kind == OverlayKind::Menu || timepicker || kind == OverlayKind::BottomSheet)
727                {
728                    f.elevation(bounds, radius, if state.style == OverlayStyle::AndroidMenu {3} else {2});
729                }
730                let surface_color = if state.style == OverlayStyle::AndroidMenu {
731                    t.surface_high
732                } else if angular {
733                    if kind == OverlayKind::BottomSheet {
734                        t.surface_low
735                    } else if kind == OverlayKind::Menu || timepicker {
736                        t.control
737                    } else if kind == OverlayKind::Popover {
738                        t.hovered
739                    } else {
740                        t.background
741                    }
742                } else if kind == OverlayKind::Dialog {
743                    t.surface_high
744                } else if state.style == OverlayStyle::NavigationRail {
745                    t.background
746                } else if state.style == OverlayStyle::NavigationDrawer
747                    || matches!(
748                        kind,
749                        OverlayKind::BottomSheet | OverlayKind::SideSheet | OverlayKind::LeftSideSheet
750                    )
751                {
752                    t.surface_low
753                } else {
754                    t.background.mix(t.secondary, 0.35)
755                };
756                if !angular && !fullscreen && kind == OverlayKind::BottomSheet {
757                    // Extend the rounded shape past the bottom edge, then clip it so
758                    // only the top two 28dp corners are rounded and the bottom sits flush.
759                    f.within(bounds, |f| {
760                        f.rect(
761                            Rect {
762                                height: (bounds.height + radius).max(radius * 2.0),
763                                ..bounds
764                            },
765                            radius,
766                            surface_color,
767                        )
768                    });
769                } else if !angular
770                    && !fullscreen
771                    && state.style != OverlayStyle::NavigationRail
772                    && kind == OverlayKind::SideSheet
773                {
774                    // Extend the rounded shape past the outer right edge, then clip it so
775                    // only the inner (top-left & bottom-left) 16dp corners are rounded.
776                    f.within(bounds, |f| {
777                        f.rect(
778                            Rect {
779                                width: (bounds.width + 16.0).max(32.0),
780                                ..bounds
781                            },
782                            16.0,
783                            surface_color,
784                        )
785                    });
786                } else if !angular
787                    && !fullscreen
788                    && state.style != OverlayStyle::NavigationRail
789                    && kind == OverlayKind::LeftSideSheet
790                {
791                    // Extend the rounded shape past the outer left edge, then clip it so
792                    // only the inner (top-right & bottom-right) 16dp corners are rounded.
793                    f.within(bounds, |f| {
794                        let extend = (bounds.width + 16.0).max(32.0) - bounds.width;
795                        f.rect(
796                            Rect {
797                                x: bounds.x - extend,
798                                width: bounds.width + extend,
799                                ..bounds
800                            },
801                            16.0,
802                            surface_color,
803                        )
804                    });
805                } else {
806                    f.rect(bounds, radius, surface_color);
807                }
808                let body = if fullscreen || (kind==OverlayKind::BottomSheet && state.drag_to_dismiss) || matches!(state.style, OverlayStyle::NavigationRail | OverlayStyle::NavigationDrawer) {
809                    bounds
810                } else if angular {
811                    if kind == OverlayKind::Menu || timepicker {
812                        Rect {
813                            y: bounds.y + 8.0,
814                            height: (bounds.height - 16.0).max(0.0),
815                            ..bounds
816                        }
817                    } else {
818                        bounds
819                    }
820                } else {
821                    Rect {
822                        height: full.height,
823                        ..bounds
824                    }
825                    .inset(16.0)
826                };
827                if modal && kind == OverlayKind::Dialog && state.open {
828                    if let Some(title) = state.accessible_title.as_deref() {
829                        f.semantic(Response { id, bounds, enabled: true, ..Response::default() }, Role::Dialog, title, false, None, None, None);
830                    }
831                    if let Some(description) = state.accessible_description.as_deref() {
832                        f.semantic(Response { id, bounds, enabled: true, ..Response::default() }, Role::DialogDescription, description, false, None, None, None);
833                    }
834                }
835                if angular && kind == OverlayKind::Menu {
836                    f.semantic(
837                        Response {
838                            id,
839                            bounds,
840                            enabled: state.open && f.enabled,
841                            ..Response::default()
842                        },
843                        Role::Menu,
844                        "Menu",
845                        false,
846                        None,
847                        None,
848                        None,
849                    );
850                }
851                let entering_menu = angular && kind == OverlayKind::Menu && values[0] < 1.0;
852                let input = f.input;
853                if entering_menu {
854                    f.input.pointer = None;
855                    f.input.pressed = false;
856                    f.input.released = false;
857                    f.input.scroll = [0.0; 2];
858                }
859                f.without_input(state.suspended || nested_claimed || side_drag_claimed, |f| f.with_enabled(state.open && (alpha > 0.001 || entering_menu), |f| {
860                    f.within(body, |f| build(f, &mut state.open))
861                }));
862                f.input = input;
863            });
864            self.overlay_nested_scroll=previous_nested_scroll;
865            if datepicker {
866                self.commands.push(DrawCommand::PopScaleY);
867            }
868            self.overlay_phase = previous_phase;
869            for (index, command) in self.commands[start..].iter_mut().enumerate() {
870                match command {
871                    DrawCommand::RoundedRect { color, .. }
872                | DrawCommand::Ellipse { color, .. }
873                | DrawCommand::Outline { color, .. }
874                    | DrawCommand::Text { color, .. }
875                    | DrawCommand::Shadow { color, .. }
876                    | DrawCommand::Ripple { color, .. }
877                    | DrawCommand::Loading { color, .. }
878                    | DrawCommand::Shape { color, .. }
879                    | DrawCommand::Image { color, .. }
880                    | DrawCommand::Arc { color, .. }
881                    | DrawCommand::Line { color, .. }
882                    | DrawCommand::Polyline { color, .. } => {
883                        *color = color.opacity(if !angular && index == 0 {
884                            alpha
885                        } else {
886                            values[3]
887                        })
888                    }
889                    _ => {}
890                }
891            }
892            if !state.open {
893                self.ui.semantics.truncate(semantics_start);
894                if state.was_open {
895                    self.ui.next_focus_order.clear();
896                }
897            }
898        }
899        if state.open && !state.suspended && self.ui.focused.is_none() {
900            self.ui.focused = state
901                .initial_focus
902                .filter(|id| self.ui.next_focus_order.contains(id))
903                .or_else(|| self.ui.next_focus_order.first().copied());
904            self.ui.keyboard_focus =
905                state.opened_with_keyboard || angular && kind == OverlayKind::BottomSheet;
906            self.ui.continuous |= angular
907                && matches!(kind, OverlayKind::Menu | OverlayKind::BottomSheet)
908                && self.ui.focused.is_some();
909        }
910        if !state.open && state.was_open {
911            // The background was built disabled earlier in this frame. Restore only
912            // once its owner is enabled again, never to a disabled/removed control.
913            self.ui.pending_focus = state.restore;
914            self.ui.pending_focus_keyboard =
915                self.input.key.is_some() || (self.ui.keyboard_focus && !self.input.pressed);
916            self.ui.keyboard_focus = self.ui.pending_focus_keyboard;
917            self.ui.continuous = true;
918        }
919        self.ui.overlay_active |= state.open;
920        state.was_open = state.open;
921    }
922    /// Direct manipulation handle: pointer movement has no animation lag.
923    #[allow(clippy::too_many_arguments)]
924    pub fn drag_handle(
925        &mut self,
926        id: u64,
927        b: Rect,
928        track: Rect,
929        label: &str,
930        value: &mut f32,
931        range: std::ops::RangeInclusive<f32>,
932        vertical: bool,
933    ) -> Response {
934        let min = *range.start();
935        let max = *range.end();
936        assert!(min.is_finite() && max.is_finite() && min < max);
937        *value = if value.is_finite() {
938            value.clamp(min, max)
939        } else {
940            min
941        };
942        let before = *value;
943        let mut r = self.interact(id, b, true);
944        if r.enabled
945            && r.pressed
946            && self.ui.capture == Capture::Pointer
947            && let Some(p) = self.input.pointer
948        {
949            let (position, start, size) = if vertical {
950                (p[1], track.y, track.height)
951            } else {
952                (p[0], track.x, track.width)
953            };
954            *value = min + ((position - start) / size.max(1.0)).clamp(0.0, 1.0) * (max - min);
955        }
956        if let Some(key) = self.key_for(r) {
957            *value = match key {
958                Key::Left | Key::Up => (*value - 1.0).max(min),
959                Key::Right | Key::Down => (*value + 1.0).min(max),
960                Key::Home => min,
961                Key::End => max,
962                _ => *value,
963            };
964        }
965        r.changed = before != *value;
966        self.semantic(
967            r,
968            Role::Slider,
969            label,
970            false,
971            None,
972            Some(*value),
973            Some([min, max]),
974        );
975        self.focus_ring(r);
976        r
977    }
978    /// Material 3 coplanar adaptive Standard Side Sheet sharing horizontal bounds
979    /// with main content, separated by a 1dp vertical divider, with animated width.
980    pub fn standard_side_sheet(
981        &mut self,
982        id: u64,
983        open: &mut bool,
984        right_edge: bool,
985        width: f32,
986        build_content: impl FnOnce(&mut Self),
987        build_sheet: impl FnOnce(&mut Self),
988    ) {
989        let avail = self.available();
990        let area = self.allocate(avail.height);
991        if area.width <= 0.0 || area.height <= 0.0 {
992            return;
993        }
994        let target_width = if width.is_finite() {
995            width.clamp(0.0, area.width)
996        } else {
997            0.0
998        };
999        let progress = self
1000            .spatial(id, 21, f32::from(*open), f32::from(*open))
1001            .clamp(0.0, 1.0);
1002        let sheet_width = (target_width * progress).min(area.width);
1003        let divider_width = if sheet_width > 0.5 && area.width > sheet_width {
1004            1.0
1005        } else {
1006            0.0
1007        };
1008        let content_width = (area.width - sheet_width - divider_width).max(0.0);
1009        let (content_rect, divider_rect, sheet_rect, inner_sheet_rect) = if right_edge {
1010            let content = Rect {
1011                x: area.x,
1012                y: area.y,
1013                width: content_width,
1014                height: area.height,
1015            };
1016            let divider = Rect {
1017                x: area.x + content_width,
1018                y: area.y,
1019                width: divider_width,
1020                height: area.height,
1021            };
1022            let sheet = Rect {
1023                x: area.x + content_width + divider_width,
1024                y: area.y,
1025                width: sheet_width,
1026                height: area.height,
1027            };
1028            let inner = Rect {
1029                x: sheet.x,
1030                y: sheet.y,
1031                width: target_width.max(sheet_width),
1032                height: sheet.height,
1033            };
1034            (content, divider, sheet, inner)
1035        } else {
1036            let sheet = Rect {
1037                x: area.x,
1038                y: area.y,
1039                width: sheet_width,
1040                height: area.height,
1041            };
1042            let divider = Rect {
1043                x: area.x + sheet_width,
1044                y: area.y,
1045                width: divider_width,
1046                height: area.height,
1047            };
1048            let content = Rect {
1049                x: area.x + sheet_width + divider_width,
1050                y: area.y,
1051                width: content_width,
1052                height: area.height,
1053            };
1054            let inner = Rect {
1055                x: sheet.x + sheet.width - target_width.max(sheet_width),
1056                y: sheet.y,
1057                width: target_width.max(sheet_width),
1058                height: sheet.height,
1059            };
1060            (content, divider, sheet, inner)
1061        };
1062
1063        if content_rect.width > 0.0 {
1064            self.within(content_rect, build_content);
1065        }
1066        if sheet_width > 0.5 {
1067            if divider_width > 0.0 {
1068                self.divider_at(divider_rect, DividerOrientation::Vertical, 0.0, 0.0);
1069            }
1070            let surface = self.ui.theme.background;
1071            self.rect(sheet_rect, 0.0, surface);
1072            let enabled = *open;
1073            self.within(sheet_rect, |f| {
1074                f.with_enabled(enabled, |f| {
1075                    f.within_unclipped(inner_sheet_rect, build_sheet);
1076                });
1077            });
1078        }
1079        if *open && !self.key_consumed && self.pressed_key(Key::Escape) {
1080            *open = false;
1081            self.key_consumed = true;
1082            self.ui.continuous = true;
1083        }
1084    }
1085
1086    /// Standard Material 3 dialog content layout (24sp title, body paragraph, Cancel/Confirm text actions).
1087    /// Returns `(cancel_clicked, confirm_clicked)`.
1088    pub fn dialog_chrome(
1089        &mut self,
1090        id: u64,
1091        title: &str,
1092        body: &str,
1093        cancel_label: Option<&str>,
1094        confirm_label: &str,
1095    ) -> (bool, bool) {
1096        let t = self.theme();
1097        let b = self.available();
1098        self.styled_text(
1099            Rect { x: b.x + 24.0, y: b.y + 16.0, width: (b.width - 48.0).max(0.0), height: 36.0 },
1100            title,
1101            t.text,
1102            TextStyle { size: 24.0, ..TextStyle::default() },
1103        );
1104        self.paragraph(
1105            Rect {
1106                x: b.x + 24.0,
1107                y: b.y + 60.0,
1108                width: (b.width - 48.0).max(0.0),
1109                height: (b.height - 124.0).max(24.0),
1110            },
1111            body,
1112            t.on_surface_variant,
1113            TextStyle { size: 14.0, ..TextStyle::default() },
1114            20.0,
1115        );
1116        let btn_y = (b.y + b.height - 56.0).max(b.y + 84.0);
1117        let conf_w = (self.text_width(confirm_label, TextStyle::LABEL) + 24.0).max(64.0);
1118        let conf_rect = Rect {
1119            x: (b.x + b.width - 20.0 - conf_w).max(b.x + 16.0),
1120            y: btn_y,
1121            width: conf_w,
1122            height: 40.0,
1123        };
1124        let confirm = self
1125            .action_at(
1126                id.wrapping_add(1),
1127                conf_rect,
1128                confirm_label,
1129                Options { variant: ButtonVariant::Text, ..Options::default() },
1130            )
1131            .clicked;
1132        let cancel = if let Some(c_label) = cancel_label {
1133            let canc_w = (self.text_width(c_label, TextStyle::LABEL) + 24.0).max(64.0);
1134            let canc_rect = Rect {
1135                x: (conf_rect.x - 8.0 - canc_w).max(b.x + 16.0),
1136                y: btn_y,
1137                width: canc_w,
1138                height: 40.0,
1139            };
1140            self.action_at(
1141                id,
1142                canc_rect,
1143                c_label,
1144                Options { variant: ButtonVariant::Text, ..Options::default() },
1145            )
1146            .clicked
1147        } else {
1148            false
1149        };
1150        (cancel, confirm)
1151    }
1152
1153    /// Material 3 Full-Screen Dialog header bar (Close X + 22sp title + Save action + divider).
1154    /// Returns `(close_clicked, action_clicked)`.
1155    pub fn fullscreen_dialog_header(&mut self, id: u64, title: &str, action_label: &str) -> (bool, bool) {
1156        let t = self.theme();
1157        let bar = self.reserve(56.0);
1158        let close_rect = Rect { x: bar.x + 4.0, y: bar.y + 4.0, width: 48.0, height: 48.0 };
1159        let close = self
1160            .material_icon_button_at(
1161                id,
1162                close_rect,
1163                MaterialIcon::Close,
1164                "Close",
1165                Options { variant: ButtonVariant::Text, ..Options::default() },
1166            )
1167            .clicked;
1168        let act_w = (self.text_width(action_label, TextStyle::LABEL) + 24.0).clamp(64.0, (bar.width * 0.4).max(64.0));
1169        let act_rect = Rect {
1170            x: (bar.x + bar.width - act_w - 8.0).max(bar.x + 56.0),
1171            y: bar.y + 8.0,
1172            width: act_w,
1173            height: 40.0,
1174        };
1175        let action = self
1176            .action_at(
1177                id.wrapping_add(1),
1178                act_rect,
1179                action_label,
1180                Options { variant: ButtonVariant::Text, ..Options::default() },
1181            )
1182            .clicked;
1183        self.styled_text(
1184            Rect {
1185                x: bar.x + 64.0,
1186                y: bar.y,
1187                width: (act_rect.x - (bar.x + 64.0) - 8.0).max(0.0),
1188                height: bar.height,
1189            },
1190            title,
1191            t.text,
1192            TextStyle { size: 22.0, ..TextStyle::default() },
1193        );
1194        self.paint_line([bar.x, bar.y + bar.height], [bar.x + bar.width, bar.y + bar.height], 1.0, t.outline_variant);
1195        (close, action)
1196    }
1197
1198    /// Centered Material 3 bottom sheet drag handle pill (`32dp × 4dp`, 22dp vertical touch margin).
1199    pub fn bottom_sheet_drag_handle(&mut self) {
1200        let row = self.reserve(28.0);
1201        let pill = Rect {
1202            x: row.x + (row.width - 32.0) * 0.5,
1203            y: row.y + (row.height - 4.0) * 0.5,
1204            width: 32.0,
1205            height: 4.0,
1206        };
1207        self.paint_rect(pill, 2.0, self.theme().on_surface_variant.opacity(0.4));
1208    }
1209
1210    /// Material 3 Side Sheet header row (22sp title + trailing Close icon button + bottom divider).
1211    /// Returns `true` when the close button is clicked.
1212    pub fn side_sheet_header(&mut self, id: u64, title: &str) -> bool {
1213        let t = self.theme();
1214        let bar = self.reserve(56.0);
1215        let close_rect = Rect {
1216            x: (bar.x + bar.width - 52.0).max(bar.x),
1217            y: bar.y + 4.0,
1218            width: 48.0,
1219            height: 48.0,
1220        };
1221        self.styled_text(
1222            Rect {
1223                x: bar.x + 24.0,
1224                y: bar.y,
1225                width: (close_rect.x - (bar.x + 24.0) - 8.0).max(0.0),
1226                height: bar.height,
1227            },
1228            title,
1229            t.text,
1230            TextStyle { size: 22.0, ..TextStyle::default() },
1231        );
1232        let closed = self
1233            .material_icon_button_at(
1234                id,
1235                close_rect,
1236                MaterialIcon::Close,
1237                "Close",
1238                Options { variant: ButtonVariant::Text, ..Options::default() },
1239            )
1240            .clicked;
1241        self.paint_line([bar.x, bar.y + bar.height], [bar.x + bar.width, bar.y + bar.height], 1.0, t.outline_variant);
1242        closed
1243    }
1244}
1245
1246#[cfg(test)]
1247#[path = "overlay.spec.rs"]
1248mod tests;