Skip to main content

bhoo/systems/material/
toolbar.rs

1use crate::*;
2
3/// Placement and surface style for a Material-inspired toolbar.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum ToolbarKind {
6    Docked,
7    FloatingHorizontal,
8    FloatingVertical,
9}
10
11#[derive(Clone, Copy, Debug)]
12pub struct ToolbarAction<'a> {
13    pub label: &'a str,
14    pub enabled: bool,
15}
16/// Logical FAB position beside a floating toolbar (start/top or end/bottom).
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum ToolbarFabPosition { Start, End }
19
20/// Action returned by a floating toolbar paired with a FAB.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum ToolbarFabSelection { Action(usize), Fab }
23
24/// Persistent tab stop for an arrow-navigable toolbar.
25#[derive(Default)]
26pub struct ToolbarState {
27    index: usize,
28    overlay: OverlayState,
29    offset: f32,
30    drag_origin: Option<f32>,
31    drag_last: Option<f32>,
32    dragging: bool,
33    drag_velocity: f32,
34    drag_sample_time: f64,
35    drag_motion_time: f64,
36    fling_velocity: f32,
37    fling_curve: crate::scroll::SplineFling,
38    docked_icons: Vec<AppBarIcon>,
39    primary: Option<usize>,
40    overflow_trigger: Option<usize>,
41    typeahead: MenuTypeaheadState,
42}
43impl ToolbarState {
44    pub fn overflow_open(&self) -> bool {
45        self.overlay.open
46    }
47}
48/// Caller-owned Android-style hide-on-scroll transition for a bottom-docked toolbar.
49#[derive(Default)]
50pub struct DockedToolbarScrollState {
51    hidden: bool,
52    progress: crate::timing::Tween,
53}
54
55/// Hysteresis for expanding or collapsing a floating toolbar from consumed scroll.
56#[derive(Default)]
57pub struct FloatingToolbarExpansionScrollState {
58    offset:f32,
59    threshold:f32,
60    previous:Option<bool>,
61    thresholds:Option<(f32,f32)>,
62}
63impl FloatingToolbarExpansionScrollState {
64    /// Positive consumed scroll means content moved down; reverse changes that policy.
65    /// Thresholds are logical pixels; invalid values use the Material 40 dp default.
66    pub fn update(&mut self, expanded:&mut bool, consumed:f32, reverse:bool, expand_threshold:f32, collapse_threshold:f32)->bool {
67        let valid=|v:f32|if v.is_finite() && v>=0.0 {v} else {40.0};
68        let expand_threshold=valid(expand_threshold);let collapse_threshold=valid(collapse_threshold);
69        if self.previous!=Some(*expanded) || self.thresholds!=Some((expand_threshold,collapse_threshold)) {
70            self.threshold=if *expanded {self.offset-collapse_threshold}else{self.offset+expand_threshold};
71            self.previous=Some(*expanded);self.thresholds=Some((expand_threshold,collapse_threshold));
72        }
73        if !consumed.is_finite() || consumed==0.0 {return false;}
74        let delta=if reverse {consumed}else{-consumed};
75        self.offset=(self.offset+delta).clamp(-1_000_000.0,1_000_000.0);
76        let before=*expanded;
77        if delta<0.0 && self.offset<=self.threshold {*expanded=false;self.threshold=self.offset+expand_threshold;}
78        else if delta>0.0 && self.offset>=self.threshold {*expanded=true;self.threshold=self.offset-collapse_threshold;}
79        self.previous=Some(*expanded);
80        if self.offset.abs()>500_000.0 {self.threshold-=self.offset;self.offset=0.0;}
81        before!=*expanded
82    }
83}
84
85/// Dock edge used to resolve automatic system-inset padding.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub enum DockedToolbarEdge {
88    Top,
89    #[default]
90    Bottom,
91}
92
93/// Insets supplied by the host after combining system bars, cutouts, and IME.
94#[derive(Clone, Copy, Debug)]
95pub struct DockedToolbarInsets {
96    pub top: f32,
97    pub bottom: f32,
98    pub apply_top: Option<bool>,
99    pub apply_bottom: Option<bool>,
100    pub edge: DockedToolbarEdge,
101    pub fits_system_windows: bool,
102}
103impl Default for DockedToolbarInsets {
104    fn default() -> Self {
105        Self {
106            top: 0.0,
107            bottom: 0.0,
108            apply_top: None,
109            apply_bottom: None,
110            edge: DockedToolbarEdge::Bottom,
111            fits_system_windows: true,
112        }
113    }
114}
115impl DockedToolbarInsets {
116    /// Split a caller-supplied total surface into background and 64 dp content.
117    /// The bounds must include enough space for the requested insets.
118    pub fn content_bounds(self, bounds: Rect) -> Option<Rect> {
119        if !bounds.x.is_finite()
120            || !bounds.y.is_finite()
121            || !bounds.width.is_finite()
122            || !bounds.height.is_finite()
123            || bounds.width < 0.0
124            || bounds.height < 0.0
125        {
126            return None;
127        }
128        let top = if self
129            .apply_top
130            .unwrap_or(self.fits_system_windows && self.edge == DockedToolbarEdge::Top)
131            && self.top.is_finite()
132        {
133            self.top.max(0.0)
134        } else {
135            0.0
136        };
137        let bottom = if self
138            .apply_bottom
139            .unwrap_or(self.fits_system_windows && self.edge == DockedToolbarEdge::Bottom)
140            && self.bottom.is_finite()
141        {
142            self.bottom.max(0.0)
143        } else {
144            0.0
145        };
146        let height = bounds.height - top - bottom;
147        if height < 64.0 {
148            return None;
149        }
150        Some(Rect {
151            y: bounds.y + top,
152            height,
153            ..bounds
154        })
155    }
156}
157
158impl Frame<'_> {
159    /// Draw a docked or floating action toolbar. The caller owns placement,
160    /// actions, and any overflow policy; returns the activated action index.
161    pub fn toolbar(
162        &mut self,
163        id: u64,
164        bounds: Rect,
165        kind: ToolbarKind,
166        vibrant: bool,
167        actions: &[ToolbarAction<'_>],
168    ) -> Option<usize> {
169        self.toolbar_inner(id, bounds, kind, vibrant, actions, None, false)
170    }
171    /// Toolbar with one tab stop and arrow-key navigation.
172    #[allow(clippy::too_many_arguments)]
173    pub fn toolbar_roving(
174        &mut self,
175        id: u64,
176        bounds: Rect,
177        kind: ToolbarKind,
178        vibrant: bool,
179        actions: &[ToolbarAction<'_>],
180        state: &mut ToolbarState,
181        rtl: bool,
182    ) -> Option<usize> {
183        if state.overlay.open {
184            state.overlay = OverlayState::default();
185            if let Some(index) = actions.iter().position(|action| action.enabled)
186                && let Some(focus_id) = id.checked_add(index as u64)
187            {
188                state.index = index;
189                self.request_focus(focus_id);
190            }
191        }
192        state.typeahead.reset();
193        state.fling_velocity = 0.0;
194        state.docked_icons.clear();
195        state.primary = None;
196        state.overflow_trigger = None;
197        self.toolbar_inner(id, bounds, kind, vibrant, actions, Some(state), rtl)
198    }
199    /// Sample bottom-edge hide-on-scroll. Positive consumed deltas hide; negative show.
200    /// Touch exploration forces visibility; the caller must reserve content padding.
201    pub fn docked_toolbar_scroll_offset(
202        &mut self,
203        state: &mut DockedToolbarScrollState,
204        consumed: f32,
205        height: f32,
206        touch_exploration: bool,
207    ) -> f32 {
208        use crate::timing::{Easing, TweenSpec};
209        if touch_exploration {
210            state.hidden = false;
211        } else if consumed.is_finite() && consumed != 0.0 {
212            state.hidden = consumed > 0.0;
213        }
214        let height = if height.is_finite() {
215            height.max(0.0)
216        } else {
217            0.0
218        };
219        let progress = state.progress.sample(
220            self.ui.time,
221            f32::from(state.hidden),
222            TweenSpec::new(0.175, Easing::Emphasized),
223            TweenSpec::new(0.225, Easing::Emphasized),
224            self.reduced_motion() || touch_exploration,
225        );
226        self.ui.continuous |= state.progress.moving();
227        progress.clamp(0.0, 1.0) * height
228    }
229
230    /// Bottom-anchored floating toolbar hide-on-scroll offset. `hide_distance`
231    /// includes the toolbar height and its gap to the viewport's bottom edge.
232    pub fn floating_toolbar_scroll_offset(
233        &mut self,
234        state: &mut DockedToolbarScrollState,
235        consumed: f32,
236        hide_distance: f32,
237    ) -> f32 {
238        self.docked_toolbar_scroll_offset(state, consumed, hide_distance, false)
239    }
240
241    /// Docked toolbar whose background also fills host-supplied system insets.
242    #[allow(clippy::too_many_arguments)]
243    pub fn docked_toolbar_with_insets(
244        &mut self,
245        id: u64,
246        bounds: Rect,
247        insets: DockedToolbarInsets,
248        vibrant: bool,
249        actions: &[ToolbarAction<'_>],
250        icons: &[AppBarIcon],
251        primary: Option<usize>,
252        state: &mut ToolbarState,
253        rtl: bool,
254    ) -> Option<usize> {
255        let content = insets.content_bounds(bounds)?;
256        let t = self.ui.theme;
257        self.paint_rect(
258            bounds,
259            0.0,
260            if vibrant {
261                t.primary_container
262            } else {
263                t.control
264            },
265        );
266        self.docked_toolbar_with_overflow(id, content, vibrant, actions, icons, primary, state, rtl)
267    }
268
269    /// Android-style 64 dp docked toolbar with icon actions and optional primary action.
270    #[allow(clippy::too_many_arguments)]
271    pub fn docked_toolbar_with_overflow(
272        &mut self,
273        id: u64,
274        bounds: Rect,
275        vibrant: bool,
276        actions: &[ToolbarAction<'_>],
277        icons: &[AppBarIcon],
278        primary: Option<usize>,
279        state: &mut ToolbarState,
280        rtl: bool,
281    ) -> Option<usize> {
282        if icons.len() != actions.len() {
283            return None;
284        }
285        state.docked_icons.clear();
286        state.docked_icons.extend_from_slice(icons);
287        state.primary = primary.filter(|i| *i < actions.len());
288        self.toolbar_overflow_inner(
289            id,
290            bounds,
291            ToolbarKind::Docked,
292            vibrant,
293            actions,
294            state,
295            rtl,
296        )
297    }
298    /// Floating toolbar and 56 dp FAB separated by the Material 8 dp gap.
299    /// The FAB uses `id + 132`; toolbar and overflow reserve `id..=id + 131`.
300    /// Bounds too small for a FAB, gap and one toolbar slot return no action.
301    #[allow(clippy::too_many_arguments)]
302    pub fn floating_toolbar_with_fab(
303        &mut self, id:u64, bounds:Rect, kind:ToolbarKind, vibrant:bool,
304        actions:&[ToolbarAction<'_>], state:&mut ToolbarState, rtl:bool,
305        fab:ToolbarAction<'_>, icon:AppBarIcon, position:ToolbarFabPosition,
306    )->Option<ToolbarFabSelection> {
307        let fab_id=id.checked_add(132)?;
308        if kind==ToolbarKind::Docked || ![bounds.x,bounds.y,bounds.width,bounds.height].iter().all(|v|v.is_finite()) {return None;}
309        let vertical=kind==ToolbarKind::FloatingVertical;
310        let (length,cross)=if vertical {(bounds.height,bounds.width)}else{(bounds.width,bounds.height)};
311        if length<128.0 || cross<56.0 {return None;}
312        let leading=if vertical {position==ToolbarFabPosition::Start}else{(position==ToolbarFabPosition::Start)^rtl};
313        let fab_bounds=if vertical {Rect{x:bounds.x+(bounds.width-56.0)*0.5,y:if leading{bounds.y}else{bounds.y+bounds.height-56.0},width:56.0,height:56.0}}
314            else {Rect{x:if leading{bounds.x}else{bounds.x+bounds.width-56.0},y:bounds.y+(bounds.height-56.0)*0.5,width:56.0,height:56.0}};
315        let bar=if vertical {Rect{x:bounds.x,y:bounds.y+if leading{64.0}else{0.0},width:bounds.width,height:bounds.height-64.0}}
316            else {Rect{x:bounds.x+if leading{64.0}else{0.0},y:bounds.y,width:bounds.width-64.0,height:bounds.height}};
317        self.elevation_dp(bar,bar.width.min(bar.height)*0.5,1.0);
318        let action=self.toolbar_with_overflow(id,bar,kind,vibrant,actions,state,rtl);
319        let mut clicked=false;
320        self.without_input(state.overflow_open(),|f|f.within_unclipped(fab_bounds,|f|{
321            clicked=f.fab_with_options(fab_id,fab.label,icon,crate::FabOptions{size:56.0,enabled:fab.enabled,elevation:crate::FabElevation::FloatingToolbar,color:if vibrant{crate::FabColor::Tertiary}else{crate::FabColor::Primary},..crate::FabOptions::default()}).clicked;
322        }));
323        if clicked {Some(ToolbarFabSelection::Fab)} else {action.map(ToolbarFabSelection::Action)}
324    }
325
326    /// Expandable floating toolbar paired with a 56–80 dp FAB. The caller owns
327    /// the expanded state and supplies stable bounds with at least 80 dp cross size.
328    /// Toolbar actions stop accepting input immediately when collapse is requested.
329    #[allow(clippy::too_many_arguments)]
330    pub fn floating_toolbar_with_fab_expanded(
331        &mut self, id:u64, bounds:Rect, kind:ToolbarKind, vibrant:bool,
332        actions:&[ToolbarAction<'_>], state:&mut ToolbarState, rtl:bool,
333        fab:ToolbarAction<'_>, icon:AppBarIcon, position:ToolbarFabPosition, expanded:bool,
334    )->Option<ToolbarFabSelection> {
335        let fab_id=id.checked_add(132)?;
336        if kind==ToolbarKind::Docked || ![bounds.x,bounds.y,bounds.width,bounds.height].iter().all(|v|v.is_finite()) {return None;}
337        let vertical=kind==ToolbarKind::FloatingVertical;
338        let (length,cross)=if vertical {(bounds.height,bounds.width)}else{(bounds.width,bounds.height)};
339        if length<144.0 || cross<80.0 {return None;}
340        let target=f32::from(expanded);
341        let progress=self.animate_geometry(id,239,target,target).clamp(0.0,1.0);
342        let fab_size=80.0-24.0*progress;
343        let bar_length=(length-64.0)*progress;
344        let leading=if vertical {position==ToolbarFabPosition::Start}else{(position==ToolbarFabPosition::Start)^rtl};
345        let fab_bounds=if vertical {Rect{x:bounds.x+(cross-fab_size)*0.5,y:if leading{bounds.y}else{bounds.y+length-fab_size},width:fab_size,height:fab_size}}
346            else {Rect{x:if leading{bounds.x}else{bounds.x+length-fab_size},y:bounds.y+(cross-fab_size)*0.5,width:fab_size,height:fab_size}};
347        let bar=if vertical {Rect{x:bounds.x+(cross-64.0)*0.5,y:if leading{bounds.y+64.0}else{bounds.y+length-64.0-bar_length},width:64.0,height:bar_length}}
348            else {Rect{x:if leading{bounds.x+64.0}else{bounds.x+length-64.0-bar_length},y:bounds.y+(cross-64.0)*0.5,width:bar_length,height:64.0}};
349        if !expanded {state.overlay=OverlayState::default();}
350        self.elevation_dp(bar,bar.width.min(bar.height)*0.5,progress);
351        let mut action=None;
352        if bar_length>=64.0 {
353            self.without_input(!expanded,|f|{action=f.toolbar_with_overflow(id,bar,kind,vibrant,actions,state,rtl);});
354        } else if bar_length>0.0 {
355            let t=self.ui.theme;self.paint_rect(bar,bar.width.min(bar.height)*0.5,if vibrant{t.primary_container}else{t.control});
356        }
357        let mut clicked=false;
358        self.without_input(state.overflow_open(),|f|f.within_unclipped(fab_bounds,|f|{
359            clicked=f.fab_with_options(fab_id,fab.label,icon,crate::FabOptions{size:fab_size,enabled:fab.enabled,elevation:crate::FabElevation::FloatingToolbar,color:if vibrant{crate::FabColor::Tertiary}else{crate::FabColor::Primary},..crate::FabOptions::default()}).clicked;
360        }));
361        if clicked {Some(ToolbarFabSelection::Fab)} else {action.map(ToolbarFabSelection::Action)}
362    }
363
364    /// Toolbar with a menu for actions that do not fit. Supports up to 64 actions.
365    /// IDs `id..=id+131` are reserved; returns the original action index.
366    #[allow(clippy::too_many_arguments)]
367    pub fn toolbar_with_overflow(
368        &mut self,
369        id: u64,
370        bounds: Rect,
371        kind: ToolbarKind,
372        vibrant: bool,
373        actions: &[ToolbarAction<'_>],
374        state: &mut ToolbarState,
375        rtl: bool,
376    ) -> Option<usize> {
377        state.docked_icons.clear();
378        state.primary = None;
379        self.toolbar_overflow_inner(id, bounds, kind, vibrant, actions, state, rtl)
380    }
381    #[allow(clippy::too_many_arguments)]
382    fn toolbar_overflow_inner(
383        &mut self,
384        id: u64,
385        bounds: Rect,
386        kind: ToolbarKind,
387        vibrant: bool,
388        actions: &[ToolbarAction<'_>],
389        state: &mut ToolbarState,
390        rtl: bool,
391    ) -> Option<usize> {
392        if actions.len() > 64 {
393            return None;
394        }
395        id.checked_add(131)?;
396        let vertical = kind == ToolbarKind::FloatingVertical;
397        let available = if vertical {
398            bounds.height
399        } else {
400            bounds.width
401        };
402        let docked_icons = kind == ToolbarKind::Docked && !state.docked_icons.is_empty();
403        let padding = if docked_icons { 32.0 } else { 16.0 };
404        let slots = ((available - padding).max(0.0) / 48.0) as usize;
405        if slots == 0 || actions.len() <= slots {
406            state.overflow_trigger = None;
407            state.typeahead.reset();
408            state.fling_velocity = 0.0;
409            if state.overlay.open {
410                state.overlay = OverlayState::default();
411                if slots > 0
412                    && let Some(index) = actions.iter().take(slots).position(|a| a.enabled)
413                {
414                    state.index = index;
415                    self.request_focus(id + index as u64);
416                }
417            }
418            return self.toolbar_inner(id, bounds, kind, vibrant, actions, Some(state), rtl);
419        }
420        let visible = slots - 1;
421        state.overflow_trigger = Some(visible);
422        let mut shown = actions[..visible].to_vec();
423        shown.push(ToolbarAction {
424            label: "More",
425            enabled: true,
426        });
427        let mut selected = None;
428        self.without_input(state.overlay.open, |f| {
429            selected = f.toolbar_inner(id, bounds, kind, vibrant, &shown, Some(state), rtl);
430        });
431        if selected == Some(visible) {
432            selected = None;
433            state.overlay.open = true;
434            state.offset = 0.0;
435        }
436        let viewport = self.viewport();
437        let trigger = if docked_icons {
438            let cell = (bounds.width - 32.0) / slots as f32;
439            let slot = if rtl { slots - 1 - visible } else { visible };
440            Rect {
441                x: bounds.x + 16.0 + slot as f32 * cell + (cell - 48.0) / 2.0,
442                y: bounds.y + (bounds.height - 48.0) / 2.0,
443                width: 48.0,
444                height: 48.0,
445            }
446        } else if vertical {
447            Rect {
448                x: bounds.x + (bounds.width - 48.0) / 2.0,
449                y: bounds.y + 8.0 + visible as f32 * 48.0,
450                width: 48.0,
451                height: 48.0,
452            }
453        } else {
454            Rect {
455                x: if rtl {
456                    bounds.x + bounds.width - 56.0 - visible as f32 * 48.0
457                } else {
458                    bounds.x + 8.0 + visible as f32 * 48.0
459                },
460                y: bounds.y + (bounds.height - 48.0) / 2.0,
461                width: 48.0,
462                height: 48.0,
463            }
464        };
465        let remaining = &actions[visible..];
466        let width = remaining
467            .iter()
468            .map(|a| {
469                self.text_width(a.label, TextStyle::LABEL) + if docked_icons { 72.0 } else { 48.0 }
470            })
471            .fold(112.0_f32, f32::max)
472            .min(280.0)
473            .min(viewport.width);
474        let below = (viewport.y + viewport.height - trigger.y - trigger.height).max(0.0);
475        let above = (trigger.y - viewport.y).max(0.0);
476        let down = below >= above;
477        let height = (remaining.len() as f32 * 48.0 + 16.0).min(if down { below } else { above });
478        let menu_bounds = Rect {
479            x: if rtl {
480                (trigger.x + trigger.width - width).max(viewport.x)
481            } else {
482                trigger.x.min(viewport.x + viewport.width - width)
483            },
484            y: if down {
485                trigger.y + trigger.height
486            } else {
487                trigger.y - height
488            },
489            width,
490            height,
491        };
492        let body = (height - 16.0).max(0.0);
493        let max_offset = (remaining.len() as f32 * 48.0 - body).max(0.0);
494        state.offset = state.offset.clamp(0.0, max_offset);
495        if !state.overlay.open
496            || self.input.pressed
497            || self.input.cancelled
498            || self.input.blurred
499            || self.reduced_motion()
500            || self.input.scroll[1] != 0.0
501            || self.input.key.is_some()
502        {
503            state.fling_velocity = 0.0;
504        }
505        if state.fling_velocity != 0.0 {
506            let (movement, moving) = state.fling_curve.step(self.ui.time);
507            let old = state.offset;
508            state.offset = (old + movement).clamp(0.0, max_offset);
509            if !moving { state.fling_velocity = 0.; }
510            if state.fling_velocity.abs() < 20.0 || (state.offset - old - movement).abs() > 0.5 {
511                state.fling_velocity = 0.0;
512            } else {
513                self.ui.continuous = true;
514            }
515        }
516        let first_id = id + 66;
517        if state.overlay.open {
518            let scroll = self.scroll_y(menu_bounds);
519            if scroll.is_finite() {
520                state.offset = (state.offset + scroll).clamp(0.0, max_offset);
521            }
522            if max_offset > 0.0 && self.input.pointer_kind == PointerKind::Touch {
523                if self.input.pressed && self.pointer_in(menu_bounds) {
524                    state.drag_origin = self.input.pointer.map(|p| p[1]);
525                    state.drag_last = state.drag_origin;
526                    state.dragging = false;
527                    state.drag_velocity = 0.0;
528                    state.drag_sample_time = self.ui.time;
529                    state.drag_motion_time = self.ui.time;
530                } else if let (Some(origin), Some(last), Some(pointer)) =
531                    (state.drag_origin, state.drag_last, self.input.pointer)
532                {
533                    if (pointer[1] - origin).abs() > 4.0 {
534                        state.dragging = true;
535                    }
536                    if state.dragging {
537                        let movement = last - pointer[1];
538                        state.offset = (state.offset + movement).clamp(0.0, max_offset);
539                        if movement != 0.0 {
540                            let elapsed = self.ui.time - state.drag_sample_time;
541                            state.drag_velocity = if (0.005..=0.15).contains(&elapsed) {
542                                (movement / elapsed as f32).clamp(-4000.0, 4000.0)
543                            } else {
544                                0.0
545                            };
546                            state.drag_sample_time = self.ui.time;
547                            state.drag_motion_time = self.ui.time;
548                        }
549                        state.drag_last = Some(pointer[1]);
550                        self.ui.active = None;
551                    }
552                }
553            }
554            if self.input.key.is_some_and(|key| key.pressed)
555                || self.input.blurred
556                || self.input.cancelled
557            {
558                let items: Vec<_> = remaining
559                    .iter()
560                    .map(|action| (action.label, action.enabled))
561                    .collect();
562                if let Some(next) = self.menu_typeahead(&mut state.typeahead, first_id, &items) {
563                    let top = next as f32 * 48.0;
564                    if top < state.offset {
565                        state.offset = top;
566                    } else if top + 48.0 > state.offset + body {
567                        state.offset = (top + 48.0 - body).min(max_offset);
568                    }
569                }
570            }
571            if let Some(current) = self
572                .focused_id()
573                .and_then(|v| v.checked_sub(first_id))
574                .and_then(|v| usize::try_from(v).ok())
575                .filter(|i| *i < remaining.len())
576            {
577                let key = self.input.key.filter(|k| k.pressed).map(|k| k.key);
578                if matches!(key, Some(Key::Up | Key::Down | Key::Home | Key::End)) {
579                    let next = (0..remaining.len())
580                        .map(|step| match key {
581                            Some(Key::Home) => step,
582                            Some(Key::End) => remaining.len() - 1 - step,
583                            Some(Key::Down) => (current + step + 1) % remaining.len(),
584                            _ => (current + remaining.len() - 1 - step) % remaining.len(),
585                        })
586                        .find(|i| remaining[*i].enabled);
587                    if let Some(next) = next {
588                        let top = next as f32 * 48.0;
589                        if top < state.offset {
590                            state.offset = top;
591                        } else if top + 48.0 > state.offset + body {
592                            state.offset = (top + 48.0 - body).min(max_offset);
593                        }
594                        self.request_focus(first_id + next as u64);
595                        self.key_consumed = true;
596                    }
597                }
598            }
599        }
600        if !state.overlay.open {
601            state.typeahead.reset();
602        }
603        if self.input.released || self.input.cancelled || self.input.blurred || !state.overlay.open
604        {
605            if state.dragging {
606                self.ui.active = None;
607                if self.input.released
608                    && !self.input.cancelled
609                    && !self.input.blurred
610                    && state.overlay.open
611                    && !self.reduced_motion()
612                    && self.ui.time - state.drag_motion_time <= 0.1
613                    && state.drag_velocity.abs() >= 350.0
614                {
615                    state.fling_velocity = state.drag_velocity;
616                    state.fling_curve.start(state.fling_velocity,self.ui.time);
617                            self.ui.continuous = true;
618                }
619            }
620            state.drag_origin = None;
621            state.drag_last = None;
622            state.dragging = false;
623        }
624        state.overlay.kind = OverlayKind::Menu;
625        state.overlay.style = OverlayStyle::AngularMaterial;
626        state.overlay.initial_focus = remaining
627            .iter()
628            .position(|a| a.enabled)
629            .map(|i| first_id + i as u64);
630        let overlay_start = self.commands.len();
631        self.overlay(
632            id + 131,
633            &mut state.overlay,
634            menu_bounds,
635            false,
636            |f, open| {
637                let content = f.available();
638                f.within(content, |f| {
639                    f.within(
640                        Rect {
641                            y: content.y - state.offset,
642                            height: remaining.len() as f32 * 48.0,
643                            ..content
644                        },
645                        |f| {
646                            f.with_gap(0.0, |f| {
647                                for (i, action) in remaining.iter().enumerate() {
648                                    let response = if docked_icons {
649                                        f.menu_item_with_icon(
650                                            first_id + i as u64,
651                                            action.label,
652                                            action.enabled,
653                                            state.docked_icons[visible + i],
654                                            rtl,
655                                        )
656                                    } else {
657                                        f.menu_item(
658                                            first_id + i as u64,
659                                            action.label,
660                                            action.enabled,
661                                        )
662                                    };
663                                    if response.clicked {
664                                        selected = Some(visible + i);
665                                        *open = false;
666                                    }
667                                }
668                            })
669                        },
670                    );
671                });
672            },
673        );
674        self.ui
675            .overlays
676            .extend(self.commands.drain(overlay_start..));
677        selected
678    }
679    #[allow(clippy::too_many_arguments)]
680    fn toolbar_inner(
681        &mut self,
682        id: u64,
683        bounds: Rect,
684        kind: ToolbarKind,
685        vibrant: bool,
686        actions: &[ToolbarAction<'_>],
687        mut state: Option<&mut ToolbarState>,
688        rtl: bool,
689    ) -> Option<usize> {
690        id.checked_add(actions.len() as u64)?;
691        let docked_icons = kind == ToolbarKind::Docked
692            && state.as_ref().is_some_and(|s| !s.docked_icons.is_empty());
693        let t = self.ui.theme;
694        let background = if vibrant {
695            t.primary_container
696        } else if docked_icons || kind != ToolbarKind::Docked {
697            t.control
698        } else {
699            t.surface_variant
700        };
701        let foreground = if vibrant {
702            t.on_primary_container
703        } else if docked_icons {
704            t.on_surface_variant
705        } else {
706            t.text
707        };
708        let vertical = kind == ToolbarKind::FloatingVertical;
709        let floating = kind != ToolbarKind::Docked;
710        self.paint_rect(
711            bounds,
712            if floating {
713                bounds.width.min(bounds.height) / 2.0
714            } else {
715                0.0
716            },
717            background,
718        );
719        let available = if vertical {
720            bounds.height
721        } else {
722            bounds.width
723        };
724        let count = actions
725            .len()
726            .min(((available - if docked_icons { 32.0 } else { 16.0 }).max(0.0) / 48.0) as usize);
727        let primary = state.as_ref().and_then(|s| s.primary);
728        let overflow_trigger = state.as_ref().and_then(|s| s.overflow_trigger);
729        let item_bounds = |i: usize| {
730            if vertical {
731                Rect {
732                    x: bounds.x + (bounds.width - 48.0) / 2.0,
733                    y: bounds.y + 8.0 + i as f32 * 48.0,
734                    width: 48.0,
735                    height: 48.0,
736                }
737            } else if docked_icons {
738                let cell = (bounds.width - 32.0) / count.max(1) as f32;
739                let index = if rtl { count - 1 - i } else { i };
740                let size = if primary == Some(i) && overflow_trigger != Some(i) {
741                    cell.min(56.0)
742                } else {
743                    48.0
744                };
745                Rect {
746                    x: bounds.x + 16.0 + index as f32 * cell + (cell - size) / 2.0,
747                    y: bounds.y + (bounds.height - size) / 2.0,
748                    width: size,
749                    height: size,
750                }
751            } else {
752                Rect {
753                    x: if rtl {
754                        bounds.x + bounds.width - 56.0 - i as f32 * 48.0
755                    } else {
756                        bounds.x + 8.0 + i as f32 * 48.0
757                    },
758                    y: bounds.y + (bounds.height - 48.0) / 2.0,
759                    width: 48.0,
760                    height: 48.0,
761                }
762            }
763        };
764        let clip = self.clip;
765        let visible = |i: usize| {
766            let clipped = item_bounds(i).intersect(bounds).intersect(clip);
767            actions[i].enabled && clipped.width > 0.0 && clipped.height > 0.0
768        };
769        if let Some(state) = state.as_deref_mut() {
770            if state.index >= count || !visible(state.index) {
771                state.index = (0..count).find(|&i| visible(i)).unwrap_or(0);
772            }
773            if let Some(current) = self
774                .focused_id()
775                .and_then(|v| v.checked_sub(id))
776                .and_then(|v| usize::try_from(v).ok())
777                .filter(|i| *i < count && visible(*i))
778            {
779                state.index = current;
780                if !self.key_consumed
781                    && let Some(key) = self.input.key.filter(|k| k.pressed)
782                {
783                    let forward = if vertical {
784                        key.key == Key::Down
785                    } else if rtl {
786                        key.key == Key::Left
787                    } else {
788                        key.key == Key::Right
789                    };
790                    let backward = if vertical {
791                        key.key == Key::Up
792                    } else if rtl {
793                        key.key == Key::Right
794                    } else {
795                        key.key == Key::Left
796                    };
797                    if forward || backward || matches!(key.key, Key::Home | Key::End) {
798                        let next = (0..count)
799                            .map(|step| {
800                                if key.key == Key::Home {
801                                    step
802                                } else if key.key == Key::End {
803                                    count - 1 - step
804                                } else if forward {
805                                    (current + step + 1) % count
806                                } else {
807                                    (current + count - 1 - step) % count
808                                }
809                            })
810                            .find(|i| visible(*i));
811                        if let Some(next) = next {
812                            state.index = next;
813                            self.request_focus(id + next as u64);
814                            self.key_consumed = true;
815                        }
816                    }
817                }
818            }
819        }
820        let mut activated = None;
821        self.within(bounds, |f| {
822            for (i, action) in actions.iter().take(count).enumerate() {
823                let b = item_bounds(i);
824                let r = if let Some(state) = state.as_deref_mut() {
825                    f.target_roving(
826                        id + i as u64,
827                        b,
828                        action.label,
829                        action.enabled,
830                        i == state.index,
831                    )
832                } else {
833                    f.target(id + i as u64, b, action.label, action.enabled, Role::Button)
834                };
835                if let Some(state) = state.as_deref_mut()
836                    && r.clicked
837                {
838                    state.index = i;
839                }
840                let is_primary = docked_icons
841                    && state
842                        .as_ref()
843                        .is_some_and(|s| s.primary == Some(i) && s.overflow_trigger != Some(i));
844                let ink = if is_primary { t.on_primary } else { foreground };
845                if is_primary {
846                    f.paint_rect(
847                        b,
848                        16.0,
849                        if r.enabled {
850                            t.primary
851                        } else {
852                            t.text.opacity(0.12)
853                        },
854                    );
855                }
856                f.state_layer(r, if is_primary { 16.0 } else { 24.0 }, ink);
857                f.focus_ring(r);
858                if docked_icons {
859                    let state = state.as_ref().unwrap();
860                    let icon = if state.overflow_trigger == Some(i) {
861                        AppBarIcon::More
862                    } else {
863                        state.docked_icons[i]
864                    };
865                    f.commands.push(DrawCommand::Shape {
866                        bounds: Rect {
867                            x: b.x + (b.width - 24.0) / 2.0,
868                            y: b.y + (b.height - 24.0) / 2.0,
869                            width: 24.0,
870                            height: 24.0,
871                        },
872                        index: icon.shape_index(rtl),
873                        color: if r.enabled { ink } else { t.text.opacity(0.38) },
874                        rotation: 0.0,
875                    });
876                } else {
877                    f.styled_text(
878                        b,
879                        action.label,
880                        foreground.opacity(if r.enabled { 1.0 } else { 0.38 }),
881                        TextStyle {
882                            size: 12.0,
883                            align: 1,
884                            ..TextStyle::default()
885                        },
886                    );
887                }
888                if r.clicked {
889                    activated = Some(i);
890                }
891            }
892        });
893        activated
894    }
895}
896
897#[cfg(test)]
898#[path = "toolbar.spec.rs"]
899mod tests;