arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/chip-group/chip-group.tsx` & `.module.css`
//!
//! P4 Component #6: `chip-group`
//!
//! - Selectable filter chips (`ControlHeights::SM` 36px, `0 14px` horizontal padding,
//!   `Radii::PILL`, `1px border`):
//!   - Selecting morphs the chip: a `SLOT = 18px` leading slot springs open on
//!     `motion.spring.morph`, driving a single `grown (0..=1)` progress that simultaneously
//!     scales (`min(grown, 1.1)`), sharpens (`(1 - grown) * 2px` blur), fades (`min(1, grown * 1.4)`),
//!     and draws (`pathLength = clamp(grown, 0.001, 1.0)`) the `14×14px` checkmark (`M4 12.5 9.5 18 20 6.5`)
//!     in exact step with the space the label opens up.
//!   - Selected surface uses Oklab tints: `11% accent` over `surface` (`16%` on hover) and `42%
//!     accent` over `border` (`60%` on hover).
//!   - Press scales `.body` to `0.97` (`duration.instant`).
//!   - Overflow folding (`max_visible`): chips beyond `max_visible` fold behind a `"+N more"` /
//!     `"Show less"` chip (`surface_muted` background). Chips selected while expanded remain
//!     pinned in view when folded so selections are never hidden.
//!   - Revealed overflow chips stagger in by `min((index - max_visible) * 35ms, 300ms)`.
//!   - `HeightFrame`: tracks wrapped row height on `motion.spring.smooth`.

use std::{cell::RefCell, rc::Rc, time::Duration};

use arc_motion::{
    BlurFallback, CubicBezier, PathPoint, PolylinePath, arc_spring, arc_transition,
    is_reduced_motion, motion_now,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, ParentElement,
    Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
    base::{Button as BaseButton, StyledExt as _},
    canvas, div,
    prelude::*,
    px,
};

type ChipGroupChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;

/// Width (`18px`) of the leading check slot (`14px` glyph + `4px` gap).
pub const CHIP_CHECK_SLOT_PX: f32 = 18.0;
/// Stagger step (`35ms`, `motion.stagger.item`) for chips revealed by `+N more`.
pub const CHIP_REVEAL_STAGGER_SECS: f64 = 0.035;
/// Maximum stagger delay (`300ms`) for revealed overflow chips.
pub const CHIP_REVEAL_MAX_DELAY_SECS: f64 = 0.30;

/// Derived check visual parameters `(slot_width_px, scale, opacity, path_length)` from `grown`
/// (`0.0..=1.0`), matching upstream `useTransform(grown, ...)`.
pub fn chip_check_metrics(grown: f32, reduced: bool) -> (f32, f32, f32, f32) {
    let g = grown.clamp(0.0, 1.15);
    let slot_w = (g * CHIP_CHECK_SLOT_PX).clamp(0.0, CHIP_CHECK_SLOT_PX);
    let scale = g.min(1.1);
    let raw_op = (g * 1.4).clamp(0.0, 1.0);
    let blur = BlurFallback::evaluate(px(((1.0 - g).max(0.0)) * 2.0), reduced);
    let opacity = (raw_op * blur.opacity_multiplier).clamp(0.0, 1.0);
    let path_len = g.clamp(0.0, 1.0);
    (slot_w, scale, opacity, path_len)
}

/// Computes `0..=1` entrance progress for an overflow chip at `index >= max_visible` at `elapsed`
/// seconds after expanding `+N more`.
pub fn chip_reveal_progress(elapsed: f64, index: usize, max_visible: usize, reduced: bool) -> f32 {
    if reduced || index < max_visible {
        return 1.0;
    }
    let delay =
        ((index - max_visible) as f64 * CHIP_REVEAL_STAGGER_SECS).min(CHIP_REVEAL_MAX_DELAY_SECS);
    if elapsed <= delay {
        return 0.0;
    }
    let t = ((elapsed - delay) / 0.16).clamp(0.0, 1.0) as f32;
    CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t)
}

/// Sampled `(enter_opacity, enter_y_px, exit_opacity, exit_y_px)` for the `MoreChip` label swap
/// (`"+N more"` ↔ `"Show less"`).
pub fn chip_more_swap_sample(elapsed: f64, reduced: bool) -> (f32, f32, f32, f32) {
    if reduced {
        let t = (elapsed / 0.15).clamp(0.0, 1.0) as f32;
        return (t, 0.0, 1.0 - t, 0.0);
    }
    let t_in = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
    let e_in = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t_in);
    let blur_in = BlurFallback::evaluate(px(4.0 * (1.0 - e_in)), false);
    let enter_op = (e_in * blur_in.opacity_multiplier).clamp(0.0, 1.0);
    let enter_y = 4.2 * (1.0 - e_in);

    let t_out = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
    let e_out = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t_out);
    let blur_out = BlurFallback::evaluate(px(2.0 * e_out), false);
    let exit_op = ((1.0 - e_out) * blur_out.opacity_multiplier).clamp(0.0, 1.0);
    let exit_y = -4.2 * e_out;

    (enter_op, enter_y, exit_op, exit_y)
}

/// Toggles `target` inside `selected` according to `multiple` and preserves `options` declaration order.
pub fn toggle_chip_group_value(
    options: &[ChipOption],
    selected: &[SharedString],
    target: &SharedString,
    multiple: bool,
) -> Vec<SharedString> {
    let is_on = selected.iter().any(|v| v == target);
    if !multiple {
        return if is_on {
            Vec::new()
        } else {
            vec![target.clone()]
        };
    }
    options
        .iter()
        .filter(|opt| {
            if &opt.value == target {
                !is_on
            } else {
                selected.iter().any(|v| v == &opt.value)
            }
        })
        .map(|opt| opt.value.clone())
        .collect()
}

/// One selectable chip option inside [`ChipGroup`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChipOption {
    pub value: SharedString,
    pub label: SharedString,
}

impl ChipOption {
    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
        }
    }
}

#[derive(Clone)]
struct ChipGroupInternal {
    uncontrolled_value: Vec<SharedString>,
    expanded: bool,
    expanded_changed_at_secs: f64,
    previous_more_text: Option<SharedString>,
    pinned: Vec<SharedString>,
    active_focus_key: Option<SharedString>,
    hovered_chip: Option<SharedString>,
    pressed_chip: Option<SharedString>,
    measured_frame_h: Rc<RefCell<Option<f32>>>,
    focus_handle: FocusHandle,
}

impl ChipGroupInternal {
    fn new(default_value: Vec<SharedString>, now: f64, focus_handle: FocusHandle) -> Self {
        Self {
            pinned: default_value.clone(),
            uncontrolled_value: default_value,
            expanded: false,
            expanded_changed_at_secs: now - 10.0,
            previous_more_text: None,
            active_focus_key: None,
            hovered_chip: None,
            pressed_chip: None,
            measured_frame_h: Rc::new(RefCell::new(None)),
            focus_handle,
        }
    }
}

fn paint_chip_check(
    origin_x: Pixels,
    origin_y: Pixels,
    scale: f32,
    path_length: f32,
    opacity: f32,
    color: Hsla,
    window: &mut Window,
) {
    let len = path_length.clamp(0.0, 1.0);
    let alpha = opacity.clamp(0.0, 1.0);
    if len <= 0.01 || alpha <= 0.01 || scale <= 0.05 {
        return;
    }
    // `M4 12.5 9.5 18 20 6.5` in 24×24 viewBox scaled into 14×14px with transform-origin `(0, 50%)`.
    let s = 14.0 / 24.0;
    let cy = 7.0_f32;
    let transform_pt = |vx: f32, vy: f32| -> PathPoint {
        let bx = vx * s;
        let by = vy * s;
        PathPoint::new(bx * scale, cy + (by - cy) * scale)
    };
    let poly = PolylinePath::new(vec![
        transform_pt(4.0, 12.5),
        transform_pt(9.5, 18.0),
        transform_pt(20.0, 6.5),
    ]);
    let sliced = poly.slice(0.0, len);
    let stroke_color = Hsla {
        a: color.a * alpha,
        ..color
    };
    if let Some(b) = sliced.to_stroke_builder(origin_x, origin_y, px(2.1))
        && let Ok(path) = b.build()
    {
        window.paint_path(path, stroke_color);
    }
}

/// Arc `ChipGroup` — single or multi-select filter chips with spring check-slot growth, Oklab
/// accent surface tinting, `"+N more"` overflow folding with pinned selections, and `HeightFrame`
/// smooth row height morphing.
#[derive(IntoElement)]
pub struct ChipGroup {
    id: ElementId,
    label: SharedString,
    show_label: bool,
    options: Vec<ChipOption>,
    value: Option<Vec<SharedString>>,
    default_value: Vec<SharedString>,
    multiple: bool,
    max_visible: Option<usize>,
    disabled: bool,
    width: Option<Pixels>,
    on_value_change: Option<ChipGroupChangeHandler>,
}

impl ChipGroup {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            show_label: false,
            options: Vec::new(),
            value: None,
            default_value: Vec::new(),
            multiple: true,
            max_visible: None,
            disabled: false,
            width: None,
            on_value_change: None,
        }
    }

    pub fn show_label(mut self, show: bool) -> Self {
        self.show_label = show;
        self
    }

    pub fn option(mut self, option: ChipOption) -> Self {
        self.options.push(option);
        self
    }

    pub fn options(mut self, options: impl IntoIterator<Item = ChipOption>) -> Self {
        self.options.extend(options);
        self
    }

    pub fn value<I, S>(mut self, value: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.value = Some(value.into_iter().map(Into::into).collect());
        self
    }

    pub fn default_value<I, S>(mut self, value: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<SharedString>,
    {
        self.default_value = value.into_iter().map(Into::into).collect();
        self
    }

    pub fn multiple(mut self, multiple: bool) -> Self {
        self.multiple = multiple;
        self
    }

    pub fn max_visible(mut self, max_visible: usize) -> Self {
        self.max_visible = Some(max_visible.max(1));
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_value_change(
        mut self,
        handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_value_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for ChipGroup {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let initial_vals = self
            .value
            .clone()
            .unwrap_or_else(|| self.default_value.clone());

        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-chip-group-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            ChipGroupInternal::new(initial_vals.clone(), now, cx.focus_handle())
        });

        let selected: Vec<SharedString> = self
            .value
            .clone()
            .unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
        let snap = internal.read(cx).clone();

        let max_vis = self.max_visible.unwrap_or(usize::MAX);
        let foldable = self.options.len() > max_vis;
        let visible_options: Vec<(usize, ChipOption)> = if !foldable || snap.expanded {
            self.options.iter().cloned().enumerate().collect()
        } else {
            self.options
                .iter()
                .cloned()
                .enumerate()
                .filter(|(idx, opt)| {
                    *idx < max_vis
                        || snap.pinned.contains(&opt.value)
                        || selected.contains(&opt.value)
                })
                .collect()
        };
        let hidden_count = self.options.len().saturating_sub(visible_options.len());
        let show_more = foldable && (snap.expanded || hidden_count > 0);

        // `HeightFrame` spring (`motion.spring.smooth`).
        let measured_h = snap.measured_frame_h.borrow().map(|h| h.max(36.0));
        let frame_h = arc_motion::arc_measured_spring(
            (self.id.clone(), "frame-h"),
            measured_h,
            36.0,
            motion.spring.smooth,
            window,
            cx,
        )
        .max(36.0);

        let frame_h_ref = snap.measured_frame_h.clone();
        let frame_probe = canvas(
            move |rect, window, _| {
                let h = f32::from(rect.size.height).max(36.0);
                let prev = *frame_h_ref.borrow();
                *frame_h_ref.borrow_mut() = Some(h);
                if prev.is_none_or(|prev| (prev - h).abs() > 0.5) {
                    window.request_animation_frame();
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();

        let expand_elapsed = (now - snap.expanded_changed_at_secs).max(0.0);
        let disabled = self.disabled;
        let multiple = self.multiple;

        let mut chip_els = Vec::with_capacity(visible_options.len() + 1);
        for (orig_idx, option) in &visible_options {
            let is_selected = selected.contains(&option.value);
            let is_hovered = snap.hovered_chip.as_ref() == Some(&option.value) && !disabled;
            let is_pressed = snap.pressed_chip.as_ref() == Some(&option.value) && !disabled;
            let is_focused = snap.active_focus_key.as_ref() == Some(&option.value);

            // `grown` (0..=1) springs on `motion.spring.morph`, driving slot width + check draw/scale/blur.
            let grown = if reduced {
                if is_selected { 1.0 } else { 0.0 }
            } else {
                arc_spring(
                    (self.id.clone(), format!("grown-{}", option.value)),
                    if is_selected { 1.0 } else { 0.0 },
                    motion.spring.morph,
                    window,
                    cx,
                )
            };
            let (slot_w, check_scale, check_op, check_path_len) =
                chip_check_metrics(grown, reduced);

            // Staggered entrance when revealed by `+N more`.
            let reveal_p = if snap.expanded && foldable && *orig_idx >= max_vis {
                let rp = chip_reveal_progress(expand_elapsed, *orig_idx, max_vis, reduced);
                if rp < 0.999 {
                    window.request_animation_frame();
                }
                rp
            } else {
                1.0
            };

            let hover_p = arc_transition(
                (self.id.clone(), format!("hover-{}", option.value)),
                if is_hovered || is_focused { 1.0 } else { 0.0 },
                if reduced {
                    Duration::ZERO
                } else {
                    motion.duration.fast
                },
                motion.ease.standard,
                window,
                cx,
            );
            let sel_p = grown.clamp(0.0, 1.0);

            let resting_unsel_bg = colors.surface;
            let resting_sel_bg = oklab_mix(colors.accent, colors.surface, 0.11);
            let hover_sel_bg = oklab_mix(colors.accent, colors.surface, 0.16);
            let sel_bg = oklab_mix(hover_sel_bg, resting_sel_bg, hover_p);
            let chip_bg = oklab_mix(sel_bg, resting_unsel_bg, sel_p);

            let resting_unsel_border = oklab_mix(colors.border_strong, colors.border, hover_p);
            let resting_sel_border = oklab_mix(colors.accent, colors.border, 0.42);
            let hover_sel_border = oklab_mix(colors.accent, colors.border, 0.60);
            let sel_border = oklab_mix(hover_sel_border, resting_sel_border, hover_p);
            let chip_border = oklab_mix(sel_border, resting_unsel_border, sel_p);

            let text_fg = if is_selected || is_hovered || is_focused {
                colors.foreground
            } else {
                colors.text_secondary
            };
            let check_color = colors.accent_strong;
            let body_h = if is_pressed && !reduced { 35.0 } else { 36.0 };

            let int_hover = internal.clone();
            let int_down = internal.clone();
            let int_up = internal.clone();
            let int_out = internal.clone();
            let int_click = internal.clone();
            let all_opts = self.options.clone();
            let cur_selected = selected.clone();
            let on_change = self.on_value_change.clone();
            let val_hover = option.value.clone();
            let val_down = option.value.clone();
            let val_up = option.value.clone();
            let val_out = option.value.clone();
            let val_click = option.value.clone();
            let focus_for_click = snap.focus_handle.clone();

            chip_els.push(
                BaseButton::new(ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from(format!("chip-{}", option.value)),
                ))
                .accessibility_label(option.label.clone())
                .disabled(disabled)
                .on_click(move |_, window, cx| {
                    if disabled {
                        return;
                    }
                    window.focus(&focus_for_click, cx);
                    let next_vals =
                        toggle_chip_group_value(&all_opts, &cur_selected, &val_click, multiple);
                    int_click.update(cx, |s, _| {
                        s.uncontrolled_value = next_vals.clone();
                        s.active_focus_key = Some(val_click.clone());
                        s.pressed_chip = None;
                    });
                    if let Some(cb) = &on_change {
                        cb(&next_vals, window, cx);
                    }
                    window.refresh();
                })
                .relative()
                .h(px(body_h))
                .px(px(14.0))
                .flex()
                .flex_row()
                .items_center()
                .rounded(Radii::PILL)
                .border_1()
                .border_color(chip_border)
                .bg(chip_bg)
                .opacity(if disabled { 0.5 } else { reveal_p })
                .text_size(Typography::TEXT_SM)
                .font_medium()
                .text_color(text_fg)
                .when(!disabled, |this| this.cursor_pointer())
                .on_hover(move |hovered, window, cx| {
                    int_hover.update(cx, |s, _| {
                        if *hovered {
                            s.hovered_chip = Some(val_hover.clone());
                        } else if s.hovered_chip.as_ref() == Some(&val_hover) {
                            s.hovered_chip = None;
                        }
                    });
                    window.refresh();
                })
                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                    if !disabled {
                        int_down.update(cx, |s, _| s.pressed_chip = Some(val_down.clone()));
                        window.refresh();
                    }
                })
                .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                    if int_up.read(cx).pressed_chip.as_ref() == Some(&val_up) {
                        int_up.update(cx, |s, _| s.pressed_chip = None);
                        window.refresh();
                    }
                })
                .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                    if int_out.read(cx).pressed_chip.as_ref() == Some(&val_out) {
                        int_out.update(cx, |s, _| s.pressed_chip = None);
                        window.refresh();
                    }
                })
                .when(check_op > 0.01, |this| {
                    this.child(
                        div()
                            .absolute()
                            .left(px(12.0))
                            .top(px((body_h - 14.0) * 0.5))
                            .size(px(14.0))
                            .child(
                                canvas(
                                    |_, _, _| {},
                                    move |rect, _, window, _| {
                                        paint_chip_check(
                                            rect.origin.x,
                                            rect.origin.y,
                                            check_scale,
                                            check_path_len,
                                            check_op,
                                            check_color,
                                            window,
                                        );
                                    },
                                )
                                .size_full(),
                            ),
                    )
                })
                .child(div().w(px(slot_w)).flex_none())
                .child(div().truncate().child(option.label.clone()))
                .into_any_element(),
            );
        }

        // Optional `+N more` / `Show less` overflow chip.
        if show_more {
            let more_key: SharedString = "__more__".into();
            let more_text: SharedString = if snap.expanded {
                "Show less".into()
            } else {
                SharedString::from(format!("+{hidden_count} more"))
            };
            let is_more_hovered = snap.hovered_chip.as_ref() == Some(&more_key) && !disabled;
            let is_more_focused = snap.active_focus_key.as_ref() == Some(&more_key);
            let more_border = if is_more_hovered || is_more_focused {
                colors.border_strong
            } else {
                colors.border
            };
            let more_fg = if is_more_hovered || is_more_focused {
                colors.foreground
            } else {
                colors.text_muted
            };

            let (in_op, in_y, out_op, out_y) = if expand_elapsed < 0.25 {
                window.request_animation_frame();
                chip_more_swap_sample(expand_elapsed, reduced)
            } else {
                (1.0, 0.0, 0.0, 0.0)
            };

            let mut more_label_slot = div()
                .relative()
                .h(px(20.0))
                .overflow_hidden()
                .flex()
                .items_center()
                .justify_center()
                .child(div().mt(px(in_y)).opacity(in_op).child(more_text.clone()));
            if out_op > 0.01
                && let Some(prev_txt) = snap.previous_more_text.clone()
            {
                more_label_slot = more_label_slot.child(
                    div()
                        .absolute()
                        .top_0()
                        .left_0()
                        .mt(px(out_y))
                        .opacity(out_op)
                        .child(prev_txt),
                );
            }

            let int_more_hover = internal.clone();
            let int_more_click = internal.clone();
            let cur_selected_for_pin = selected.clone();
            let cur_more_text = more_text.clone();
            let focus_for_more = snap.focus_handle.clone();

            chip_els.push(
                BaseButton::new(ElementId::NamedChild(self.id.clone().into(), "more".into()))
                    .accessibility_label(more_text)
                    .disabled(disabled)
                    .on_click(move |_, window, cx| {
                        if disabled {
                            return;
                        }
                        window.focus(&focus_for_more, cx);
                        let t_now = motion_now(cx);
                        int_more_click.update(cx, |s, _| {
                            if s.expanded {
                                s.pinned = cur_selected_for_pin.clone();
                            }
                            s.expanded = !s.expanded;
                            s.expanded_changed_at_secs = t_now;
                            s.previous_more_text = Some(cur_more_text.clone());
                            s.active_focus_key = Some("__more__".into());
                        });
                        window.refresh();
                    })
                    .h(ControlHeights::SM)
                    .px(px(14.0))
                    .flex()
                    .flex_row()
                    .items_center()
                    .rounded(Radii::PILL)
                    .border_1()
                    .border_color(more_border)
                    .bg(colors.surface_muted)
                    .text_size(Typography::TEXT_SM)
                    .font_medium()
                    .text_color(more_fg)
                    .when(!disabled, |this| this.cursor_pointer())
                    .on_hover(move |hovered, window, cx| {
                        int_more_hover.update(cx, |s, _| {
                            if *hovered {
                                s.hovered_chip = Some("__more__".into());
                            } else if s.hovered_chip.as_deref() == Some("__more__") {
                                s.hovered_chip = None;
                            }
                        });
                        window.refresh();
                    })
                    .child(more_label_slot)
                    .into_any_element(),
            );
        }

        // Keyboard roving focus (`ArrowRight`/`ArrowDown`, `ArrowLeft`/`ArrowUp`, `Home`, `End`,
        // `Enter` / `Space`).
        let mut focus_keys: Vec<SharedString> = visible_options
            .iter()
            .map(|(_, o)| o.value.clone())
            .collect();
        if show_more {
            focus_keys.push("__more__".into());
        }
        let int_key = internal.clone();
        let all_opts_key = self.options.clone();
        let selected_for_key = selected;
        let on_change_key = self.on_value_change.clone();
        let focus_handle = snap.focus_handle.clone();

        let group_box = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "group".into(),
            ))
            .test_support()
            .role(Role::Group)
            .aria_label(self.label.clone())
            .track_focus(&focus_handle)
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if disabled || focus_keys.is_empty() {
                    return;
                }
                let cur_key = int_key.read(cx).active_focus_key.clone();
                let cur_idx = cur_key
                    .as_ref()
                    .and_then(|k| focus_keys.iter().position(|fk| fk == k))
                    .unwrap_or(0);
                let len = focus_keys.len();

                match event.keystroke.key.as_str() {
                    "right" | "arrowright" | "down" | "arrowdown" => {
                        let next_k = focus_keys[(cur_idx + 1) % len].clone();
                        int_key.update(cx, |s, _| s.active_focus_key = Some(next_k));
                        window.refresh();
                    }
                    "left" | "arrowleft" | "up" | "arrowup" => {
                        let prev_k = focus_keys[(cur_idx + len - 1) % len].clone();
                        int_key.update(cx, |s, _| s.active_focus_key = Some(prev_k));
                        window.refresh();
                    }
                    "home" => {
                        let first_k = focus_keys[0].clone();
                        int_key.update(cx, |s, _| s.active_focus_key = Some(first_k));
                        window.refresh();
                    }
                    "end" => {
                        let last_k = focus_keys[len - 1].clone();
                        int_key.update(cx, |s, _| s.active_focus_key = Some(last_k));
                        window.refresh();
                    }
                    "enter" | " " | "space" => {
                        let target_k = focus_keys[cur_idx].clone();
                        if target_k.as_ref() == "__more__" {
                            let t_now = motion_now(cx);
                            int_key.update(cx, |s, _| {
                                if s.expanded {
                                    s.pinned = selected_for_key.clone();
                                }
                                s.expanded = !s.expanded;
                                s.expanded_changed_at_secs = t_now;
                            });
                        } else {
                            let next_vals = toggle_chip_group_value(
                                &all_opts_key,
                                &selected_for_key,
                                &target_k,
                                multiple,
                            );
                            int_key.update(cx, |s, _| {
                                s.uncontrolled_value = next_vals.clone();
                            });
                            if let Some(cb) = &on_change_key {
                                cb(&next_vals, window, cx);
                            }
                        }
                        window.refresh();
                    }
                    _ => {}
                }
            })
            .w_full()
            .h(px(frame_h))
            .overflow_hidden()
            .child(
                div()
                    .relative()
                    .w_full()
                    .flex()
                    .flex_row()
                    .flex_wrap()
                    .gap(Spacing::S2)
                    .child(frame_probe)
                    .children(chip_els),
            );

        div()
            .id(self.id)
            .test_support()
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w_full())
            .flex()
            .flex_col()
            .gap(Spacing::S2)
            .when(self.show_label, |this| {
                this.child(
                    div()
                        .text_size(Typography::TEXT_SM)
                        .font_medium()
                        .text_color(colors.foreground)
                        .child(self.label),
                )
            })
            .child(group_box)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn chip_check_metrics_coordinate_slot_width_and_path_length() {
        let (w0, sc0, op0, len0) = chip_check_metrics(0.0, false);
        assert!(w0.abs() < 1e-4);
        assert!(sc0.abs() < 1e-4);
        assert!(op0.abs() < 1e-4);
        assert!(len0.abs() < 1e-4);

        let (w1, sc1, op1, len1) = chip_check_metrics(1.0, false);
        assert!((w1 - CHIP_CHECK_SLOT_PX).abs() < 1e-4);
        assert!((sc1 - 1.0).abs() < 1e-4);
        assert!((op1 - 1.0).abs() < 1e-4);
        assert!((len1 - 1.0).abs() < 1e-4);
    }

    #[test]
    fn toggle_chip_group_value_handles_multi_and_single_modes() {
        let opts = vec![
            ChipOption::new("a", "Alpha"),
            ChipOption::new("b", "Beta"),
            ChipOption::new("c", "Gamma"),
        ];
        // Multiple mode preserves option declaration order
        let sel: Vec<SharedString> = vec!["c".into()];
        let next_multi = toggle_chip_group_value(&opts, &sel, &"a".into(), true);
        assert_eq!(
            next_multi,
            vec![SharedString::from("a"), SharedString::from("c")]
        );

        // Single mode replaces selection, and clicking active clears it
        let next_single = toggle_chip_group_value(&opts, &sel, &"a".into(), false);
        assert_eq!(next_single, vec![SharedString::from("a")]);
        let cleared = toggle_chip_group_value(&opts, &next_single, &"a".into(), false);
        assert!(cleared.is_empty());
    }

    #[test]
    fn chip_reveal_progress_staggers_items_beyond_max_visible() {
        assert!((chip_reveal_progress(0.0, 2, 4, false) - 1.0).abs() < 1e-4);
        assert!(chip_reveal_progress(0.02, 5, 4, false) < 1e-4);
        assert!((chip_reveal_progress(0.50, 5, 4, false) - 1.0).abs() < 1e-4);
    }
}