Skip to main content

bhoo/systems/material/
button_group.rs

1use crate::*;
2
3fn update_group_selection(selected:&mut u32,index:usize,total:usize,multiple:bool,required:bool) {
4    let bit=1_u32<<index;
5    if multiple {
6        let valid=if total==32 {u32::MAX} else {(1_u32<<total)-1};
7        if *selected&bit==0 || !required || (*selected&valid).count_ones()>1 { *selected^=bit; }
8    } else if *selected&bit==0 { *selected=bit; }
9    else if !required { *selected=0; }
10}
11/// Persistent hit geometry for a standard expressive button group.
12#[derive(Default)]
13pub struct ButtonGroupState {
14    bounds: Rect,
15    rtl: bool,
16    hit_bounds: Vec<Rect>,
17    overflow: OverlayState,
18    overflow_offset: f32,
19    overflow_typeahead: MenuTypeaheadState,
20    drag_origin: Option<f32>,
21    drag_last: Option<f32>,
22    dragging: bool,
23    drag_velocity: f32,
24    drag_sample_time: f64,
25    drag_motion_time: f64,
26    fling_velocity: f32,
27    fling_curve: crate::scroll::SplineFling,
28}
29
30impl Frame<'_> {
31    /// Equal-width connected toggle buttons with 2dp spacing. Selection stays
32    /// with the caller; returns the activated index. The caller supplies at
33    /// least 48dp per target. A group may contain at most 32 items.
34    pub fn connected_button_group(
35        &mut self,
36        id: u64,
37        bounds: Rect,
38        actions: &[ToolbarAction<'_>],
39        selected: &mut u32,
40        multiple: bool,
41        selection_required: bool,
42    ) -> Option<usize> {
43        self.connected_button_group_direction(
44            id,
45            bounds,
46            actions,
47            selected,
48            multiple,
49            selection_required,
50            false,
51        )
52    }
53    /// Connected selection group with logical order mirrored for right-to-left layouts.
54    #[allow(clippy::too_many_arguments)]
55    pub fn connected_button_group_direction(
56        &mut self,
57        id: u64,
58        bounds: Rect,
59        actions: &[ToolbarAction<'_>],
60        selected: &mut u32,
61        multiple: bool,
62        selection_required: bool,
63        rtl: bool,
64    ) -> Option<usize> {
65        self.connected_button_group_inner(id,bounds,actions,selected,multiple,selection_required,rtl,None,actions.len())
66    }
67    #[allow(clippy::too_many_arguments)]
68    fn connected_button_group_inner(
69        &mut self, id:u64, bounds:Rect, actions:&[ToolbarAction<'_>], selected:&mut u32,
70        multiple:bool, selection_required:bool, rtl:bool, overflow_trigger:Option<usize>, total:usize,
71    ) -> Option<usize> {
72        let n = actions.len();
73        if n == 0
74            || n > 32
75            || id.checked_add((n - 1) as u64).is_none()
76            || !bounds.x.is_finite()
77            || !bounds.y.is_finite()
78            || !bounds.width.is_finite()
79            || !bounds.height.is_finite()
80            || bounds.width < n as f32 * 48.0 + (n - 1) as f32 * 2.0
81            || bounds.height < 48.0
82        {
83            return None;
84        }
85        let width = (bounds.width - (n - 1) as f32 * 2.0) / n as f32;
86        let mut activated = None;
87        let mut responses = [Response::default(); 32];
88        for (i, action) in actions.iter().enumerate() {
89            let hit = Rect {
90                x: bounds.x + (if rtl { n - 1 - i } else { i }) as f32 * (width + 2.0),
91                y: bounds.y,
92                width,
93                height: 48.0,
94            };
95            let r = self.target(
96                id + i as u64,
97                hit,
98                action.label,
99                action.enabled,
100                if overflow_trigger==Some(i) { Role::Button } else { Role::ToggleButton },
101            );
102            if r.clicked {
103                if overflow_trigger!=Some(i) { update_group_selection(selected,i,total,multiple,selection_required); }
104                activated = Some(i);
105            }
106            responses[i] = r;
107        }
108        if !self.key_consumed
109            && let Some(key) = self.input.key
110            && key.pressed
111            && matches!(key.key, Key::Left | Key::Right | Key::Home | Key::End)
112            && let Some(current) = responses[..n].iter().position(|r| r.focused && r.enabled)
113        {
114            let next = match key.key {
115                Key::Home => (0..n).find(|&i| responses[i].enabled),
116                Key::End => (0..n).rev().find(|&i| responses[i].enabled),
117                Key::Right | Key::Left => (1..=n)
118                    .map(|d| {
119                        if (key.key == Key::Right) != rtl {
120                            (current + d) % n
121                        } else {
122                            (current + n - d) % n
123                        }
124                    })
125                    .find(|&i| responses[i].enabled),
126                _ => None,
127            };
128            if let Some(next) = next {
129                let next_id = responses[next].id;
130                self.request_focus(next_id);
131                self.key_consumed = true;
132                self.ui.continuous = true;
133                for r in &mut responses[..n] {
134                    r.focused = r.id == next_id;
135                }
136                for node in &mut self.ui.semantics {
137                    if responses[..n].iter().any(|r| r.id == node.id) {
138                        node.focused = node.id == next_id;
139                    }
140                }
141            }
142        }
143        for (i, action) in actions.iter().enumerate() {
144            let r = responses[i];
145            let hit = r.bounds;
146            let checked = overflow_trigger != Some(i) && *selected & (1_u32 << i) != 0;
147            if let Some(node) = self
148                .ui
149                .semantics
150                .iter_mut()
151                .rev()
152                .find(|node| node.id == r.id)
153            {
154                node.selected = checked;
155                node.checked = Some(if checked {
156                    CheckState::Checked
157                } else {
158                    CheckState::Unchecked
159                });
160            }
161            let target = if r.pressed {
162                4.0
163            } else if checked {
164                20.0
165            } else {
166                8.0
167            };
168            let inner = self
169                .spatial(r.id, 57, target, if checked { 20.0 } else { 8.0 })
170                .clamp(4.0, 20.0);
171            let physical = if rtl { n - 1 - i } else { i };
172            let left = if physical == 0 { 20.0 } else { inner };
173            let right = if physical + 1 == n { 20.0 } else { inner };
174            let visual = Rect {
175                y: hit.y + 4.0,
176                height: 40.0,
177                ..hit
178            };
179            let t = self.ui.theme;
180            let surface = if !r.enabled {
181                t.text.opacity(0.12)
182            } else if checked {
183                t.secondary
184            } else {
185                t.surface_variant
186            };
187            let ink = if !r.enabled {
188                t.text.opacity(0.38)
189            } else if checked {
190                t.on_secondary
191            } else {
192                t.text
193            };
194            self.paint_connected_halves(visual, left, right, surface);
195            let hover = self.effect(r.id, 0, f32::from(r.hovered), 0.0);
196            let layer = if r.pressed || (r.focused && self.ui.keyboard_focus) {
197                0.12
198            } else {
199                hover * 0.08
200            };
201            if r.enabled && layer > 0.001 {
202                self.paint_connected_halves(visual, left, right, ink.opacity(layer));
203            }
204            self.connected_ink(r, visual, left, right, ink);
205            self.focus_ring(r);
206            if overflow_trigger==Some(i) {
207                self.commands.push(DrawCommand::Shape { bounds:Rect { x:visual.x+(visual.width-24.0)*0.5, y:visual.y+8.0, width:24.0,height:24.0 }, index:AppBarIcon::More.shape_index(rtl),color:ink,rotation:0.0 });
208            } else {
209                self.styled_text(visual,action.label,ink,TextStyle { align:1,..TextStyle::LABEL });
210            }
211        }
212        activated
213    }
214
215    pub(super) fn connected_ink(&mut self, r: Response, visual: Rect, left: f32, right: f32, ink: Color) {
216        let before = self.commands.len();
217        self.ink(
218            Response {
219                bounds: visual,
220                ..r
221            },
222            0.0,
223            ink,
224        );
225        if self.commands.len() > before
226            && let Some(DrawCommand::Ripple {
227                bounds,
228                center,
229                radius,
230                color,
231                soft,
232                ..
233            }) = self.commands.pop()
234        {
235            for (x, corner_radius) in [(visual.x, left), (visual.x + visual.width / 2.0, right)] {
236                self.commands.push(DrawCommand::PushClip(
237                    Rect {
238                        x,
239                        width: visual.width / 2.0,
240                        ..visual
241                    }
242                    .intersect(self.clip),
243                ));
244                self.commands.push(DrawCommand::Ripple {
245                    bounds,
246                    corner_radius,
247                    center,
248                    radius,
249                    color,
250                    soft,
251                });
252                self.commands.push(DrawCommand::PopClip);
253            }
254        }
255    }
256
257    pub(super) fn connected_elevation(&mut self, bounds: Rect, left: f32, right: f32, level: u8) {
258        let middle = bounds.x + bounds.width / 2.0;
259        for (start, end, radius) in [
260            (self.clip.x, middle, left),
261            (middle, self.clip.x + self.clip.width, right),
262        ] {
263            self.commands.push(DrawCommand::PushClip(
264                Rect {
265                    x: start,
266                    y: self.clip.y,
267                    width: (end - start).max(0.0),
268                    height: self.clip.height,
269                }
270                .intersect(self.clip),
271            ));
272            self.elevation(bounds, radius, level);
273            self.commands.push(DrawCommand::PopClip);
274        }
275    }
276
277    pub(super) fn paint_connected_outline(&mut self, b: Rect, left: f32, right: f32, color: Color) {
278        use std::f32::consts::{FRAC_PI_2, PI};
279        let left = left.clamp(1.0, (b.width.min(b.height) / 2.0).max(1.0));
280        let right = right.clamp(1.0, (b.width.min(b.height) / 2.0).max(1.0));
281        let x0 = b.x;
282        let x1 = b.x + b.width;
283        let y0 = b.y;
284        let y1 = b.y + b.height;
285        for (x, y, r, start) in [
286            (x0, y0, left, PI),
287            (x1 - 2.0 * right, y0, right, 3.0 * FRAC_PI_2),
288            (x1 - 2.0 * right, y1 - 2.0 * right, right, 0.0),
289            (x0, y1 - 2.0 * left, left, FRAC_PI_2),
290        ] {
291            self.commands.push(DrawCommand::Arc {
292                bounds: Rect {
293                    x,
294                    y,
295                    width: 2.0 * r,
296                    height: 2.0 * r,
297                },
298                start,
299                sweep: FRAC_PI_2,
300                stroke: 1.0,
301                color,
302                rounded: false,
303            });
304        }
305        for (from, to) in [
306            ([x0 + left, y0 + 0.5], [x1 - right, y0 + 0.5]),
307            ([x1 - 0.5, y0 + right], [x1 - 0.5, y1 - right]),
308            ([x1 - right, y1 - 0.5], [x0 + left, y1 - 0.5]),
309            ([x0 + 0.5, y1 - left], [x0 + 0.5, y0 + left]),
310        ] {
311            self.paint_line(from, to, 1.0, color);
312        }
313    }
314
315    pub(super) fn paint_connected_halves(&mut self, bounds: Rect, left: f32, right: f32, color: Color) {
316        for (x, radius) in [(bounds.x, left), (bounds.x + bounds.width / 2.0, right)] {
317            self.commands.push(DrawCommand::PushClip(
318                Rect {
319                    x,
320                    width: bounds.width / 2.0,
321                    ..bounds
322                }
323                .intersect(self.clip),
324            ));
325            self.paint_rect(bounds, radius, color);
326            self.commands.push(DrawCommand::PopClip);
327        }
328    }
329
330    /// Standard equal-width action group. Returns the activated child index.
331    /// The caller must provide enough room for 48dp targets and 12dp gaps.
332    pub fn button_group(
333        &mut self,
334        id: u64,
335        bounds: Rect,
336        actions: &[ToolbarAction<'_>],
337        state: &mut ButtonGroupState,
338    ) -> Option<usize> {
339        self.button_group_direction(id, bounds, actions, state, false)
340    }
341    /// Standard group with logical action order mirrored in right-to-left layouts.
342    pub fn button_group_direction(
343        &mut self,
344        id: u64,
345        bounds: Rect,
346        actions: &[ToolbarAction<'_>],
347        state: &mut ButtonGroupState,
348        rtl: bool,
349    ) -> Option<usize> {
350        self.button_group_inner(id, bounds, actions, state, rtl, None, &[])
351    }
352    /// Standard group with optional decorative 20dp Material icons preceding labels.
353    /// Missing icon entries are treated as text-only actions.
354    pub fn button_group_with_icons(
355        &mut self,
356        id: u64,
357        bounds: Rect,
358        actions: &[ToolbarAction<'_>],
359        icons: &[Option<AppBarIcon>],
360        state: &mut ButtonGroupState,
361        rtl: bool,
362    ) -> Option<usize> {
363        self.button_group_inner(id, bounds, actions, state, rtl, None, icons)
364    }
365    #[allow(clippy::too_many_arguments)]
366    fn button_group_inner(
367        &mut self,
368        id: u64,
369        bounds: Rect,
370        actions: &[ToolbarAction<'_>],
371        state: &mut ButtonGroupState,
372        rtl: bool,
373        overflow_trigger: Option<usize>,
374        icons: &[Option<AppBarIcon>],
375    ) -> Option<usize> {
376        let n = actions.len();
377        if n == 0
378            || n > 32
379            || id.checked_add((n - 1) as u64).is_none()
380            || !bounds.x.is_finite()
381            || !bounds.y.is_finite()
382            || !bounds.width.is_finite()
383            || !bounds.height.is_finite()
384            || bounds.width < n as f32 * 48.0 + (n - 1) as f32 * 12.0
385            || bounds.height < 48.0
386        {
387            state.hit_bounds.clear();
388            return None;
389        }
390        let width = (bounds.width - (n - 1) as f32 * 12.0) / n as f32;
391        if state.bounds != bounds || state.hit_bounds.len() != n || state.rtl != rtl {
392            state.bounds = bounds;
393            state.rtl = rtl;
394            state.hit_bounds = (0..n)
395                .map(|i| Rect {
396                    x: bounds.x + (if rtl { n - 1 - i } else { i }) as f32 * (width + 12.0),
397                    y: bounds.y,
398                    width,
399                    height: 48.0,
400                })
401                .collect();
402        }
403        let mut responses = [Response::default(); 32];
404        let mut progress = [0.0; 32];
405        for (i, action) in actions.iter().enumerate() {
406            let r = self.target(
407                id + i as u64,
408                state.hit_bounds[i],
409                action.label,
410                action.enabled,
411                Role::Button,
412            );
413            progress[i] = self
414                .spatial(r.id, 56, f32::from(r.pressed), 0.0)
415                .clamp(0.0, 1.0);
416            responses[i] = r;
417        }
418        let mut widths = [width; 32];
419        if n > 1 {
420            for i in 0..n {
421                let requested = width * 0.15 * progress[i];
422                let neighbors = usize::from(i > 0) + usize::from(i + 1 < n);
423                let share = requested / neighbors as f32;
424                for j in [i.checked_sub(1), (i + 1 < n).then_some(i + 1)]
425                    .into_iter()
426                    .flatten()
427                {
428                    let delta = share.min((widths[j] - 48.0).max(0.0));
429                    widths[j] -= delta;
430                    widths[i] += delta;
431                }
432            }
433        }
434        let mut x = if rtl {
435            bounds.x + bounds.width
436        } else {
437            bounds.x
438        };
439        let mut activated = None;
440        for (i, mut r) in responses.into_iter().take(n).enumerate() {
441            if rtl {
442                x -= widths[i];
443            }
444            let hit = Rect {
445                x,
446                y: bounds.y,
447                width: widths[i],
448                height: 48.0,
449            };
450            state.hit_bounds[i] = hit;
451            if let Some(node) = self
452                .ui
453                .semantics
454                .iter_mut()
455                .rev()
456                .find(|node| node.id == r.id)
457            {
458                node.bounds = hit.intersect(self.clip);
459            }
460            r.bounds = hit;
461            let visual = Rect {
462                x: if overflow_trigger == Some(i) {
463                    hit.x + (hit.width - 40.0) / 2.0
464                } else {
465                    hit.x
466                },
467                y: hit.y + 4.0,
468                width: if overflow_trigger == Some(i) {
469                    40.0
470                } else {
471                    hit.width
472                },
473                height: 40.0,
474            };
475            let t = self.ui.theme;
476            // Compose small expressive button: full round at rest, 8dp when pressed.
477            let radius = 20.0 - 12.0 * progress[i];
478            self.paint_rect(
479                visual,
480                radius,
481                if r.enabled && overflow_trigger == Some(i) {
482                    t.primary
483                } else if r.enabled {
484                    t.secondary
485                } else {
486                    t.text.opacity(0.12)
487                },
488            );
489            self.state_layer(
490                Response {
491                    bounds: visual,
492                    ..r
493                },
494                radius,
495                if r.enabled && overflow_trigger == Some(i) {
496                    t.on_primary
497                } else if r.enabled {
498                    t.on_secondary
499                } else {
500                    t.text
501                },
502            );
503            self.focus_ring(r);
504            let foreground = if r.enabled && overflow_trigger == Some(i) {
505                t.on_primary
506            } else if r.enabled {
507                t.on_secondary
508            } else {
509                t.text.opacity(0.38)
510            };
511            if overflow_trigger == Some(i) {
512                self.commands.push(DrawCommand::Shape {
513                    bounds: visual.inset(8.0),
514                    index: AppBarIcon::More.shape_index(rtl),
515                    color: foreground,
516                    rotation: 0.0,
517                });
518            } else if let Some(icon) = icons.get(i).copied().flatten() {
519                let style = TextStyle::LABEL;
520                let text_width = self.text_width(actions[i].label, style);
521                let group_width = 20.0 + 8.0 + text_width;
522                let start = visual.x + ((visual.width - group_width) / 2.0).max(0.0);
523                let icon_x = if rtl { start + text_width + 8.0 } else { start };
524                let text_x = if rtl { start } else { start + 28.0 };
525                self.commands
526                    .push(DrawCommand::PushClip(visual.intersect(self.clip)));
527                self.commands.push(DrawCommand::Shape {
528                    bounds: Rect {
529                        x: icon_x,
530                        y: visual.y + 10.0,
531                        width: 20.0,
532                        height: 20.0,
533                    },
534                    index: icon.shape_index(rtl),
535                    color: foreground,
536                    rotation: 0.0,
537                });
538                self.styled_text(
539                    Rect {
540                        x: text_x,
541                        width: text_width,
542                        ..visual
543                    },
544                    actions[i].label,
545                    foreground,
546                    style,
547                );
548                self.commands.push(DrawCommand::PopClip);
549            } else {
550                self.styled_text(
551                    visual,
552                    actions[i].label,
553                    foreground,
554                    TextStyle {
555                        align: 1,
556                        ..TextStyle::LABEL
557                    },
558                );
559            }
560            if r.clicked {
561                activated = Some(i);
562            }
563            if rtl {
564                x -= 12.0;
565            } else {
566                x += widths[i] + 12.0;
567            }
568        }
569        activated
570    }
571    /// Standard group with an anchored overflow menu. Action IDs remain logical.
572    /// Requires at least a 48dp target, at most 32 actions, and reserves 66 IDs.
573    pub fn button_group_with_overflow(
574        &mut self,
575        id: u64,
576        bounds: Rect,
577        actions: &[ToolbarAction<'_>],
578        state: &mut ButtonGroupState,
579        rtl: bool,
580    ) -> Option<usize> {
581        self.button_group_with_overflow_icons(id, bounds, actions, &[], state, rtl)
582    }
583    /// Standard overflow group retaining optional icons on visible and menu actions.
584    pub fn button_group_with_overflow_icons(
585        &mut self,
586        id: u64,
587        bounds: Rect,
588        actions: &[ToolbarAction<'_>],
589        icons: &[Option<AppBarIcon>],
590        state: &mut ButtonGroupState,
591        rtl: bool,
592    ) -> Option<usize> {
593        self.button_group_overflow_inner(id,bounds,actions,icons,state,rtl,None)
594    }
595    /// Connected single- or multi-selection group with an anchored overflow menu.
596    #[allow(clippy::too_many_arguments)]
597    pub fn connected_button_group_with_overflow(
598        &mut self,id:u64,bounds:Rect,actions:&[ToolbarAction<'_>],selected:&mut u32,
599        multiple:bool,required:bool,state:&mut ButtonGroupState,rtl:bool,
600    ) -> Option<usize> {
601        self.button_group_overflow_inner(id,bounds,actions,&[],state,rtl,Some((selected,multiple,required)))
602    }
603    #[allow(clippy::too_many_arguments)]
604    fn button_group_overflow_inner(
605        &mut self,id:u64,bounds:Rect,actions:&[ToolbarAction<'_>],icons:&[Option<AppBarIcon>],
606        state:&mut ButtonGroupState,rtl:bool,mut connected:Option<(&mut u32,bool,bool)>,
607    ) -> Option<usize> {
608        if actions.is_empty()
609            || actions.len() > 32
610            || id.checked_add(66).is_none()
611            || !bounds.x.is_finite()
612            || !bounds.y.is_finite()
613            || !bounds.width.is_finite()
614            || !bounds.height.is_finite()
615            || bounds.width < 48.0
616            || bounds.height < 48.0
617        {
618            state.overflow.open = false;
619            state.hit_bounds.clear();
620            return None;
621        }
622        let gap=if connected.is_some() {2.0} else {12.0};
623        let slots = (((bounds.width + gap) / (48.0+gap)).floor() as usize).min(actions.len());
624        if slots >= actions.len() {
625            if state.overflow.open {
626                state.overflow = OverlayState::default();
627                if let Some(i) = actions.iter().position(|action| action.enabled) {
628                    self.request_focus(id + i as u64);
629                }
630            }
631            state.overflow_typeahead.reset();
632            return if let Some((selected,multiple,required))=connected {
633                self.connected_button_group_direction(id,bounds,actions,selected,multiple,required,rtl)
634            } else { self.button_group_with_icons(id,bounds,actions,icons,state,rtl) };
635        }
636        let visible = slots.saturating_sub(1);
637        let mut shown = actions[..visible].to_vec();
638        shown.push(ToolbarAction {
639            label: "More",
640            enabled: true,
641        });
642        let mut activated = None;
643        self.without_input(state.overflow.open, |f| {
644            if let Some((selected,multiple,required))=connected.as_mut() {
645                activated = f.connected_button_group_inner(id,bounds,&shown,selected,*multiple,*required,rtl,Some(visible),actions.len());
646                let n=shown.len();let width=(bounds.width-(n-1) as f32*2.0)/n as f32;
647                state.hit_bounds=(0..n).map(|i| Rect { x:bounds.x+(if rtl {n-1-i} else {i}) as f32*(width+2.0),y:bounds.y,width,height:48.0 }).collect();
648            } else { activated = f.button_group_inner(id, bounds, &shown, state, rtl, Some(visible), icons); }
649        });
650        if activated == Some(visible) {
651            activated = None;
652            state.overflow.open = true;
653            state.overflow_offset = 0.0;
654        }
655        let trigger = state.hit_bounds[visible];
656        let viewport = self.viewport();
657        let remaining = &actions[visible..];
658        let width = remaining
659            .iter()
660            .enumerate()
661            .map(|(i, a)| self.text_width(a.label, TextStyle::LABEL) + if connected.is_some() || icons.get(visible+i).copied().flatten().is_some() { 80.0 } else { 48.0 })
662            .fold(112.0_f32, f32::max)
663            .min(280.0)
664            .min(viewport.width);
665        let below = (viewport.y + viewport.height - trigger.y - trigger.height).max(0.0);
666        let above = (trigger.y - viewport.y).max(0.0);
667        let down = below >= above;
668        let height = (remaining.len() as f32 * 48.0 + 16.0).min(if down { below } else { above });
669        let menu = Rect {
670            x: if rtl {
671                (trigger.x + trigger.width - width).max(viewport.x)
672            } else {
673                trigger.x.min(viewport.x + viewport.width - width)
674            },
675            y: if down {
676                trigger.y + trigger.height
677            } else {
678                trigger.y - height
679            },
680            width,
681            height,
682        };
683        let body = (height - 16.0).max(0.0);
684        let max_offset = (remaining.len() as f32 * 48.0 - body).max(0.0);
685        state.overflow_offset = state.overflow_offset.clamp(0.0, max_offset);
686        if !state.overflow.open
687            || self.input.pressed
688            || self.input.cancelled
689            || self.input.blurred
690            || self.reduced_motion()
691            || self.input.scroll[1] != 0.0
692            || self.input.key.is_some()
693        {
694            state.fling_velocity = 0.0;
695        }
696        if state.fling_velocity != 0.0 {
697            let (movement, moving) = state.fling_curve.step(self.ui.time);
698            let old = state.overflow_offset;
699            state.overflow_offset = (old + movement).clamp(0.0, max_offset);
700            if !moving { state.fling_velocity = 0.; }
701            if state.fling_velocity.abs() < 20.0
702                || (state.overflow_offset - old - movement).abs() > 0.5
703            {
704                state.fling_velocity = 0.0;
705            } else {
706                self.ui.continuous = true;
707            }
708        }
709        let first_id = id + 33;
710        if state.overflow.open {
711            state.overflow_offset =
712                (state.overflow_offset + self.scroll_y(menu)).clamp(0.0, max_offset);
713            if max_offset > 0.0 && self.input.pointer_kind == PointerKind::Touch {
714                if self.input.pressed && self.pointer_in(menu) {
715                    state.drag_origin = self.input.pointer.map(|p| p[1]);
716                    state.drag_last = state.drag_origin;
717                    state.dragging = false;
718                    state.drag_velocity = 0.0;
719                    state.drag_sample_time = self.ui.time;
720                    state.drag_motion_time = self.ui.time;
721                } else if let (Some(origin), Some(last), Some(pointer)) =
722                    (state.drag_origin, state.drag_last, self.input.pointer)
723                {
724                    if (pointer[1] - origin).abs() > 4.0 {
725                        state.dragging = true;
726                    }
727                    if state.dragging {
728                        let movement = last - pointer[1];
729                        state.overflow_offset =
730                            (state.overflow_offset + movement).clamp(0.0, max_offset);
731                        if movement != 0.0 {
732                            let elapsed = self.ui.time - state.drag_sample_time;
733                            state.drag_velocity = if (0.005..=0.15).contains(&elapsed) {
734                                (movement / elapsed as f32).clamp(-4000.0, 4000.0)
735                            } else {
736                                0.0
737                            };
738                            state.drag_sample_time = self.ui.time;
739                            state.drag_motion_time = self.ui.time;
740                        }
741                        state.drag_last = Some(pointer[1]);
742                        self.ui.active = None;
743                    }
744                }
745            }
746            if let Some(current) = self
747                .focused_id()
748                .and_then(|v| v.checked_sub(first_id))
749                .and_then(|v| usize::try_from(v).ok())
750                .filter(|i| *i < remaining.len())
751            {
752                let key = self.input.key.filter(|k| k.pressed).map(|k| k.key);
753                if !self.key_consumed
754                    && matches!(key, Some(Key::Up | Key::Down | Key::Home | Key::End))
755                {
756                    let next = (0..remaining.len())
757                        .map(|step| match key {
758                            Some(Key::Home) => step,
759                            Some(Key::End) => remaining.len() - 1 - step,
760                            Some(Key::Down) => (current + step + 1) % remaining.len(),
761                            _ => (current + remaining.len() - 1 - step) % remaining.len(),
762                        })
763                        .find(|i| remaining[*i].enabled);
764                    if let Some(next) = next {
765                        let top = next as f32 * 48.0;
766                        if top < state.overflow_offset {
767                            state.overflow_offset = top;
768                        } else if top + 48.0 > state.overflow_offset + body {
769                            state.overflow_offset = (top + 48.0 - body).min(max_offset);
770                        }
771                        self.request_focus(first_id + next as u64);
772                        self.key_consumed = true;
773                    }
774                }
775            }
776            let items: Vec<_> = remaining.iter().map(|a| (a.label, a.enabled)).collect();
777            if let Some(next) = self.menu_typeahead(&mut state.overflow_typeahead, first_id, &items)
778            {
779                let top = next as f32 * 48.0;
780                if top < state.overflow_offset {
781                    state.overflow_offset = top;
782                } else if top + 48.0 > state.overflow_offset + body {
783                    state.overflow_offset = (top + 48.0 - body).min(max_offset);
784                }
785            }
786        } else {
787            state.overflow_typeahead.reset();
788        }
789        if self.input.released || self.input.cancelled || self.input.blurred || !state.overflow.open
790        {
791            if state.dragging {
792                self.ui.active = None;
793                if self.input.released
794                    && !self.input.cancelled
795                    && !self.input.blurred
796                    && state.overflow.open
797                    && !self.reduced_motion()
798                    && self.ui.time - state.drag_motion_time <= 0.1
799                    && state.drag_velocity.abs() >= 350.0
800                {
801                    state.fling_velocity = state.drag_velocity;
802                    state.fling_curve.start(state.fling_velocity,self.ui.time);
803                            self.ui.continuous = true;
804                }
805            }
806            state.drag_origin = None;
807            state.drag_last = None;
808            state.dragging = false;
809        }
810        state.overflow.kind = OverlayKind::Menu;
811        state.overflow.style = OverlayStyle::AndroidMenu;
812        state.overflow.initial_focus = remaining
813            .iter()
814            .position(|a| a.enabled)
815            .map(|i| first_id + i as u64);
816        let start = self.commands.len();
817        self.overlay(id + 66, &mut state.overflow, menu, false, |f, open| {
818            let content = f.available();
819            f.within(content, |f| {
820                f.within(
821                    Rect {
822                        y: content.y - state.overflow_offset,
823                        height: remaining.len() as f32 * 48.0,
824                        ..content
825                    },
826                    |f| {
827                        f.with_gap(0.0, |f| {
828                            for (i, action) in remaining.iter().enumerate() {
829                                let response = if let Some((selected,_,_))=connected.as_ref() {
830                                    f.menu_item_with_selection(first_id+i as u64,action.label,action.enabled,**selected & (1_u32 << (visible+i)) != 0,rtl)
831                                } else if let Some(icon) = icons.get(visible+i).copied().flatten() {
832                                    f.menu_item_with_icon(first_id+i as u64, action.label, action.enabled, icon, rtl)
833                                } else {
834                                    f.menu_item(first_id+i as u64, action.label, action.enabled)
835                                };
836                                if response.clicked {
837                                    if let Some((selected,multiple,required))=connected.as_mut() { update_group_selection(selected,visible+i,actions.len(),*multiple,*required); }
838                                    activated = Some(visible + i);
839                                    *open = false;
840                                }
841                            }
842                        });
843                    },
844                );
845            });
846        });
847        self.ui.overlays.extend(self.commands.drain(start..));
848        activated
849    }
850}
851
852#[cfg(test)]
853#[path = "button_group.spec.rs"]
854mod tests;