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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/segmented-control/segmented-control.tsx` & `.module.css`
//!
//! P2 Component #19: `segmented-control`
//!
//! - Sunken track (`colors.surface_muted`) with one raised selection pill (`colors.surface` +
//!   `1px` border) gliding beneath labels via `sample_shared_layout` (`motion.spring.morph`).
//! - Supports `on_option_intent` hover preloading, arrow/Home/End keyboard selection, and
//!   horizontal overflow scrolling with `20px` `EdgeFadeMask`.

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

use arc_motion::{
    EdgeFadeMask, EdgeFadeSide, LayoutSnapshot, layout::layout_scope_key, sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography};
use gpui_kit::{
    App, BorderStyle, Bounds, ElementId, IntoElement, KeyDownEvent, ParentElement, Pixels,
    RenderOnce, ScrollEvent, SharedString, Styled, Window,
    base::{Button as BaseButton, StyledExt as _},
    bounds, canvas, div,
    prelude::*,
    px, quad,
};

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

/// One segment inside a [`SegmentedControl`].
#[derive(Clone)]
pub struct Segment {
    pub value: SharedString,
    pub label: SharedString,
    pub accessory: Option<SharedString>,
}

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

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

#[derive(Clone)]
struct SegmentedInternal {
    uncontrolled_value: SharedString,
    scroll_offset: f32,
    content_width: Rc<RefCell<f32>>,
    viewport_width: Rc<RefCell<f32>>,
    item_bounds: Rc<RefCell<HashMap<SharedString, Bounds<Pixels>>>>,
}

/// Arc `SegmentedControl` — mutually exclusive mode switcher with a gliding FLIP highlight pill.
#[derive(IntoElement)]
pub struct SegmentedControl {
    id: ElementId,
    options: Vec<Segment>,
    value: Option<SharedString>,
    default_value: Option<SharedString>,
    label: Option<SharedString>,
    on_value_change: Option<SegmentHandler>,
    on_option_intent: Option<SegmentHandler>,
}

impl SegmentedControl {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            options: Vec::new(),
            value: None,
            default_value: None,
            label: None,
            on_value_change: None,
            on_option_intent: None,
        }
    }

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

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

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

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

    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.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
    }

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

impl RenderOnce for SegmentedControl {
    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 fallback = self
            .default_value
            .clone()
            .or_else(|| self.options.first().map(|s| s.value.clone()))
            .unwrap_or_default();

        let is_controlled = self.value.is_some();
        let state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-segmented-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, _| SegmentedInternal {
            uncontrolled_value: fallback,
            scroll_offset: 0.0,
            content_width: Rc::new(RefCell::new(0.0)),
            viewport_width: Rc::new(RefCell::new(0.0)),
            item_bounds: Rc::new(RefCell::new(HashMap::new())),
        });

        let snap = internal.read(cx).clone();
        let active = self
            .value
            .clone()
            .unwrap_or_else(|| snap.uncontrolled_value.clone());

        let scope = layout_scope_key(&self.id);
        let bounds_for_pill = snap.item_bounds.clone();
        let active_for_pill = active.clone();
        let morph_spec = motion.spring.morph;
        let pill_bg = colors.surface;
        let pill_border = colors.border;
        let pill_radius = px(14.0);

        let pill_canvas = canvas(
            |_, _, _| {},
            move |track_rect, _, window, cx| {
                let Some(btn_rect) = bounds_for_pill.borrow().get(&active_for_pill).copied() else {
                    window.request_animation_frame();
                    return;
                };
                let local_rect = bounds(btn_rect.origin - track_rect.origin, btn_rect.size);
                let target = LayoutSnapshot::uniform_radius(local_rect, pill_radius);
                let flip = sample_shared_layout(
                    scope.clone(),
                    "selection",
                    target,
                    Some(morph_spec),
                    window,
                    cx,
                );
                let paint_rect = bounds(track_rect.origin + flip.bounds.origin, flip.bounds.size);
                window.paint_quad(quad(
                    paint_rect,
                    flip.corner_radii,
                    pill_bg,
                    gpui_kit::Edges::all(px(1.0)),
                    pill_border,
                    BorderStyle::Solid,
                ));
            },
        )
        .absolute()
        .inset_0();

        let all_values: Vec<SharedString> = self.options.iter().map(|s| s.value.clone()).collect();
        let scroll_x = snap.scroll_offset;

        let mut track = div()
            .relative()
            .flex()
            .flex_row()
            .items_center()
            .gap(px(2.0))
            .ml(px(-scroll_x))
            .child(pill_canvas);

        for segment in self.options {
            let seg_val = segment.value.clone();
            let selected = active == seg_val;

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

            let int_click = internal.clone();
            let int_key = internal.clone();
            let on_change = self.on_value_change.clone();
            let on_change_key = self.on_value_change.clone();
            let on_intent = self.on_option_intent.clone();
            let val_click = seg_val.clone();
            let val_key = seg_val.clone();
            let val_intent = seg_val.clone();
            let vals_key = all_values.clone();
            let hover_fg = colors.foreground;

            let btn = BaseButton::new(ElementId::NamedChild(
                self.id.clone().into(),
                SharedString::from(format!("seg-{seg_val}")),
            ))
            .accessibility_label(segment.label.clone())
            .on_click(move |_, window, cx| {
                if !is_controlled {
                    int_click.update(cx, |s, _| s.uncontrolled_value = val_click.clone());
                }
                if let Some(cb) = &on_change {
                    cb(&val_click, window, cx);
                }
                window.refresh();
            })
            .relative()
            .flex_none()
            .min_h(ControlHeights::SM)
            .px(px(12.0))
            .rounded(pill_radius)
            .flex()
            .items_center()
            .justify_center()
            .gap(px(6.0))
            .text_size(Typography::TEXT_SM)
            .font_medium()
            .text_color(if selected {
                colors.foreground
            } else {
                colors.text_muted
            })
            .cursor_pointer()
            .when(!selected, |this| {
                this.hover(move |s| s.text_color(hover_fg))
            })
            .when_some(on_intent, |this, intent_cb| {
                this.on_hover(move |hovered, window, cx| {
                    if *hovered {
                        intent_cb(&val_intent, window, cx);
                    }
                })
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if vals_key.len() < 2 {
                    return;
                }
                let cur = vals_key.iter().position(|v| v == &val_key).unwrap_or(0);
                let next_idx = match event.keystroke.key.as_str() {
                    "right" | "down" => Some((cur + 1) % vals_key.len()),
                    "left" | "up" => Some((cur + vals_key.len() - 1) % vals_key.len()),
                    "home" => Some(0),
                    "end" => Some(vals_key.len() - 1),
                    _ => None,
                };
                if let Some(ni) = next_idx {
                    let next_val = vals_key[ni].clone();
                    if !is_controlled {
                        int_key.update(cx, |s, _| s.uncontrolled_value = next_val.clone());
                    }
                    if let Some(cb) = &on_change_key {
                        cb(&next_val, window, cx);
                    }
                    window.refresh();
                }
            })
            .child(probe)
            .child(segment.label)
            .when_some(segment.accessory, |this, acc| {
                this.child(
                    div()
                        .px(px(6.0))
                        .py(px(1.0))
                        .rounded(Radii::PILL)
                        .bg(colors.surface_muted)
                        .text_size(Typography::TEXT_XS)
                        .text_color(colors.text_muted)
                        .child(acc),
                )
            });

            track = track.child(btn);
        }

        let cw_ref = snap.content_width.clone();
        let vw_ref = snap.viewport_width.clone();
        let bounds_for_fade = snap.item_bounds.clone();
        let fade_bg = colors.surface_muted;

        let edge_fade_overlay = canvas(
            move |vp_rect, _, _| {
                *vw_ref.borrow_mut() = f32::from(vp_rect.size.width);
                let map = bounds_for_fade.borrow();
                if let (Some(min_x), Some(max_x)) = (
                    map.values().map(|r| f32::from(r.origin.x)).reduce(f32::min),
                    map.values()
                        .map(|r| f32::from(r.origin.x + r.size.width))
                        .reduce(f32::max),
                ) {
                    *cw_ref.borrow_mut() = (max_x - min_x).max(0.0);
                }
            },
            move |vp_rect, _, window, _| {
                let cw = *snap.content_width.borrow();
                let vw = f32::from(vp_rect.size.width);
                let max_scroll = (cw - vw).max(0.0);
                let fade_start = scroll_x > 1.0;
                let fade_end = max_scroll - scroll_x > 1.0;
                if fade_start {
                    EdgeFadeMask::new(EdgeFadeSide::Left, px(20.0), fade_bg).paint(vp_rect, window);
                }
                if fade_end {
                    EdgeFadeMask::new(EdgeFadeSide::Right, px(20.0), fade_bg)
                        .paint(vp_rect, window);
                }
            },
        )
        .absolute()
        .inset_0();

        let int_wheel = internal.clone();
        let frame = div()
            .relative()
            .overflow_hidden()
            .p(px(3.0))
            .rounded(Radii::CONTROL)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface_muted)
            .on_scroll(move |ev: &ScrollEvent, window, cx| {
                let delta = ev.delta.pixel_delta(px(20.0));
                let dx = if f32::from(delta.x).abs() > 0.1 {
                    -f32::from(delta.x)
                } else {
                    -f32::from(delta.y)
                };
                int_wheel.update(cx, |s, _| {
                    let cw = *s.content_width.borrow();
                    let vw = *s.viewport_width.borrow();
                    let max_scroll = (cw - vw).max(0.0);
                    if max_scroll > 1.0 {
                        s.scroll_offset = (s.scroll_offset + dx).clamp(0.0, max_scroll);
                    }
                });
                window.refresh();
            })
            .child(track)
            .child(edge_fade_overlay);

        div()
            .id(self.id)
            .flex()
            .flex_col()
            .items_start()
            .gap(Spacing::S2)
            .when_some(self.label, |this, lbl| {
                this.child(
                    div()
                        .text_size(Typography::TEXT_XS)
                        .text_color(colors.text_muted)
                        .child(lbl),
                )
            })
            .child(frame)
    }
}

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

    use super::*;

    struct SegmentedHost {
        selected: SharedString,
    }

    impl Render for SegmentedHost {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            div().w(px(420.0)).p(Spacing::S4).child(
                SegmentedControl::new("view-mode")
                    .label("View")
                    .value(self.selected.clone())
                    .options([
                        Segment::new("day", "Day"),
                        Segment::new("week", "Week").accessory("7"),
                        Segment::new("month", "Month"),
                    ])
                    .on_value_change(cx.listener(|this, v: &SharedString, _, cx| {
                        this.selected = v.clone();
                        cx.notify();
                    })),
            )
        }
    }

    #[gpui_kit::test]
    fn segmented_control_switches_selection_on_click(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(|_, _| SegmentedHost {
            selected: "day".into(),
        });

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

        assert_eq!(view.read_with(cx, |v, _| v.selected.clone()), "week");
    }
}