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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/badge/badge.tsx` & `.module.css`
//!
//! P2 Component #21: `badge`
//!
//! - One Oklab formula tints every semantic tone and categorical color from `--tone-*`:
//!   - Background: `10%` (light) / `12%` (dark) mixed into `surface`.
//!   - Foreground: `84%` (light; `76%` for warning/amber) / `94%` (dark) toward `foreground`.
//!   - Mark (icon / dot): `88%` tone toward `foreground`.
//!   - Outline border: `14%` (light) / `22%` (dark) mixed into `border`.
//! - Morphing label transitions: when the badge text changes, width springs (`spring.morph`) and
//!   text enters with `BlurFallback::soft`.

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

use arc_motion::{BlurFallback, arc_spring, arc_transition, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Radii, Typography, oklab_mix};
use gpui_kit::{
    App, ElementId, Hsla, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
    TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, component::Icon,
    div, prelude::*, px,
};

/// Semantic status tone for [`Badge`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum BadgeTone {
    #[default]
    Neutral,
    Info,
    Success,
    Warning,
    Danger,
}

/// Categorical palette color override for [`Badge`] (HTTP methods, tags, etc.).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BadgeColor {
    Teal,
    Sky,
    Orchid,
    Violet,
    Rose,
    Amber,
}

/// Four-point-grid size presets for [`Badge`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum BadgeSize {
    Sm,
    #[default]
    Md,
    Lg,
}

#[derive(Clone)]
struct BadgeInternal {
    last_label: SharedString,
    generation: u64,
    measured_width: Rc<RefCell<Option<f32>>>,
}

/// Arc `Badge` — status pill / categorical tag with Oklab tint formula and spring width morphing.
#[derive(IntoElement)]
pub struct Badge {
    id: ElementId,
    label: SharedString,
    tone: BadgeTone,
    color: Option<BadgeColor>,
    size: BadgeSize,
    icon: Option<IconName>,
    dot: bool,
    outline: bool,
    pill: bool,
}

impl Badge {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            tone: BadgeTone::Neutral,
            color: None,
            size: BadgeSize::Md,
            icon: None,
            dot: false,
            outline: false,
            pill: false,
        }
    }

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

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

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

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

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

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

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

impl RenderOnce for Badge {
    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 state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-badge-state".into());
        let initial_label = self.label.clone();
        let internal = window.use_keyed_state(state_id, cx, |_, _| BadgeInternal {
            last_label: initial_label,
            generation: 0,
            measured_width: Rc::new(RefCell::new(None)),
        });

        let changed = internal.read(cx).last_label != self.label;
        if changed {
            internal.update(cx, |s, _| {
                s.last_label = self.label.clone();
                s.generation = s.generation.wrapping_add(1);
            });
        }
        let snap = internal.read(cx).clone();

        let base_tone = match self.color {
            Some(BadgeColor::Teal) => colors.tone_teal,
            Some(BadgeColor::Sky) => colors.tone_sky,
            Some(BadgeColor::Orchid) => colors.tone_orchid,
            Some(BadgeColor::Violet) => colors.tone_violet,
            Some(BadgeColor::Rose) => colors.tone_rose,
            Some(BadgeColor::Amber) => colors.tone_amber,
            None => match self.tone {
                BadgeTone::Neutral => colors.text_secondary,
                BadgeTone::Info => colors.info,
                BadgeTone::Success => colors.success,
                BadgeTone::Warning => colors.warning,
                BadgeTone::Danger => colors.danger,
            },
        };

        let is_amber_like = matches!(self.color, Some(BadgeColor::Amber))
            || (self.color.is_none() && self.tone == BadgeTone::Warning);
        let tint_weight = if is_dark { 0.12 } else { 0.10 };
        let ink_weight = if is_dark {
            0.94
        } else if is_amber_like {
            0.76
        } else {
            0.84
        };

        let bg = oklab_mix(base_tone, colors.surface, tint_weight);
        let fg = oklab_mix(base_tone, colors.foreground, ink_weight);
        let mark_color = oklab_mix(base_tone, colors.foreground, 0.88);
        let border_color = if self.outline {
            oklab_mix(base_tone, colors.border, if is_dark { 0.22 } else { 0.14 })
        } else {
            Hsla::transparent_black()
        };

        let (height, default_radius, pad, gap, icon_sz, dot_sz, font_sz) = match self.size {
            BadgeSize::Sm => (20.0, 5.0, 8.0, 4.0, 12.0, 5.0, px(11.0)),
            BadgeSize::Md => (24.0, 6.0, 10.0, 5.0, 14.0, 6.0, Typography::TEXT_XS),
            BadgeSize::Lg => (28.0, 7.0, 12.0, 6.0, 16.0, 7.0, Typography::TEXT_SM),
        };
        let radius = if self.pill {
            Radii::PILL
        } else {
            px(default_radius)
        };
        let pl = if self.icon.is_some() {
            pad - 2.0
        } else if self.dot {
            pad - 1.0
        } else {
            pad
        };

        let enter_p = if snap.generation == 0 || reduced {
            1.0
        } else {
            arc_transition(
                (self.id.clone(), format!("enter-{}", snap.generation)),
                1.0,
                motion.duration.standard,
                motion.ease.enter,
                window,
                cx,
            )
        };
        let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - enter_p), reduced);

        let measured_w = *snap.measured_width.borrow();
        let animated_w = if let Some(target_w) = measured_w {
            if reduced || snap.generation == 0 {
                None
            } else {
                let cur_w = arc_spring(
                    (self.id.clone(), "badge-width"),
                    target_w,
                    motion.spring.morph,
                    window,
                    cx,
                );
                if (cur_w - target_w).abs() > 0.4 {
                    Some(cur_w)
                } else {
                    None
                }
            }
        } else {
            None
        };

        // Natural content width is measured on a hidden, out-of-flow copy of the content so the
        // animated width never feeds back into its own target (which used to shrink the badge to a
        // circle and clip the label).
        let width_ref = snap.measured_width.clone();
        let measure_canvas = {
            let width_ref = width_ref.clone();
            canvas(
                move |rect, _, _| {
                    let w = f32::from(rect.size.width);
                    if w > 1.0 {
                        *width_ref.borrow_mut() = Some(w);
                    }
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0()
        };

        let content_row = |enter: f32| {
            let mut row = div()
                .flex()
                .flex_row()
                .flex_none()
                .items_center()
                .gap(px(gap));
            if self.icon.is_none() && self.dot {
                row = row.child(
                    div()
                        .w(px(dot_sz))
                        .h(px(dot_sz))
                        .rounded(Radii::PILL)
                        .bg(mark_color)
                        .flex_none(),
                );
            }
            if let Some(icon) = self.icon {
                row = row.child(
                    Icon::new(icon)
                        .text_size(px(icon_sz))
                        .text_color(mark_color),
                );
            }
            row.child(
                div()
                    .whitespace_nowrap()
                    .opacity((enter * blur.opacity_multiplier).clamp(0.0, 1.0))
                    .child(self.label.clone()),
            )
        };

        // Sizer mirrors the badge's padding and 1px border so its outer width is the badge's
        // target border-box width.
        let sizer = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                "sizer".into(),
            ))
            .test_support()
            .absolute()
            .left(px(0.0))
            .top(px(0.0))
            .opacity(0.0)
            .border_1()
            .border_color(Hsla::transparent_black())
            .pl(px(pl))
            .pr(px(pad))
            .py(px(0.0))
            .text_size(font_sz)
            .font_medium()
            .child(measure_canvas)
            .child(content_row(1.0));

        div()
            .id(self.id)
            .test_support()
            .relative()
            .min_h(px(height))
            .when_some(animated_w, |this, w| this.w(px(w.max(height))))
            .pl(px(pl))
            .pr(px(pad))
            .rounded(radius)
            .border_1()
            .border_color(border_color)
            .bg(bg)
            .overflow_hidden()
            .flex()
            .flex_row()
            .items_center()
            .gap(px(gap))
            .text_size(font_sz)
            .font_medium()
            .text_color(fg)
            .child(sizer)
            .child(content_row(enter_p))
    }
}

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

    use super::*;

    struct BadgeHost {
        label: SharedString,
        tone: BadgeTone,
    }

    impl Render for BadgeHost {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(px(360.0))
                .p(Spacing::S4)
                .flex()
                .gap(Spacing::S2)
                .child(
                    Badge::new("status-badge", self.label.clone())
                        .tone(self.tone)
                        .dot(true)
                        .outline(true),
                )
                .child(
                    Badge::new("method-badge", "POST")
                        .color(BadgeColor::Violet)
                        .size(BadgeSize::Sm)
                        .pill(true),
                )
        }
    }

    #[gpui_kit::test]
    fn badge_grows_to_fit_a_longer_label_without_clipping(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(|_, _| BadgeHost {
            label: "已部署".into(),
            tone: BadgeTone::Success,
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
        });
        view.update(cx, |host, cx| {
            host.label = "构建中 · 82%".into();
            cx.notify();
        });
        // The spring starts on the next frame after the label change; the headless clock is
        // deterministic, so advance it instead of sleeping.
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
        });
        for _ in 0..4 {
            cx.executor()
                .advance_clock(std::time::Duration::from_millis(200));
            cx.update(|window, cx| {
                window.render_frame(cx);
                window.render_frame(cx);
            });
        }
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
            let root: std::sync::Arc<ElementId> = ElementId::from("status-badge").into();
            let sizer = window.find(ElementId::NamedChild(root.clone(), "sizer".into()));
            let badge = window.find(ElementId::from("status-badge"));
            let sizer_w = f32::from(sizer.bounds().size.width);
            let badge_w = f32::from(badge.bounds().size.width);
            assert!(sizer_w > 0.0, "sizer must report the natural label width");
            assert!(
                badge_w + 1.0 >= sizer_w,
                "badge {badge_w} must grow to the natural content width {sizer_w}"
            );
        });
    }

    #[gpui_kit::test]
    fn badge_renders_tones_colors_and_label_morph_without_panicking(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(|_, _| BadgeHost {
            label: "Queued".into(),
            tone: BadgeTone::Warning,
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            view.update(cx, |v, cx| {
                v.label = "Deployed".into();
                v.tone = BadgeTone::Success;
                cx.notify();
            });
            window.render_frame(cx);
        });
    }
}