Skip to main content

arc_ui/inputs/
chip_group.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/chip-group/chip-group.tsx` & `.module.css`
3//!
4//! P4 Component #6: `chip-group`
5//!
6//! - Selectable filter chips (`ControlHeights::SM` 36px, `0 14px` horizontal padding,
7//!   `Radii::PILL`, `1px border`):
8//!   - Selecting morphs the chip: a `SLOT = 18px` leading slot springs open on
9//!     `motion.spring.morph`, driving a single `grown (0..=1)` progress that simultaneously
10//!     scales (`min(grown, 1.1)`), sharpens (`(1 - grown) * 2px` blur), fades (`min(1, grown * 1.4)`),
11//!     and draws (`pathLength = clamp(grown, 0.001, 1.0)`) the `14×14px` checkmark (`M4 12.5 9.5 18 20 6.5`)
12//!     in exact step with the space the label opens up.
13//!   - Selected surface uses Oklab tints: `11% accent` over `surface` (`16%` on hover) and `42%
14//!     accent` over `border` (`60%` on hover).
15//!   - Press scales `.body` to `0.97` (`duration.instant`).
16//!   - Overflow folding (`max_visible`): chips beyond `max_visible` fold behind a `"+N more"` /
17//!     `"Show less"` chip (`surface_muted` background). Chips selected while expanded remain
18//!     pinned in view when folded so selections are never hidden.
19//!   - Revealed overflow chips stagger in by `min((index - max_visible) * 35ms, 300ms)`.
20//!   - `HeightFrame`: tracks wrapped row height on `motion.spring.smooth`.
21
22use std::{cell::RefCell, rc::Rc, time::Duration};
23
24use arc_motion::{
25    BlurFallback, CubicBezier, PathPoint, PolylinePath, arc_spring, arc_spring_with_options,
26    arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
27};
28use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
29use gpui_kit::{
30    App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, ParentElement,
31    Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
32    base::{Button as BaseButton, StyledExt as _},
33    canvas, div,
34    prelude::*,
35    px,
36};
37
38type ChipGroupChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
39
40/// Width (`18px`) of the leading check slot (`14px` glyph + `4px` gap).
41pub const CHIP_CHECK_SLOT_PX: f32 = 18.0;
42/// Stagger step (`35ms`, `motion.stagger.item`) for chips revealed by `+N more`.
43pub const CHIP_REVEAL_STAGGER_SECS: f64 = 0.035;
44/// Maximum stagger delay (`300ms`) for revealed overflow chips.
45pub const CHIP_REVEAL_MAX_DELAY_SECS: f64 = 0.30;
46
47/// Derived check visual parameters `(slot_width_px, scale, opacity, path_length)` from `grown`
48/// (`0.0..=1.0`), matching upstream `useTransform(grown, ...)`.
49pub fn chip_check_metrics(grown: f32, reduced: bool) -> (f32, f32, f32, f32) {
50    let g = grown.clamp(0.0, 1.15);
51    let slot_w = (g * CHIP_CHECK_SLOT_PX).clamp(0.0, CHIP_CHECK_SLOT_PX);
52    let scale = g.min(1.1);
53    let raw_op = (g * 1.4).clamp(0.0, 1.0);
54    let blur = BlurFallback::evaluate(px(((1.0 - g).max(0.0)) * 2.0), reduced);
55    let opacity = (raw_op * blur.opacity_multiplier).clamp(0.0, 1.0);
56    let path_len = g.clamp(0.0, 1.0);
57    (slot_w, scale, opacity, path_len)
58}
59
60/// Computes `0..=1` entrance progress for an overflow chip at `index >= max_visible` at `elapsed`
61/// seconds after expanding `+N more`.
62pub fn chip_reveal_progress(elapsed: f64, index: usize, max_visible: usize, reduced: bool) -> f32 {
63    if reduced || index < max_visible {
64        return 1.0;
65    }
66    let delay =
67        ((index - max_visible) as f64 * CHIP_REVEAL_STAGGER_SECS).min(CHIP_REVEAL_MAX_DELAY_SECS);
68    if elapsed <= delay {
69        return 0.0;
70    }
71    let t = ((elapsed - delay) / 0.16).clamp(0.0, 1.0) as f32;
72    CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t)
73}
74
75/// Sampled `(enter_opacity, enter_y_px, exit_opacity, exit_y_px)` for the `MoreChip` label swap
76/// (`"+N more"` ↔ `"Show less"`).
77pub fn chip_more_swap_sample(elapsed: f64, reduced: bool) -> (f32, f32, f32, f32) {
78    if reduced {
79        let t = (elapsed / 0.15).clamp(0.0, 1.0) as f32;
80        return (t, 0.0, 1.0 - t, 0.0);
81    }
82    let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
83    let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
84    let blur_in = BlurFallback::evaluate(px(4.0 * (1.0 - e_in)), false);
85    let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
86    let enter_y = 4.2 * (1.0 - e_in);
87
88    let t_out = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
89    let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
90    let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
91    let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
92    let exit_y = -4.2 * e_out;
93
94    (enter_op, enter_y, exit_op, exit_y)
95}
96
97/// Toggles `target` inside `selected` according to `multiple` and preserves `options` declaration order.
98pub fn toggle_chip_group_value(
99    options: &[ChipOption],
100    selected: &[SharedString],
101    target: &SharedString,
102    multiple: bool,
103) -> Vec<SharedString> {
104    let is_on = selected.iter().any(|v| v == target);
105    if !multiple {
106        return if is_on {
107            Vec::new()
108        } else {
109            vec![target.clone()]
110        };
111    }
112    options
113        .iter()
114        .filter(|opt| {
115            if &opt.value == target {
116                !is_on
117            } else {
118                selected.iter().any(|v| v == &opt.value)
119            }
120        })
121        .map(|opt| opt.value.clone())
122        .collect()
123}
124
125/// One selectable chip option inside [`ChipGroup`].
126#[derive(Clone, Debug, PartialEq, Eq)]
127pub struct ChipOption {
128    pub value: SharedString,
129    pub label: SharedString,
130}
131
132impl ChipOption {
133    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
134        Self {
135            value: value.into(),
136            label: label.into(),
137        }
138    }
139}
140
141#[derive(Clone)]
142struct ChipGroupInternal {
143    uncontrolled_value: Vec<SharedString>,
144    expanded: bool,
145    expanded_changed_at_secs: f64,
146    previous_more_text: Option<SharedString>,
147    pinned: Vec<SharedString>,
148    active_focus_key: Option<SharedString>,
149    hovered_chip: Option<SharedString>,
150    pressed_chip: Option<SharedString>,
151    measured_frame_h: Rc<RefCell<f32>>,
152    focus_handle: FocusHandle,
153}
154
155impl ChipGroupInternal {
156    fn new(default_value: Vec<SharedString>, now: f64, focus_handle: FocusHandle) -> Self {
157        Self {
158            pinned: default_value.clone(),
159            uncontrolled_value: default_value,
160            expanded: false,
161            expanded_changed_at_secs: now - 10.0,
162            previous_more_text: None,
163            active_focus_key: None,
164            hovered_chip: None,
165            pressed_chip: None,
166            measured_frame_h: Rc::new(RefCell::new(36.0)),
167            focus_handle,
168        }
169    }
170}
171
172fn paint_chip_check(
173    origin_x: Pixels,
174    origin_y: Pixels,
175    scale: f32,
176    path_length: f32,
177    opacity: f32,
178    color: Hsla,
179    window: &mut Window,
180) {
181    let len = path_length.clamp(0.0, 1.0);
182    let alpha = opacity.clamp(0.0, 1.0);
183    if len <= 0.01 || alpha <= 0.01 || scale <= 0.05 {
184        return;
185    }
186    // `M4 12.5 9.5 18 20 6.5` in 24×24 viewBox scaled into 14×14px with transform-origin `(0, 50%)`.
187    let s = 14.0 / 24.0;
188    let cy = 7.0_f32;
189    let transform_pt = |vx: f32, vy: f32| -> PathPoint {
190        let bx = vx * s;
191        let by = vy * s;
192        PathPoint::new(bx * scale, cy + (by - cy) * scale)
193    };
194    let poly = PolylinePath::new(vec![
195        transform_pt(4.0, 12.5),
196        transform_pt(9.5, 18.0),
197        transform_pt(20.0, 6.5),
198    ]);
199    let sliced = poly.slice(0.0, len);
200    let stroke_color = Hsla {
201        a: color.a * alpha,
202        ..color
203    };
204    if let Some(b) = sliced.to_stroke_builder(origin_x, origin_y, px(2.1))
205        && let Ok(path) = b.build()
206    {
207        window.paint_path(path, stroke_color);
208    }
209}
210
211/// Arc `ChipGroup` — single or multi-select filter chips with spring check-slot growth, Oklab
212/// accent surface tinting, `"+N more"` overflow folding with pinned selections, and `HeightFrame`
213/// smooth row height morphing.
214#[derive(IntoElement)]
215pub struct ChipGroup {
216    id: ElementId,
217    label: SharedString,
218    show_label: bool,
219    options: Vec<ChipOption>,
220    value: Option<Vec<SharedString>>,
221    default_value: Vec<SharedString>,
222    multiple: bool,
223    max_visible: Option<usize>,
224    disabled: bool,
225    width: Option<Pixels>,
226    on_value_change: Option<ChipGroupChangeHandler>,
227}
228
229impl ChipGroup {
230    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
231        Self {
232            id: id.into(),
233            label: label.into(),
234            show_label: false,
235            options: Vec::new(),
236            value: None,
237            default_value: Vec::new(),
238            multiple: true,
239            max_visible: None,
240            disabled: false,
241            width: None,
242            on_value_change: None,
243        }
244    }
245
246    pub fn show_label(mut self, show: bool) -> Self {
247        self.show_label = show;
248        self
249    }
250
251    pub fn option(mut self, option: ChipOption) -> Self {
252        self.options.push(option);
253        self
254    }
255
256    pub fn options(mut self, options: impl IntoIterator<Item = ChipOption>) -> Self {
257        self.options.extend(options);
258        self
259    }
260
261    pub fn value<I, S>(mut self, value: I) -> Self
262    where
263        I: IntoIterator<Item = S>,
264        S: Into<SharedString>,
265    {
266        self.value = Some(value.into_iter().map(Into::into).collect());
267        self
268    }
269
270    pub fn default_value<I, S>(mut self, value: I) -> Self
271    where
272        I: IntoIterator<Item = S>,
273        S: Into<SharedString>,
274    {
275        self.default_value = value.into_iter().map(Into::into).collect();
276        self
277    }
278
279    pub fn multiple(mut self, multiple: bool) -> Self {
280        self.multiple = multiple;
281        self
282    }
283
284    pub fn max_visible(mut self, max_visible: usize) -> Self {
285        self.max_visible = Some(max_visible.max(1));
286        self
287    }
288
289    pub fn disabled(mut self, disabled: bool) -> Self {
290        self.disabled = disabled;
291        self
292    }
293
294    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
295        self.width = Some(width.into());
296        self
297    }
298
299    pub fn on_value_change(
300        mut self,
301        handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
302    ) -> Self {
303        self.on_value_change = Some(Rc::new(handler));
304        self
305    }
306}
307
308impl RenderOnce for ChipGroup {
309    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
310        let theme = cx.arc_theme().clone();
311        let colors = theme.colors;
312        let motion = theme.motion;
313        let reduced = is_reduced_motion(cx);
314        let now = motion_now(cx);
315
316        let initial_vals = self
317            .value
318            .clone()
319            .unwrap_or_else(|| self.default_value.clone());
320
321        let state_id =
322            ElementId::NamedChild(self.id.clone().into(), "__arc-chip-group-state".into());
323        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
324            ChipGroupInternal::new(initial_vals.clone(), now, cx.focus_handle())
325        });
326
327        let selected: Vec<SharedString> = self
328            .value
329            .clone()
330            .unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
331        let snap = internal.read(cx).clone();
332
333        let max_vis = self.max_visible.unwrap_or(usize::MAX);
334        let foldable = self.options.len() > max_vis;
335        let visible_options: Vec<(usize, ChipOption)> = if !foldable || snap.expanded {
336            self.options.iter().cloned().enumerate().collect()
337        } else {
338            self.options
339                .iter()
340                .cloned()
341                .enumerate()
342                .filter(|(idx, opt)| {
343                    *idx < max_vis
344                        || snap.pinned.contains(&opt.value)
345                        || selected.contains(&opt.value)
346                })
347                .collect()
348        };
349        let hidden_count = self.options.len().saturating_sub(visible_options.len());
350        let show_more = foldable && (snap.expanded || hidden_count > 0);
351
352        // `HeightFrame` spring (`motion.spring.smooth`).
353        let measured_h = (*snap.measured_frame_h.borrow()).max(36.0);
354        let frame_h = if reduced {
355            measured_h
356        } else {
357            arc_spring_with_options(
358                (self.id.clone(), "frame-h"),
359                measured_h,
360                SpringOptions::new(motion.spring.smooth).with_initial_value(36.0),
361                window,
362                cx,
363            )
364            .value
365            .max(36.0)
366        };
367
368        let frame_h_ref = snap.measured_frame_h.clone();
369        let frame_probe = canvas(
370            move |rect, window, _| {
371                let h = f32::from(rect.size.height).max(36.0);
372                let prev = *frame_h_ref.borrow();
373                *frame_h_ref.borrow_mut() = h;
374                if (prev - h).abs() > 0.5 {
375                    window.request_animation_frame();
376                }
377            },
378            |_, _, _, _| {},
379        )
380        .absolute()
381        .inset_0();
382
383        let expand_elapsed = (now - snap.expanded_changed_at_secs).max(0.0);
384        let disabled = self.disabled;
385        let multiple = self.multiple;
386
387        let mut chip_els = Vec::with_capacity(visible_options.len() + 1);
388        for (orig_idx, option) in &visible_options {
389            let is_selected = selected.contains(&option.value);
390            let is_hovered = snap.hovered_chip.as_ref() == Some(&option.value) && !disabled;
391            let is_pressed = snap.pressed_chip.as_ref() == Some(&option.value) && !disabled;
392            let is_focused = snap.active_focus_key.as_ref() == Some(&option.value);
393
394            // `grown` (0..=1) springs on `motion.spring.morph`, driving slot width + check draw/scale/blur.
395            let grown = if reduced {
396                if is_selected { 1.0 } else { 0.0 }
397            } else {
398                arc_spring(
399                    (self.id.clone(), format!("grown-{}", option.value)),
400                    if is_selected { 1.0 } else { 0.0 },
401                    motion.spring.morph,
402                    window,
403                    cx,
404                )
405            };
406            let (slot_w, check_scale, check_op, check_path_len) =
407                chip_check_metrics(grown, reduced);
408
409            // Staggered entrance when revealed by `+N more`.
410            let reveal_p = if snap.expanded && foldable && *orig_idx >= max_vis {
411                let rp = chip_reveal_progress(expand_elapsed, *orig_idx, max_vis, reduced);
412                if rp < 0.999 {
413                    window.request_animation_frame();
414                }
415                rp
416            } else {
417                1.0
418            };
419
420            let hover_p = arc_transition(
421                (self.id.clone(), format!("hover-{}", option.value)),
422                if is_hovered || is_focused { 1.0 } else { 0.0 },
423                if reduced {
424                    Duration::ZERO
425                } else {
426                    motion.duration.fast
427                },
428                motion.ease.standard,
429                window,
430                cx,
431            );
432            let sel_p = grown.clamp(0.0, 1.0);
433
434            let resting_unsel_bg = colors.surface;
435            let resting_sel_bg = oklab_mix(colors.accent, colors.surface, 0.11);
436            let hover_sel_bg = oklab_mix(colors.accent, colors.surface, 0.16);
437            let sel_bg = oklab_mix(hover_sel_bg, resting_sel_bg, hover_p);
438            let chip_bg = oklab_mix(sel_bg, resting_unsel_bg, sel_p);
439
440            let resting_unsel_border = oklab_mix(colors.border_strong, colors.border, hover_p);
441            let resting_sel_border = oklab_mix(colors.accent, colors.border, 0.42);
442            let hover_sel_border = oklab_mix(colors.accent, colors.border, 0.60);
443            let sel_border = oklab_mix(hover_sel_border, resting_sel_border, hover_p);
444            let chip_border = oklab_mix(sel_border, resting_unsel_border, sel_p);
445
446            let text_fg = if is_selected || is_hovered || is_focused {
447                colors.foreground
448            } else {
449                colors.text_secondary
450            };
451            let check_color = colors.accent_strong;
452            let body_h = if is_pressed && !reduced { 35.0 } else { 36.0 };
453
454            let int_hover = internal.clone();
455            let int_down = internal.clone();
456            let int_up = internal.clone();
457            let int_out = internal.clone();
458            let int_click = internal.clone();
459            let all_opts = self.options.clone();
460            let cur_selected = selected.clone();
461            let on_change = self.on_value_change.clone();
462            let val_hover = option.value.clone();
463            let val_down = option.value.clone();
464            let val_up = option.value.clone();
465            let val_out = option.value.clone();
466            let val_click = option.value.clone();
467            let focus_for_click = snap.focus_handle.clone();
468
469            chip_els.push(
470                BaseButton::new(ElementId::NamedChild(
471                    self.id.clone().into(),
472                    SharedString::from(format!("chip-{}", option.value)),
473                ))
474                .accessibility_label(option.label.clone())
475                .disabled(disabled)
476                .on_click(move |_, window, cx| {
477                    if disabled {
478                        return;
479                    }
480                    window.focus(&focus_for_click, cx);
481                    let next_vals =
482                        toggle_chip_group_value(&all_opts, &cur_selected, &val_click, multiple);
483                    int_click.update(cx, |s, _| {
484                        s.uncontrolled_value = next_vals.clone();
485                        s.active_focus_key = Some(val_click.clone());
486                        s.pressed_chip = None;
487                    });
488                    if let Some(cb) = &on_change {
489                        cb(&next_vals, window, cx);
490                    }
491                    window.refresh();
492                })
493                .relative()
494                .h(px(body_h))
495                .px(px(14.0))
496                .flex()
497                .flex_row()
498                .items_center()
499                .rounded(Radii::PILL)
500                .border_1()
501                .border_color(chip_border)
502                .bg(chip_bg)
503                .opacity(if disabled { 0.5 } else { reveal_p })
504                .text_size(Typography::TEXT_SM)
505                .font_medium()
506                .text_color(text_fg)
507                .when(!disabled, |this| this.cursor_pointer())
508                .on_hover(move |hovered, window, cx| {
509                    int_hover.update(cx, |s, _| {
510                        if *hovered {
511                            s.hovered_chip = Some(val_hover.clone());
512                        } else if s.hovered_chip.as_ref() == Some(&val_hover) {
513                            s.hovered_chip = None;
514                        }
515                    });
516                    window.refresh();
517                })
518                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
519                    if !disabled {
520                        int_down.update(cx, |s, _| s.pressed_chip = Some(val_down.clone()));
521                        window.refresh();
522                    }
523                })
524                .on_mouse_up(MouseButton::Left, move |_, window, cx| {
525                    if int_up.read(cx).pressed_chip.as_ref() == Some(&val_up) {
526                        int_up.update(cx, |s, _| s.pressed_chip = None);
527                        window.refresh();
528                    }
529                })
530                .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
531                    if int_out.read(cx).pressed_chip.as_ref() == Some(&val_out) {
532                        int_out.update(cx, |s, _| s.pressed_chip = None);
533                        window.refresh();
534                    }
535                })
536                .when(check_op > 0.01, |this| {
537                    this.child(
538                        div()
539                            .absolute()
540                            .left(px(12.0))
541                            .top(px((body_h - 14.0) * 0.5))
542                            .size(px(14.0))
543                            .child(
544                                canvas(
545                                    |_, _, _| {},
546                                    move |rect, _, window, _| {
547                                        paint_chip_check(
548                                            rect.origin.x,
549                                            rect.origin.y,
550                                            check_scale,
551                                            check_path_len,
552                                            check_op,
553                                            check_color,
554                                            window,
555                                        );
556                                    },
557                                )
558                                .size_full(),
559                            ),
560                    )
561                })
562                .child(div().w(px(slot_w)).flex_none())
563                .child(div().truncate().child(option.label.clone()))
564                .into_any_element(),
565            );
566        }
567
568        // Optional `+N more` / `Show less` overflow chip.
569        if show_more {
570            let more_key: SharedString = "__more__".into();
571            let more_text: SharedString = if snap.expanded {
572                "Show less".into()
573            } else {
574                SharedString::from(format!("+{hidden_count} more"))
575            };
576            let is_more_hovered = snap.hovered_chip.as_ref() == Some(&more_key) && !disabled;
577            let is_more_focused = snap.active_focus_key.as_ref() == Some(&more_key);
578            let more_border = if is_more_hovered || is_more_focused {
579                colors.border_strong
580            } else {
581                colors.border
582            };
583            let more_fg = if is_more_hovered || is_more_focused {
584                colors.foreground
585            } else {
586                colors.text_muted
587            };
588
589            let (in_op, in_y, out_op, out_y) = if expand_elapsed < 0.25 {
590                window.request_animation_frame();
591                chip_more_swap_sample(expand_elapsed, reduced)
592            } else {
593                (1.0, 0.0, 0.0, 0.0)
594            };
595
596            let mut more_label_slot = div()
597                .relative()
598                .h(px(20.0))
599                .overflow_hidden()
600                .flex()
601                .items_center()
602                .justify_center()
603                .child(div().mt(px(in_y)).opacity(in_op).child(more_text.clone()));
604            if out_op > 0.01
605                && let Some(prev_txt) = snap.previous_more_text.clone()
606            {
607                more_label_slot = more_label_slot.child(
608                    div()
609                        .absolute()
610                        .top_0()
611                        .left_0()
612                        .mt(px(out_y))
613                        .opacity(out_op)
614                        .child(prev_txt),
615                );
616            }
617
618            let int_more_hover = internal.clone();
619            let int_more_click = internal.clone();
620            let cur_selected_for_pin = selected.clone();
621            let cur_more_text = more_text.clone();
622            let focus_for_more = snap.focus_handle.clone();
623
624            chip_els.push(
625                BaseButton::new(ElementId::NamedChild(self.id.clone().into(), "more".into()))
626                    .accessibility_label(more_text)
627                    .disabled(disabled)
628                    .on_click(move |_, window, cx| {
629                        if disabled {
630                            return;
631                        }
632                        window.focus(&focus_for_more, cx);
633                        let t_now = motion_now(cx);
634                        int_more_click.update(cx, |s, _| {
635                            if s.expanded {
636                                s.pinned = cur_selected_for_pin.clone();
637                            }
638                            s.expanded = !s.expanded;
639                            s.expanded_changed_at_secs = t_now;
640                            s.previous_more_text = Some(cur_more_text.clone());
641                            s.active_focus_key = Some("__more__".into());
642                        });
643                        window.refresh();
644                    })
645                    .h(ControlHeights::SM)
646                    .px(px(14.0))
647                    .flex()
648                    .flex_row()
649                    .items_center()
650                    .rounded(Radii::PILL)
651                    .border_1()
652                    .border_color(more_border)
653                    .bg(colors.surface_muted)
654                    .text_size(Typography::TEXT_SM)
655                    .font_medium()
656                    .text_color(more_fg)
657                    .when(!disabled, |this| this.cursor_pointer())
658                    .on_hover(move |hovered, window, cx| {
659                        int_more_hover.update(cx, |s, _| {
660                            if *hovered {
661                                s.hovered_chip = Some("__more__".into());
662                            } else if s.hovered_chip.as_deref() == Some("__more__") {
663                                s.hovered_chip = None;
664                            }
665                        });
666                        window.refresh();
667                    })
668                    .child(more_label_slot)
669                    .into_any_element(),
670            );
671        }
672
673        // Keyboard roving focus (`ArrowRight`/`ArrowDown`, `ArrowLeft`/`ArrowUp`, `Home`, `End`,
674        // `Enter` / `Space`).
675        let mut focus_keys: Vec<SharedString> = visible_options
676            .iter()
677            .map(|(_, o)| o.value.clone())
678            .collect();
679        if show_more {
680            focus_keys.push("__more__".into());
681        }
682        let int_key = internal.clone();
683        let all_opts_key = self.options.clone();
684        let selected_for_key = selected;
685        let on_change_key = self.on_value_change.clone();
686        let focus_handle = snap.focus_handle.clone();
687
688        let group_box = div()
689            .id(ElementId::NamedChild(
690                self.id.clone().into(),
691                "group".into(),
692            ))
693            .test_support()
694            .role(Role::Group)
695            .aria_label(self.label.clone())
696            .track_focus(&focus_handle)
697            .on_key_down(move |event: &KeyDownEvent, window, cx| {
698                if disabled || focus_keys.is_empty() {
699                    return;
700                }
701                let cur_key = int_key.read(cx).active_focus_key.clone();
702                let cur_idx = cur_key
703                    .as_ref()
704                    .and_then(|k| focus_keys.iter().position(|fk| fk == k))
705                    .unwrap_or(0);
706                let len = focus_keys.len();
707
708                match event.keystroke.key.as_str() {
709                    "right" | "arrowright" | "down" | "arrowdown" => {
710                        let next_k = focus_keys[(cur_idx + 1) % len].clone();
711                        int_key.update(cx, |s, _| s.active_focus_key = Some(next_k));
712                        window.refresh();
713                    }
714                    "left" | "arrowleft" | "up" | "arrowup" => {
715                        let prev_k = focus_keys[(cur_idx + len - 1) % len].clone();
716                        int_key.update(cx, |s, _| s.active_focus_key = Some(prev_k));
717                        window.refresh();
718                    }
719                    "home" => {
720                        let first_k = focus_keys[0].clone();
721                        int_key.update(cx, |s, _| s.active_focus_key = Some(first_k));
722                        window.refresh();
723                    }
724                    "end" => {
725                        let last_k = focus_keys[len - 1].clone();
726                        int_key.update(cx, |s, _| s.active_focus_key = Some(last_k));
727                        window.refresh();
728                    }
729                    "enter" | " " | "space" => {
730                        let target_k = focus_keys[cur_idx].clone();
731                        if target_k.as_ref() == "__more__" {
732                            let t_now = motion_now(cx);
733                            int_key.update(cx, |s, _| {
734                                if s.expanded {
735                                    s.pinned = selected_for_key.clone();
736                                }
737                                s.expanded = !s.expanded;
738                                s.expanded_changed_at_secs = t_now;
739                            });
740                        } else {
741                            let next_vals = toggle_chip_group_value(
742                                &all_opts_key,
743                                &selected_for_key,
744                                &target_k,
745                                multiple,
746                            );
747                            int_key.update(cx, |s, _| {
748                                s.uncontrolled_value = next_vals.clone();
749                            });
750                            if let Some(cb) = &on_change_key {
751                                cb(&next_vals, window, cx);
752                            }
753                        }
754                        window.refresh();
755                    }
756                    _ => {}
757                }
758            })
759            .w_full()
760            .h(px(frame_h))
761            .overflow_hidden()
762            .child(
763                div()
764                    .relative()
765                    .w_full()
766                    .flex()
767                    .flex_row()
768                    .flex_wrap()
769                    .gap(Spacing::S2)
770                    .child(frame_probe)
771                    .children(chip_els),
772            );
773
774        div()
775            .id(self.id)
776            .test_support()
777            .when_some(self.width, |this, w| this.w(w))
778            .when(self.width.is_none(), |this| this.w_full())
779            .flex()
780            .flex_col()
781            .gap(Spacing::S2)
782            .when(self.show_label, |this| {
783                this.child(
784                    div()
785                        .text_size(Typography::TEXT_SM)
786                        .font_medium()
787                        .text_color(colors.foreground)
788                        .child(self.label),
789                )
790            })
791            .child(group_box)
792    }
793}
794
795#[cfg(test)]
796mod tests {
797    use super::*;
798
799    #[test]
800    fn chip_check_metrics_coordinate_slot_width_and_path_length() {
801        let (w0, sc0, op0, len0) = chip_check_metrics(0.0, false);
802        assert!(w0.abs() < 1e-4);
803        assert!(sc0.abs() < 1e-4);
804        assert!(op0.abs() < 1e-4);
805        assert!(len0.abs() < 1e-4);
806
807        let (w1, sc1, op1, len1) = chip_check_metrics(1.0, false);
808        assert!((w1 - CHIP_CHECK_SLOT_PX).abs() < 1e-4);
809        assert!((sc1 - 1.0).abs() < 1e-4);
810        assert!((op1 - 1.0).abs() < 1e-4);
811        assert!((len1 - 1.0).abs() < 1e-4);
812    }
813
814    #[test]
815    fn toggle_chip_group_value_handles_multi_and_single_modes() {
816        let opts = vec![
817            ChipOption::new("a", "Alpha"),
818            ChipOption::new("b", "Beta"),
819            ChipOption::new("c", "Gamma"),
820        ];
821        // Multiple mode preserves option declaration order
822        let sel: Vec<SharedString> = vec!["c".into()];
823        let next_multi = toggle_chip_group_value(&opts, &sel, &"a".into(), true);
824        assert_eq!(
825            next_multi,
826            vec![SharedString::from("a"), SharedString::from("c")]
827        );
828
829        // Single mode replaces selection, and clicking active clears it
830        let next_single = toggle_chip_group_value(&opts, &sel, &"a".into(), false);
831        assert_eq!(next_single, vec![SharedString::from("a")]);
832        let cleared = toggle_chip_group_value(&opts, &next_single, &"a".into(), false);
833        assert!(cleared.is_empty());
834    }
835
836    #[test]
837    fn chip_reveal_progress_staggers_items_beyond_max_visible() {
838        assert!((chip_reveal_progress(0.0, 2, 4, false) - 1.0).abs() < 1e-4);
839        assert!(chip_reveal_progress(0.02, 5, 4, false) < 1e-4);
840        assert!((chip_reveal_progress(0.50, 5, 4, false) - 1.0).abs() < 1e-4);
841    }
842}