Skip to main content

arc_ui/inputs/
toggle_group.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/toggle-group/toggle-group.tsx` & `.module.css`
3//!
4//! P2 Component #20: `toggle-group`
5//!
6//! - Flat row on `colors.surface` where pressed options sink into a tinted fill (`11%` light /
7//!   `14%` dark `control_on`).
8//! - `Single` mode: one fill glides between options via `sample_shared_layout` (`spring.morph`).
9//! - `Multiple` mode: each item owns a fill (`scale 0.86 -> 1.0`) and adjacent active items
10//!   bridge the `2px` gap with flat adjoining corners.
11
12use std::{cell::RefCell, collections::HashMap, rc::Rc, time::Duration};
13
14use arc_motion::{
15    LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion, layout::layout_scope_key,
16    sample_shared_layout,
17};
18use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
19use gpui_kit::{
20    App, BorderStyle, Bounds, Corners, Edges, ElementId, Hsla, IntoElement, KeyDownEvent,
21    MouseButton, ParentElement, Pixels, RenderOnce, SharedString, Styled, Window,
22    assets::IconName,
23    base::{Button as BaseButton, StyledExt as _},
24    bounds, canvas,
25    component::Icon,
26    div,
27    prelude::*,
28    px, quad,
29};
30
31type ValuesChangeHandler = Rc<dyn Fn(&[SharedString], &mut Window, &mut App)>;
32
33/// Selection mode for [`ToggleGroup`].
34#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
35pub enum ToggleGroupType {
36    #[default]
37    Single,
38    Multiple,
39}
40
41/// Height preset for [`ToggleGroup`].
42#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
43pub enum ToggleGroupSize {
44    Sm,
45    #[default]
46    Md,
47}
48
49/// One toggle button inside a [`ToggleGroup`].
50#[derive(Clone)]
51pub struct ToggleGroupItem {
52    pub value: SharedString,
53    pub label: SharedString,
54    pub text: Option<SharedString>,
55    pub icon: Option<IconName>,
56    pub disabled: bool,
57}
58
59impl ToggleGroupItem {
60    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
61        let label = label.into();
62        Self {
63            value: value.into(),
64            text: Some(label.clone()),
65            label,
66            icon: None,
67            disabled: false,
68        }
69    }
70
71    pub fn icon_only(
72        value: impl Into<SharedString>,
73        label: impl Into<SharedString>,
74        icon: IconName,
75    ) -> Self {
76        Self {
77            value: value.into(),
78            label: label.into(),
79            text: None,
80            icon: Some(icon),
81            disabled: false,
82        }
83    }
84
85    pub fn icon(mut self, icon: IconName) -> Self {
86        self.icon = Some(icon);
87        self
88    }
89
90    pub fn disabled(mut self, disabled: bool) -> Self {
91        self.disabled = disabled;
92        self
93    }
94}
95
96#[derive(Clone)]
97struct ToggleGroupInternal {
98    uncontrolled: Vec<SharedString>,
99    pressed_item: Option<SharedString>,
100    item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
101}
102
103/// Arc `ToggleGroup` — single-choice gliding pill or multi-select connected fills.
104#[derive(IntoElement)]
105pub struct ToggleGroup {
106    id: ElementId,
107    label: SharedString,
108    kind: ToggleGroupType,
109    size: ToggleGroupSize,
110    items: Vec<ToggleGroupItem>,
111    values: Option<Vec<SharedString>>,
112    default_values: Vec<SharedString>,
113    disabled: bool,
114    on_values_change: Option<ValuesChangeHandler>,
115}
116
117impl ToggleGroup {
118    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
119        Self {
120            id: id.into(),
121            label: label.into(),
122            kind: ToggleGroupType::Single,
123            size: ToggleGroupSize::Md,
124            items: Vec::new(),
125            values: None,
126            default_values: Vec::new(),
127            disabled: false,
128            on_values_change: None,
129        }
130    }
131
132    pub fn kind(mut self, kind: ToggleGroupType) -> Self {
133        self.kind = kind;
134        self
135    }
136
137    pub fn size(mut self, size: ToggleGroupSize) -> Self {
138        self.size = size;
139        self
140    }
141
142    pub fn item(mut self, item: ToggleGroupItem) -> Self {
143        self.items.push(item);
144        self
145    }
146
147    pub fn items(mut self, items: impl IntoIterator<Item = ToggleGroupItem>) -> Self {
148        self.items.extend(items);
149        self
150    }
151
152    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
153        self.values = Some(vec![value.into()]);
154        self
155    }
156
157    pub fn values(mut self, values: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
158        self.values = Some(values.into_iter().map(Into::into).collect());
159        self
160    }
161
162    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
163        self.default_values = vec![value.into()];
164        self
165    }
166
167    pub fn default_values(
168        mut self,
169        values: impl IntoIterator<Item = impl Into<SharedString>>,
170    ) -> Self {
171        self.default_values = values.into_iter().map(Into::into).collect();
172        self
173    }
174
175    pub fn disabled(mut self, disabled: bool) -> Self {
176        self.disabled = disabled;
177        self
178    }
179
180    pub fn on_values_change(
181        mut self,
182        handler: impl Fn(&[SharedString], &mut Window, &mut App) + 'static,
183    ) -> Self {
184        self.on_values_change = Some(Rc::new(handler));
185        self
186    }
187}
188
189impl RenderOnce for ToggleGroup {
190    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
191        let theme = cx.arc_theme().clone();
192        let colors = theme.colors;
193        let motion = theme.motion;
194        let reduced = is_reduced_motion(cx);
195        let is_dark = theme.mode.is_dark();
196
197        let is_controlled = self.values.is_some();
198        let state_id =
199            ElementId::NamedChild(self.id.clone().into(), "__arc-toggle-group-state".into());
200        let default_vals = self.default_values.clone();
201        let internal = window.use_keyed_state(state_id, cx, |_, _| ToggleGroupInternal {
202            uncontrolled: default_vals,
203            pressed_item: None,
204            item_bounds: Rc::new(RefCell::new(HashMap::new())),
205        });
206
207        let snap = internal.read(cx).clone();
208        let active_values: Vec<SharedString> = self
209            .values
210            .clone()
211            .unwrap_or_else(|| snap.uncontrolled.clone());
212
213        let fill_color = oklab_mix(
214            colors.control_on,
215            colors.surface,
216            if is_dark { 0.14 } else { 0.11 },
217        );
218        let item_h = match self.size {
219            ToggleGroupSize::Sm => px(28.0),
220            ToggleGroupSize::Md => px(36.0),
221        };
222        let item_pad = match self.size {
223            ToggleGroupSize::Sm => px(8.0),
224            ToggleGroupSize::Md => px(10.0),
225        };
226        let icon_sz = match self.size {
227            ToggleGroupSize::Sm => px(14.0),
228            ToggleGroupSize::Md => px(16.0),
229        };
230        let text_sz = match self.size {
231            ToggleGroupSize::Sm => Typography::TEXT_XS,
232            ToggleGroupSize::Md => Typography::TEXT_SM,
233        };
234        let item_radius = px(15.0);
235
236        let is_single = self.kind == ToggleGroupType::Single;
237        let scope = layout_scope_key(&self.id);
238        let bounds_for_fill = snap.item_bounds.clone();
239        let active_first = active_values.first().cloned();
240        let morph_spec = motion.spring.morph;
241
242        let single_fill_canvas = if is_single {
243            Some(
244                canvas(
245                    |_, _, _| {},
246                    move |group_rect, _, window, cx| {
247                        let Some(val) = active_first.as_ref() else {
248                            return;
249                        };
250                        let Some(btn_rect) = bounds_for_fill.borrow().get(val).copied() else {
251                            window.request_animation_frame();
252                            return;
253                        };
254                        let local = bounds(btn_rect.origin - group_rect.origin, btn_rect.size);
255                        let target = LayoutSnapshot::uniform_radius(local, item_radius);
256                        let flip = sample_shared_layout(
257                            scope.clone(),
258                            "fill",
259                            target,
260                            Some(morph_spec),
261                            window,
262                            cx,
263                        );
264                        let paint =
265                            bounds(group_rect.origin + flip.bounds.origin, flip.bounds.size);
266                        window.paint_quad(quad(
267                            paint,
268                            flip.corner_radii,
269                            fill_color,
270                            Edges::default(),
271                            Hsla::transparent_black(),
272                            BorderStyle::Solid,
273                        ));
274                    },
275                )
276                .absolute()
277                .inset_0(),
278            )
279        } else {
280            None
281        };
282
283        let on_flags: Vec<bool> = self
284            .items
285            .iter()
286            .map(|it| active_values.contains(&it.value))
287            .collect();
288        let enabled_values: Vec<SharedString> = self
289            .items
290            .iter()
291            .filter(|it| !self.disabled && !it.disabled)
292            .map(|it| it.value.clone())
293            .collect();
294
295        let mut row = div()
296            .relative()
297            .p(px(3.0))
298            .rounded(Radii::CONTROL)
299            .border_1()
300            .border_color(colors.border)
301            .bg(colors.surface)
302            .when(self.disabled, |this| this.opacity(0.52))
303            .flex()
304            .flex_row()
305            .items_center()
306            .gap(px(2.0))
307            .when_some(single_fill_canvas, |this, c| this.child(c));
308
309        let count = self.items.len();
310        for (idx, item) in self.items.into_iter().enumerate() {
311            let val = item.value.clone();
312            let on = on_flags[idx];
313            let off = self.disabled || item.disabled;
314            let prev_on = !is_single && idx > 0 && on_flags[idx - 1];
315            let next_on = !is_single && idx + 1 < count && on_flags[idx + 1];
316
317            let multi_op = if !is_single {
318                arc_transition(
319                    (self.id.clone(), format!("tg-op-{val}")),
320                    if on { 1.0 } else { 0.0 },
321                    if reduced {
322                        Duration::ZERO
323                    } else {
324                        motion.duration.fast
325                    },
326                    motion.ease.standard,
327                    window,
328                    cx,
329                )
330            } else {
331                0.0
332            };
333
334            let is_pressed = !off && snap.pressed_item.as_ref() == Some(&val);
335            let content_scale = if reduced {
336                1.0
337            } else {
338                arc_spring(
339                    (self.id.clone(), format!("tg-press-{val}")),
340                    if is_pressed { 0.92 } else { 1.0 },
341                    motion.spring.snappy,
342                    window,
343                    cx,
344                )
345            };
346
347            let bounds_measure = snap.item_bounds.clone();
348            let val_measure = val.clone();
349            let probe = canvas(
350                move |rect, _, _| {
351                    bounds_measure
352                        .borrow_mut()
353                        .insert(val_measure.clone(), rect);
354                },
355                |_, _, _, _| {},
356            )
357            .absolute()
358            .inset_0();
359
360            let multi_bg = if !is_single && multi_op > 0.01 {
361                let bg = Hsla {
362                    a: fill_color.a * multi_op,
363                    ..fill_color
364                };
365                let left_r = if on && prev_on { px(0.0) } else { item_radius };
366                let right_r = if on && next_on { px(0.0) } else { item_radius };
367                let extend_right = if on && next_on { px(2.0) } else { px(0.0) };
368                Some(
369                    canvas(
370                        |_, _, _| {},
371                        move |rect, _, window, _| {
372                            let paint_rect = bounds(
373                                rect.origin,
374                                gpui_kit::size(rect.size.width + extend_right, rect.size.height),
375                            );
376                            window.paint_quad(quad(
377                                paint_rect,
378                                Corners {
379                                    top_left: left_r,
380                                    bottom_left: left_r,
381                                    top_right: right_r,
382                                    bottom_right: right_r,
383                                },
384                                bg,
385                                Edges::default(),
386                                Hsla::transparent_black(),
387                                BorderStyle::Solid,
388                            ));
389                        },
390                    )
391                    .absolute()
392                    .inset_0(),
393                )
394            } else {
395                None
396            };
397
398            let int_click = internal.clone();
399            let int_down = internal.clone();
400            let int_up = internal.clone();
401            let int_out = internal.clone();
402            let int_key = internal.clone();
403            let on_change = self.on_values_change.clone();
404            let on_change_key = self.on_values_change.clone();
405            let current_active = active_values.clone();
406            let val_click = val.clone();
407            let val_down = val.clone();
408            let val_key = val.clone();
409            let enabled_for_key = enabled_values.clone();
410            let hover_bg = colors.surface_muted;
411            let hover_fg = colors.foreground;
412
413            let btn = BaseButton::new(ElementId::NamedChild(
414                self.id.clone().into(),
415                SharedString::from(format!("tg-{val}")),
416            ))
417            .disabled(off)
418            .accessibility_label(item.label)
419            .on_click(move |_, window, cx| {
420                if off {
421                    return;
422                }
423                let next = if is_single {
424                    if current_active.first() == Some(&val_click) {
425                        return;
426                    }
427                    vec![val_click.clone()]
428                } else if current_active.contains(&val_click) {
429                    current_active
430                        .iter()
431                        .filter(|v| *v != &val_click)
432                        .cloned()
433                        .collect()
434                } else {
435                    let mut v = current_active.clone();
436                    v.push(val_click.clone());
437                    v
438                };
439                if !is_controlled {
440                    int_click.update(cx, |s, _| s.uncontrolled = next.clone());
441                }
442                if let Some(cb) = &on_change {
443                    cb(&next, window, cx);
444                }
445                window.refresh();
446            })
447            .relative()
448            .min_w(item_h)
449            .h(item_h)
450            .px(item_pad)
451            .rounded(item_radius)
452            .flex()
453            .items_center()
454            .justify_center()
455            .text_size(text_sz)
456            .font_medium()
457            .text_color(if on {
458                colors.foreground
459            } else {
460                colors.text_secondary
461            })
462            .when(off, |this| this.opacity(0.45))
463            .when(!off && !on, |this| {
464                this.cursor_pointer()
465                    .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
466            })
467            .when(!off && on, |this| this.cursor_pointer())
468            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
469                if !off {
470                    int_down.update(cx, |s, _| s.pressed_item = Some(val_down.clone()));
471                    window.refresh();
472                }
473            })
474            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
475                int_up.update(cx, |s, _| s.pressed_item = None);
476                window.refresh();
477            })
478            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
479                int_out.update(cx, |s, _| s.pressed_item = None);
480                window.refresh();
481            })
482            .on_key_down(move |event: &KeyDownEvent, window, cx| {
483                if !is_single || enabled_for_key.len() < 2 {
484                    return;
485                }
486                let cur = enabled_for_key
487                    .iter()
488                    .position(|v| v == &val_key)
489                    .unwrap_or(0);
490                let next_idx = match event.keystroke.key.as_str() {
491                    "right" | "down" => Some((cur + 1) % enabled_for_key.len()),
492                    "left" | "up" => {
493                        Some((cur + enabled_for_key.len() - 1) % enabled_for_key.len())
494                    }
495                    "home" => Some(0),
496                    "end" => Some(enabled_for_key.len() - 1),
497                    _ => None,
498                };
499                if let Some(ni) = next_idx {
500                    let next = vec![enabled_for_key[ni].clone()];
501                    if !is_controlled {
502                        int_key.update(cx, |s, _| s.uncontrolled = next.clone());
503                    }
504                    if let Some(cb) = &on_change_key {
505                        cb(&next, window, cx);
506                    }
507                    window.refresh();
508                }
509            })
510            .child(probe)
511            .when_some(multi_bg, |this, bg| this.child(bg))
512            .child(
513                div()
514                    .flex()
515                    .items_center()
516                    .gap(px(6.0))
517                    .when((content_scale - 1.0).abs() > 0.005, |this| {
518                        this.mt(px((1.0 - content_scale) * 10.0))
519                    })
520                    .when_some(item.icon, |this, ic| {
521                        this.child(Icon::new(ic).text_size(icon_sz))
522                    })
523                    .when_some(item.text, |this, txt| this.child(txt)),
524            );
525
526            row = row.child(btn);
527        }
528
529        div()
530            .id(self.id)
531            .flex()
532            .flex_col()
533            .items_start()
534            .gap(Spacing::S2)
535            .child(
536                div()
537                    .text_size(Typography::TEXT_XS)
538                    .text_color(colors.text_muted)
539                    .child(self.label),
540            )
541            .child(row)
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
548    use gpui_kit::{
549        Context, Render, Role, TestAppContext, div,
550        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
551    };
552
553    use super::*;
554
555    struct ToggleHost {
556        align: SharedString,
557        styles: Vec<SharedString>,
558    }
559
560    impl Render for ToggleHost {
561        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
562            div()
563                .w(px(460.0))
564                .p(Spacing::S4)
565                .flex()
566                .flex_col()
567                .gap(Spacing::S4)
568                .child(
569                    ToggleGroup::new("align-tg", "Alignment")
570                        .kind(ToggleGroupType::Single)
571                        .value(self.align.clone())
572                        .items([
573                            ToggleGroupItem::new("left", "Left"),
574                            ToggleGroupItem::new("center", "Center"),
575                            ToggleGroupItem::new("right", "Right"),
576                        ])
577                        .on_values_change(cx.listener(|this, vals: &[SharedString], _, cx| {
578                            if let Some(first) = vals.first() {
579                                this.align = first.clone();
580                                cx.notify();
581                            }
582                        })),
583                )
584                .child(
585                    ToggleGroup::new("fmt-tg", "Format")
586                        .kind(ToggleGroupType::Multiple)
587                        .values(self.styles.clone())
588                        .items([
589                            ToggleGroupItem::new("bold", "Bold"),
590                            ToggleGroupItem::new("italic", "Italic"),
591                            ToggleGroupItem::new("underline", "Underline"),
592                        ])
593                        .on_values_change(cx.listener(|this, vals: &[SharedString], _, cx| {
594                            this.styles = vals.to_vec();
595                            cx.notify();
596                        })),
597                )
598        }
599    }
600
601    #[gpui_kit::test]
602    fn toggle_group_handles_single_and_multiple_modes(cx: &mut TestAppContext) {
603        cx.update(|cx| {
604            gpui_kit::init(cx);
605            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
606        });
607        let (view, cx) = cx.add_window_view(|_, _| ToggleHost {
608            align: "left".into(),
609            styles: vec!["bold".into()],
610        });
611
612        cx.update(|window, cx| {
613            window.render_frame(cx);
614            let center = window.find_by_label("Center");
615            assert_eq!(center.role(), Some(Role::Button));
616            let pos = center.bounds().center();
617            window.pointer_down(pos, MouseButton::Left, cx);
618            window.pointer_up(pos, MouseButton::Left, cx);
619
620            let italic = window.find_by_label("Italic");
621            let ipos = italic.bounds().center();
622            window.pointer_down(ipos, MouseButton::Left, cx);
623            window.pointer_up(ipos, MouseButton::Left, cx);
624        });
625
626        assert_eq!(view.read_with(cx, |v, _| v.align.clone()), "center");
627        assert_eq!(
628            view.read_with(cx, |v, _| v.styles.clone()),
629            vec![SharedString::from("bold"), SharedString::from("italic")]
630        );
631    }
632}