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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/toggle-group/toggle-group.tsx` & `.module.css`
//!
//! P2 Component #20: `toggle-group`
//!
//! - Flat row on `colors.surface` where pressed options sink into a tinted fill (`11%` light /
//!   `14%` dark `control_on`).
//! - `Single` mode: one fill glides between options via `sample_shared_layout` (`spring.morph`).
//! - `Multiple` mode: each item owns a fill (`scale 0.86 -> 1.0`) and adjacent active items
//!   bridge the `2px` gap with flat adjoining corners.

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

use arc_motion::{
    LayoutSnapshot, arc_spring, arc_transition, is_reduced_motion, layout::layout_scope_key,
    sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    App, BorderStyle, Bounds, Corners, Edges, ElementId, Hsla, IntoElement, KeyDownEvent,
    MouseButton, ParentElement, Pixels, RenderOnce, SharedString, Styled, Window,
    assets::IconName,
    base::{Button as BaseButton, StyledExt as _},
    bounds, canvas,
    component::Icon,
    div,
    prelude::*,
    px, quad,
};

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

/// Selection mode for [`ToggleGroup`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToggleGroupType {
    #[default]
    Single,
    Multiple,
}

/// Height preset for [`ToggleGroup`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToggleGroupSize {
    Sm,
    #[default]
    Md,
}

/// One toggle button inside a [`ToggleGroup`].
#[derive(Clone)]
pub struct ToggleGroupItem {
    pub value: SharedString,
    pub label: SharedString,
    pub text: Option<SharedString>,
    pub icon: Option<IconName>,
    pub disabled: bool,
}

impl ToggleGroupItem {
    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        let label = label.into();
        Self {
            value: value.into(),
            text: Some(label.clone()),
            label,
            icon: None,
            disabled: false,
        }
    }

    pub fn icon_only(
        value: impl Into<SharedString>,
        label: impl Into<SharedString>,
        icon: IconName,
    ) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            text: None,
            icon: Some(icon),
            disabled: false,
        }
    }

    pub fn icon(mut self, icon: IconName) -> Self {
        self.icon = Some(icon);
        self
    }

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

#[derive(Clone)]
struct ToggleGroupInternal {
    uncontrolled: Vec<SharedString>,
    pressed_item: Option<SharedString>,
    item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
}

/// Arc `ToggleGroup` — single-choice gliding pill or multi-select connected fills.
#[derive(IntoElement)]
pub struct ToggleGroup {
    id: ElementId,
    label: SharedString,
    kind: ToggleGroupType,
    size: ToggleGroupSize,
    items: Vec<ToggleGroupItem>,
    values: Option<Vec<SharedString>>,
    default_values: Vec<SharedString>,
    disabled: bool,
    on_values_change: Option<ValuesChangeHandler>,
}

impl ToggleGroup {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            kind: ToggleGroupType::Single,
            size: ToggleGroupSize::Md,
            items: Vec::new(),
            values: None,
            default_values: Vec::new(),
            disabled: false,
            on_values_change: None,
        }
    }

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

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

    pub fn item(mut self, item: ToggleGroupItem) -> Self {
        self.items.push(item);
        self
    }

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

    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
        self.values = Some(vec![value.into()]);
        self
    }

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

    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
        self.default_values = vec![value.into()];
        self
    }

    pub fn default_values(
        mut self,
        values: impl IntoIterator<Item = impl Into<SharedString>>,
    ) -> Self {
        self.default_values = values.into_iter().map(Into::into).collect();
        self
    }

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

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

impl RenderOnce for ToggleGroup {
    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 is_dark = theme.mode.is_dark();

        let is_controlled = self.values.is_some();
        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-toggle-group-state".into());
        let default_vals = self.default_values.clone();
        let internal = window.use_keyed_state(state_id, cx, |_, _| ToggleGroupInternal {
            uncontrolled: default_vals,
            pressed_item: None,
            item_bounds: Rc::new(RefCell::new(HashMap::new())),
        });

        let snap = internal.read(cx).clone();
        let active_values: Vec<SharedString> = self
            .values
            .clone()
            .unwrap_or_else(|| snap.uncontrolled.clone());

        let fill_color = oklab_mix(
            colors.control_on,
            colors.surface,
            if is_dark { 0.14 } else { 0.11 },
        );
        let item_h = match self.size {
            ToggleGroupSize::Sm => px(28.0),
            ToggleGroupSize::Md => px(36.0),
        };
        let item_pad = match self.size {
            ToggleGroupSize::Sm => px(8.0),
            ToggleGroupSize::Md => px(10.0),
        };
        let icon_sz = match self.size {
            ToggleGroupSize::Sm => px(14.0),
            ToggleGroupSize::Md => px(16.0),
        };
        let text_sz = match self.size {
            ToggleGroupSize::Sm => Typography::TEXT_XS,
            ToggleGroupSize::Md => Typography::TEXT_SM,
        };
        let item_radius = px(15.0);

        let is_single = self.kind == ToggleGroupType::Single;
        let scope = layout_scope_key(&self.id);
        let bounds_for_fill = snap.item_bounds.clone();
        let active_first = active_values.first().cloned();
        let morph_spec = motion.spring.morph;

        let single_fill_canvas = if is_single {
            Some(
                canvas(
                    |_, _, _| {},
                    move |group_rect, _, window, cx| {
                        let Some(val) = active_first.as_ref() else {
                            return;
                        };
                        let Some(btn_rect) = bounds_for_fill.borrow().get(val).copied() else {
                            window.request_animation_frame();
                            return;
                        };
                        let local = bounds(btn_rect.origin - group_rect.origin, btn_rect.size);
                        let target = LayoutSnapshot::uniform_radius(local, item_radius);
                        let flip = sample_shared_layout(
                            scope.clone(),
                            "fill",
                            target,
                            Some(morph_spec),
                            window,
                            cx,
                        );
                        let paint =
                            bounds(group_rect.origin + flip.bounds.origin, flip.bounds.size);
                        window.paint_quad(quad(
                            paint,
                            flip.corner_radii,
                            fill_color,
                            Edges::default(),
                            Hsla::transparent_black(),
                            BorderStyle::Solid,
                        ));
                    },
                )
                .absolute()
                .inset_0(),
            )
        } else {
            None
        };

        let on_flags: Vec<bool> = self
            .items
            .iter()
            .map(|it| active_values.contains(&it.value))
            .collect();
        let enabled_values: Vec<SharedString> = self
            .items
            .iter()
            .filter(|it| !self.disabled && !it.disabled)
            .map(|it| it.value.clone())
            .collect();

        let mut row = div()
            .relative()
            .p(px(3.0))
            .rounded(Radii::CONTROL)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface)
            .when(self.disabled, |this| this.opacity(0.52))
            .flex()
            .flex_row()
            .items_center()
            .gap(px(2.0))
            .when_some(single_fill_canvas, |this, c| this.child(c));

        let count = self.items.len();
        for (idx, item) in self.items.into_iter().enumerate() {
            let val = item.value.clone();
            let on = on_flags[idx];
            let off = self.disabled || item.disabled;
            let prev_on = !is_single && idx > 0 && on_flags[idx - 1];
            let next_on = !is_single && idx + 1 < count && on_flags[idx + 1];

            let multi_op = if !is_single {
                arc_transition(
                    (self.id.clone(), format!("tg-op-{val}")),
                    if on { 1.0 } else { 0.0 },
                    if reduced {
                        Duration::ZERO
                    } else {
                        motion.duration.fast
                    },
                    motion.ease.standard,
                    window,
                    cx,
                )
            } else {
                0.0
            };

            let is_pressed = !off && snap.pressed_item.as_ref() == Some(&val);
            let content_scale = if reduced {
                1.0
            } else {
                arc_spring(
                    (self.id.clone(), format!("tg-press-{val}")),
                    if is_pressed { 0.92 } else { 1.0 },
                    motion.spring.snappy,
                    window,
                    cx,
                )
            };

            let bounds_measure = snap.item_bounds.clone();
            let val_measure = val.clone();
            let probe = canvas(
                move |rect, _, _| {
                    bounds_measure
                        .borrow_mut()
                        .insert(val_measure.clone(), rect);
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0();

            let multi_bg = if !is_single && multi_op > 0.01 {
                let bg = Hsla {
                    a: fill_color.a * multi_op,
                    ..fill_color
                };
                let left_r = if on && prev_on { px(0.0) } else { item_radius };
                let right_r = if on && next_on { px(0.0) } else { item_radius };
                let extend_right = if on && next_on { px(2.0) } else { px(0.0) };
                Some(
                    canvas(
                        |_, _, _| {},
                        move |rect, _, window, _| {
                            let paint_rect = bounds(
                                rect.origin,
                                gpui_kit::size(rect.size.width + extend_right, rect.size.height),
                            );
                            window.paint_quad(quad(
                                paint_rect,
                                Corners {
                                    top_left: left_r,
                                    bottom_left: left_r,
                                    top_right: right_r,
                                    bottom_right: right_r,
                                },
                                bg,
                                Edges::default(),
                                Hsla::transparent_black(),
                                BorderStyle::Solid,
                            ));
                        },
                    )
                    .absolute()
                    .inset_0(),
                )
            } else {
                None
            };

            let int_click = internal.clone();
            let int_down = internal.clone();
            let int_up = internal.clone();
            let int_out = internal.clone();
            let int_key = internal.clone();
            let on_change = self.on_values_change.clone();
            let on_change_key = self.on_values_change.clone();
            let current_active = active_values.clone();
            let val_click = val.clone();
            let val_down = val.clone();
            let val_key = val.clone();
            let enabled_for_key = enabled_values.clone();
            let hover_bg = colors.surface_muted;
            let hover_fg = colors.foreground;

            let btn = BaseButton::new(ElementId::NamedChild(
                self.id.clone().into(),
                SharedString::from(format!("tg-{val}")),
            ))
            .disabled(off)
            .accessibility_label(item.label)
            .on_click(move |_, window, cx| {
                if off {
                    return;
                }
                let next = if is_single {
                    if current_active.first() == Some(&val_click) {
                        return;
                    }
                    vec![val_click.clone()]
                } else if current_active.contains(&val_click) {
                    current_active
                        .iter()
                        .filter(|v| *v != &val_click)
                        .cloned()
                        .collect()
                } else {
                    let mut v = current_active.clone();
                    v.push(val_click.clone());
                    v
                };
                if !is_controlled {
                    int_click.update(cx, |s, _| s.uncontrolled = next.clone());
                }
                if let Some(cb) = &on_change {
                    cb(&next, window, cx);
                }
                window.refresh();
            })
            .relative()
            .min_w(item_h)
            .h(item_h)
            .px(item_pad)
            .rounded(item_radius)
            .flex()
            .items_center()
            .justify_center()
            .text_size(text_sz)
            .font_medium()
            .text_color(if on {
                colors.foreground
            } else {
                colors.text_secondary
            })
            .when(off, |this| this.opacity(0.45))
            .when(!off && !on, |this| {
                this.cursor_pointer()
                    .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
            })
            .when(!off && on, |this| this.cursor_pointer())
            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                if !off {
                    int_down.update(cx, |s, _| s.pressed_item = Some(val_down.clone()));
                    window.refresh();
                }
            })
            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
                int_up.update(cx, |s, _| s.pressed_item = None);
                window.refresh();
            })
            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
                int_out.update(cx, |s, _| s.pressed_item = None);
                window.refresh();
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if !is_single || enabled_for_key.len() < 2 {
                    return;
                }
                let cur = enabled_for_key
                    .iter()
                    .position(|v| v == &val_key)
                    .unwrap_or(0);
                let next_idx = match event.keystroke.key.as_str() {
                    "right" | "down" => Some((cur + 1) % enabled_for_key.len()),
                    "left" | "up" => {
                        Some((cur + enabled_for_key.len() - 1) % enabled_for_key.len())
                    }
                    "home" => Some(0),
                    "end" => Some(enabled_for_key.len() - 1),
                    _ => None,
                };
                if let Some(ni) = next_idx {
                    let next = vec![enabled_for_key[ni].clone()];
                    if !is_controlled {
                        int_key.update(cx, |s, _| s.uncontrolled = next.clone());
                    }
                    if let Some(cb) = &on_change_key {
                        cb(&next, window, cx);
                    }
                    window.refresh();
                }
            })
            .child(probe)
            .when_some(multi_bg, |this, bg| this.child(bg))
            .child(
                div()
                    .flex()
                    .items_center()
                    .gap(px(6.0))
                    .when((content_scale - 1.0).abs() > 0.005, |this| {
                        this.mt(px((1.0 - content_scale) * 10.0))
                    })
                    .when_some(item.icon, |this, ic| {
                        this.child(Icon::new(ic).text_size(icon_sz))
                    })
                    .when_some(item.text, |this, txt| this.child(txt)),
            );

            row = row.child(btn);
        }

        div()
            .id(self.id)
            .flex()
            .flex_col()
            .items_start()
            .gap(Spacing::S2)
            .child(
                div()
                    .text_size(Typography::TEXT_XS)
                    .text_color(colors.text_muted)
                    .child(self.label),
            )
            .child(row)
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    struct ToggleHost {
        align: SharedString,
        styles: Vec<SharedString>,
    }

    impl Render for ToggleHost {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(px(460.0))
                .p(Spacing::S4)
                .flex()
                .flex_col()
                .gap(Spacing::S4)
                .child(
                    ToggleGroup::new("align-tg", "Alignment")
                        .kind(ToggleGroupType::Single)
                        .value(self.align.clone())
                        .items([
                            ToggleGroupItem::new("left", "Left"),
                            ToggleGroupItem::new("center", "Center"),
                            ToggleGroupItem::new("right", "Right"),
                        ])
                        .on_values_change(cx.listener(|this, vals: &[SharedString], _, cx| {
                            if let Some(first) = vals.first() {
                                this.align = first.clone();
                                cx.notify();
                            }
                        })),
                )
                .child(
                    ToggleGroup::new("fmt-tg", "Format")
                        .kind(ToggleGroupType::Multiple)
                        .values(self.styles.clone())
                        .items([
                            ToggleGroupItem::new("bold", "Bold"),
                            ToggleGroupItem::new("italic", "Italic"),
                            ToggleGroupItem::new("underline", "Underline"),
                        ])
                        .on_values_change(cx.listener(|this, vals: &[SharedString], _, cx| {
                            this.styles = vals.to_vec();
                            cx.notify();
                        })),
                )
        }
    }

    #[gpui_kit::test]
    fn toggle_group_handles_single_and_multiple_modes(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| ToggleHost {
            align: "left".into(),
            styles: vec!["bold".into()],
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let center = window.find_by_label("Center");
            assert_eq!(center.role(), Some(Role::Button));
            let pos = center.bounds().center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);

            let italic = window.find_by_label("Italic");
            let ipos = italic.bounds().center();
            window.pointer_down(ipos, MouseButton::Left, cx);
            window.pointer_up(ipos, MouseButton::Left, cx);
        });

        assert_eq!(view.read_with(cx, |v, _| v.align.clone()), "center");
        assert_eq!(
            view.read_with(cx, |v, _| v.styles.clone()),
            vec![SharedString::from("bold"), SharedString::from("italic")]
        );
    }
}