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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/metric-card/metric-card.tsx` & `.module.css`
//!
//! P6 Component #2: `metric-card`
//!
//! - Surface KPI card (`Radii::SURFACE`, `Spacing::S6` padding, `Shadows::resting`) showing a
//!   top row (`label` + optional signed `change` trend pill), a large `AnimatedCounter` readout,
//!   and a `context` caption below.
//! - Trend pill detects leading `+` (`MetricTrend::Up`, `11%` success tint + success text) and
//!   leading `-` / `−` (`MetricTrend::Down`, `11%` danger tint + danger text); neutral change
//!   strings use a `1px` border and `text_secondary`.
//! - When `label`, `change`, or `context` updates, directional text swap rises from below when
//!   the embedded number increases (`direction = +1`) and drops from above when it decreases
//!   (`direction = -1`), while the trend pill smoothly springs its width via `motion.spring.morph`.

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

use arc_motion::{
    BlurFallback, CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now,
    spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, ElementId, Hsla, IntoElement, ParentElement, RenderOnce, Role, SharedString,
    Styled, Window, div, prelude::*, px,
};

use crate::text::animated_counter::AnimatedCounter;

/// Trend direction inferred from the leading sign of `change`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricTrend {
    Up,
    Down,
    Neutral,
}

/// Infers `MetricTrend` from a change string (`"+14.2%"` -> `Up`, `"-3.1%"` / `"−3.1%"` -> `Down`).
pub fn metric_card_trend(change: &str) -> MetricTrend {
    let trimmed = change.trim();
    if trimmed.starts_with('+') {
        MetricTrend::Up
    } else if trimmed.starts_with('-') || trimmed.starts_with('−') {
        MetricTrend::Down
    } else {
        MetricTrend::Neutral
    }
}

/// Extracts the first signed decimal number from a string (matching `amountIn` in `metric-card.tsx`).
pub fn metric_card_extract_number(text: &str) -> Option<f64> {
    let cleaned = text.replace(',', "").replace('−', "-");
    let bytes = cleaned.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let ch = bytes[i] as char;
        let is_sign = (ch == '-' || ch == '+')
            && i + 1 < bytes.len()
            && (bytes[i + 1] as char).is_ascii_digit();
        if is_sign || ch.is_ascii_digit() {
            let start = i;
            if ch == '-' || ch == '+' {
                i += 1;
            }
            let mut seen_dot = false;
            while i < bytes.len() {
                let c = bytes[i] as char;
                if c.is_ascii_digit() {
                    i += 1;
                } else if c == '.' && !seen_dot {
                    seen_dot = true;
                    i += 1;
                } else {
                    break;
                }
            }
            if let Ok(v) = cleaned[start..i].parse::<f64>() {
                return Some(v);
            }
        }
        i += 1;
    }
    None
}

/// Computes swap direction (`+1` rising from below, `-1` dropping from above).
pub fn metric_card_swap_direction(prev: &str, next: &str) -> i8 {
    match (
        metric_card_extract_number(prev),
        metric_card_extract_number(next),
    ) {
        (Some(a), Some(b)) if b < a => -1,
        _ => 1,
    }
}

/// Samples `(old_alpha, old_y_px, new_alpha, new_y_px)` for a directional metric text swap.
pub fn metric_card_swap_sample(
    elapsed_secs: f64,
    direction: i8,
    reduced: bool,
) -> (f32, f32, f32, f32) {
    let dir = direction as f32;
    if reduced {
        let t = (elapsed_secs / 0.12).clamp(0.0, 1.0) as f32;
        return ((1.0 - t).clamp(0.0, 1.0), 0.0, t, 0.0);
    }
    let out_t = (elapsed_secs / 0.16).clamp(0.0, 1.0) as f32;
    let out_eased = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(out_t);
    let out_blur = BlurFallback::evaluate(px(out_eased * 2.0), false);
    let old_alpha = ((1.0 - out_eased) * out_blur.opacity_multiplier).clamp(0.0, 1.0);
    let old_y = -4.2 * dir * out_eased;

    let in_t = (elapsed_secs / 0.24).clamp(0.0, 1.0) as f32;
    let in_eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(in_t);
    let in_blur = BlurFallback::evaluate(px((1.0 - in_eased) * 4.0), false);
    let new_alpha = (in_eased * in_blur.opacity_multiplier).clamp(0.0, 1.0);
    let new_y = 4.2 * dir * (1.0 - in_eased);
    (old_alpha, old_y, new_alpha, new_y)
}

#[derive(Clone)]
struct SwapTrack {
    current: SharedString,
    previous: Option<SharedString>,
    direction: i8,
    changed_at: f64,
}

impl SwapTrack {
    fn new(initial: SharedString, now: f64) -> Self {
        Self {
            current: initial,
            previous: None,
            direction: 1,
            changed_at: now - 1.0,
        }
    }

    fn sync(&mut self, next: &SharedString, now: f64) -> bool {
        if &self.current != next {
            self.direction = metric_card_swap_direction(self.current.as_ref(), next.as_ref());
            self.previous = Some(self.current.clone());
            self.current = next.clone();
            self.changed_at = now;
        }
        let elapsed = (now - self.changed_at).max(0.0);
        if self.previous.is_some() && elapsed >= 0.28 {
            self.previous = None;
        }
        self.previous.is_some()
    }
}

#[derive(Clone)]
struct MetricCardInternal {
    label: SwapTrack,
    change: SwapTrack,
    context: SwapTrack,
    measured_pill_w: Rc<RefCell<f32>>,
}

/// KPI metric card pairing `AnimatedCounter` with directional text swap & trend badge (`metric-card`).
#[derive(IntoElement)]
pub struct MetricCard {
    id: ElementId,
    label: SharedString,
    value: f64,
    decimals: usize,
    prefix: Option<SharedString>,
    suffix: Option<SharedString>,
    context: SharedString,
    change: Option<SharedString>,
}

impl MetricCard {
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        value: f64,
        context: impl Into<SharedString>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value,
            decimals: 0,
            prefix: None,
            suffix: None,
            context: context.into(),
            change: None,
        }
    }

    pub fn decimals(mut self, decimals: usize) -> Self {
        self.decimals = decimals.min(6);
        self
    }

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

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

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

fn render_swapped_text(
    track: &SwapTrack,
    now: f64,
    color: Hsla,
    reduced: bool,
    nowrap: bool,
) -> AnyElement {
    let elapsed = (now - track.changed_at).max(0.0);
    let (old_alpha, old_y, new_alpha, new_y) = if track.previous.is_some() {
        metric_card_swap_sample(elapsed, track.direction, reduced)
    } else {
        (0.0, 0.0, 1.0, 0.0)
    };

    let outgoing = track.previous.as_ref().and_then(|prev| {
        if old_alpha <= 0.01 {
            None
        } else {
            let mut el = div()
                .absolute()
                .left_0()
                .top(px(old_y))
                .opacity(old_alpha)
                .text_size(Typography::TEXT_SM)
                .text_color(color)
                .child(prev.clone());
            if nowrap {
                el = el.whitespace_nowrap();
            }
            Some(el)
        }
    });

    let mut incoming = div()
        .relative()
        .top(px(new_y))
        .opacity(new_alpha)
        .text_size(Typography::TEXT_SM)
        .text_color(color)
        .child(track.current.clone());
    if nowrap {
        incoming = incoming.whitespace_nowrap();
    }

    div()
        .relative()
        .min_w(px(0.0))
        .when_some(outgoing, |el, out| el.child(out))
        .child(incoming)
        .into_any_element()
}

fn estimate_pill_width(text: &str) -> f32 {
    let text_w: f32 = text
        .chars()
        .map(|c| if c.is_ascii() { 7.8 } else { 13.5 })
        .sum();
    (text_w + 18.0).max(40.0)
}

impl RenderOnce for MetricCard {
    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_change = self.change.clone().unwrap_or_default();
        let state_cell = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), SharedString::from("mc-state")),
                cx,
                |_, _| {
                    Rc::new(RefCell::new(MetricCardInternal {
                        label: SwapTrack::new(self.label.clone(), now),
                        change: SwapTrack::new(initial_change.clone(), now),
                        context: SwapTrack::new(self.context.clone(), now),
                        measured_pill_w: Rc::new(RefCell::new(estimate_pill_width(
                            initial_change.as_ref(),
                        ))),
                    }))
                },
            )
            .read(cx)
            .clone();

        let (label_track, change_track, context_track, pill_w_ref, animating) = {
            let mut st = state_cell.borrow_mut();
            let a1 = st.label.sync(&self.label, now);
            let a2 = st.change.sync(&initial_change, now);
            let a3 = st.context.sync(&self.context, now);
            (
                st.label.clone(),
                st.change.clone(),
                st.context.clone(),
                st.measured_pill_w.clone(),
                a1 || a2 || a3,
            )
        };

        if animating && !reduced {
            window.request_animation_frame();
        }

        let change_pill: Option<AnyElement> = self.change.as_ref().map(|chg| {
            let trend = metric_card_trend(chg.as_ref());
            let (pill_bg, pill_border, pill_fg) = match trend {
                MetricTrend::Up => (
                    oklab_mix(colors.success, colors.surface, 0.11),
                    gpui_kit::transparent_black(),
                    colors.success,
                ),
                MetricTrend::Down => (
                    oklab_mix(colors.danger, colors.surface, 0.11),
                    gpui_kit::transparent_black(),
                    colors.danger,
                ),
                MetricTrend::Neutral => (colors.surface, colors.border, colors.text_secondary),
            };

            let target_w = {
                let est = estimate_pill_width(chg.as_ref());
                let m = *pill_w_ref.borrow();
                if (m - est).abs() < 40.0 && m > 24.0 {
                    m
                } else {
                    est
                }
            };
            let animated_w = if reduced {
                target_w
            } else {
                arc_spring_with_options(
                    ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from("change-pill-w"),
                    ),
                    target_w,
                    SpringOptions::new(motion.spring.morph).with_initial_value(target_w),
                    window,
                    cx,
                )
                .value
                .max(36.0)
            };

            let measure_w = pill_w_ref.clone();
            div()
                .flex_shrink_0()
                .w(px(animated_w))
                .px(px(8.0))
                .py(px(3.0))
                .rounded(Radii::PILL)
                .border_1()
                .border_color(pill_border)
                .bg(pill_bg)
                .overflow_hidden()
                .flex()
                .items_center()
                .justify_center()
                .child(render_swapped_text(
                    &change_track,
                    now,
                    pill_fg,
                    reduced,
                    true,
                ))
                .on_children_prepainted(move |bounds, window, _| {
                    if let Some(b) = bounds.first() {
                        let w = f32::from(b.size.width) + 18.0;
                        let prev = *measure_w.borrow();
                        if w > 24.0 && (prev - w).abs() > 1.0 {
                            *measure_w.borrow_mut() = w;
                            window.request_animation_frame();
                        }
                    }
                })
                .into_any_element()
        });

        let mut counter = AnimatedCounter::new(
            ElementId::NamedChild(self.id.clone().into(), SharedString::from("counter")),
            self.value,
        )
        .decimals(self.decimals)
        .animate_on_view(true);

        if let Some(prefix) = self.prefix {
            counter = counter.prefix(prefix);
        }
        if let Some(suffix) = self.suffix {
            counter = counter.suffix(suffix);
        }

        div()
            .id(self.id)
            .role(Role::Region)
            .w_full()
            .min_w(px(0.0))
            .p(Spacing::S6)
            .rounded(Radii::SURFACE)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface)
            .shadow(Shadows::resting(theme.mode))
            .flex()
            .flex_col()
            .child(
                div()
                    .w_full()
                    .mb(Spacing::S6)
                    .flex()
                    .flex_row()
                    .items_center()
                    .justify_between()
                    .gap(Spacing::S3)
                    .child(div().flex_1().min_w(px(0.0)).child(render_swapped_text(
                        &label_track,
                        now,
                        colors.text_secondary,
                        reduced,
                        false,
                    )))
                    .when_some(change_pill, |el, pill| el.child(pill)),
            )
            .child(counter)
            .child(div().w_full().mt(Spacing::S4).child(render_swapped_text(
                &context_track,
                now,
                colors.text_muted,
                reduced,
                false,
            )))
            .into_any_element()
    }
}

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

    #[test]
    fn metric_card_trend_and_number_direction_detection() {
        assert_eq!(metric_card_trend("+14.2%"), MetricTrend::Up);
        assert_eq!(metric_card_trend("-3.8%"), MetricTrend::Down);
        assert_eq!(metric_card_trend("−1.2%"), MetricTrend::Down);
        assert_eq!(metric_card_trend("flat"), MetricTrend::Neutral);

        assert_eq!(metric_card_extract_number("+1,240.5 ms"), Some(1240.5));
        assert_eq!(metric_card_extract_number("−12%"), Some(-12.0));
        assert_eq!(metric_card_swap_direction("+8.2%", "+12.4%"), 1);
        assert_eq!(metric_card_swap_direction("+12.4%", "+8.2%"), -1);
    }
}