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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! `BarChart`: single-measure comparison chart across days/weeks/months with clean gridlines,
//! animated bar heights, dashed average reference line, pointer/keyboard scrubbing, and headline readout.

use std::cell::RefCell;
use std::rc::Rc;

use arc_motion::{arc_spring_with_options, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
    App, Bounds, Corners, ElementId, FocusHandle, IntoElement, KeyDownEvent, MouseButton,
    MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
    Window, base::StyledExt as _, canvas, div, fill, point, prelude::*, px, size,
};

use super::common::{build_dashed_polyline, format_grouped, nice_scale_positive};

pub const BAR_CHART_TOP_PAD: f32 = 12.0;
pub const BAR_CHART_FILL_RATIO: f32 = 0.58;
pub const BAR_CHART_MAX_BAR_W: f32 = 28.0;
pub const BAR_CHART_RADIUS: f32 = 4.0;

#[derive(Clone, Debug, PartialEq)]
pub struct BarChartDatum {
    pub key: SharedString,
    pub label: SharedString,
    pub axis_label: Option<SharedString>,
    pub value: f64,
}

impl BarChartDatum {
    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>, value: f64) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            axis_label: None,
            value,
        }
    }

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

/// Compute average and peak values for a bar chart dataset.
pub fn bar_chart_stats(data: &[BarChartDatum]) -> (f64, f64) {
    if data.is_empty() {
        return (0.0, 0.0);
    }
    let sum: f64 = data.iter().map(|d| d.value.max(0.0)).sum();
    let peak = data.iter().map(|d| d.value.max(0.0)).fold(0.0f64, f64::max);
    (sum / data.len() as f64, peak)
}

/// Select axis label indices spaced cleanly from right to left so the newest bar is always labeled.
pub fn bar_chart_visible_axis_indices(data: &[BarChartDatum], plot_width: f32) -> Vec<usize> {
    if data.is_empty() || plot_width <= 20.0 {
        return Vec::new();
    }
    let labeled: Vec<usize> = data
        .iter()
        .enumerate()
        .filter_map(|(i, d)| d.axis_label.as_ref().map(|_| i))
        .collect();
    if labeled.is_empty() {
        return Vec::new();
    }
    let max_labels = (plot_width / 46.0).floor().max(2.0) as usize;
    let stride = labeled.len().div_ceil(max_labels).max(1);
    let mut picked: Vec<usize> = labeled
        .into_iter()
        .rev()
        .enumerate()
        .filter_map(|(rank, idx)| if rank % stride == 0 { Some(idx) } else { None })
        .collect();
    picked.reverse();
    picked
}

/// Map pointer x inside `[left, left + width]` to a bar index.
pub fn bar_chart_index_at(x: f32, left: f32, width: f32, count: usize) -> usize {
    if count <= 1 || width <= 1e-4 {
        return 0;
    }
    let frac = ((x - left) / width).clamp(0.0, 0.9999);
    (frac * count as f32).floor() as usize
}

struct BarChartState {
    active: Option<usize>,
    plot_bounds: Option<Bounds<Pixels>>,
    focus: FocusHandle,
}

#[derive(IntoElement)]
pub struct BarChart {
    id: ElementId,
    data: Vec<BarChartDatum>,
    label: SharedString,
    period: SharedString,
    unit: SharedString,
    average_label: SharedString,
    value_label: SharedString,
    show_average: bool,
    height: f32,
}

impl BarChart {
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        period: impl Into<SharedString>,
        data: Vec<BarChartDatum>,
    ) -> Self {
        Self {
            id: id.into(),
            data,
            label: label.into(),
            period: period.into(),
            unit: SharedString::default(),
            average_label: SharedString::from("Daily average"),
            value_label: SharedString::from("Total"),
            show_average: true,
            height: 176.0,
        }
    }

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

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

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

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

    pub fn height(mut self, px_val: f32) -> Self {
        self.height = px_val.clamp(100.0, 360.0);
        self
    }
}

impl RenderOnce for BarChart {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let count = self.data.len();
        let last = count.saturating_sub(1);
        let (average, peak) = bar_chart_stats(&self.data);
        let scale = nice_scale_positive(peak);

        let state = window.use_keyed_state(
            SharedString::from(format!("arc-barchart-state-{:?}", self.id)),
            cx,
            |_w, cx| {
                Rc::new(RefCell::new(BarChartState {
                    active: None,
                    plot_bounds: None,
                    focus: cx.focus_handle(),
                }))
            },
        );
        let st_rc = state.read(cx).clone();
        let (active_idx, focus_handle, plot_w) = {
            let st = st_rc.borrow();
            let idx = st.active.filter(|_| count > 0).map(|i| i.min(last));
            let w: f32 = st.plot_bounds.map(|b| b.size.width.into()).unwrap_or(480.0);
            (idx, st.focus.clone(), w)
        };

        // Spring-animated scale top & average line
        let anim_top = arc_spring_with_options(
            SharedString::from(format!("arc-barchart-top-{:?}", self.id)),
            scale.max as f32,
            SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
            window,
            cx,
        )
        .value
        .max(1.0);

        let anim_avg = arc_spring_with_options(
            SharedString::from(format!("arc-barchart-avg-{:?}", self.id)),
            average as f32,
            SpringOptions::new(SpringSpec::visual(0.4, 0.0)),
            window,
            cx,
        )
        .value
        .max(0.0);

        // Animate each bar's value keyed by its stable datum key
        let mut anim_values = Vec::with_capacity(count);
        for d in &self.data {
            let v = arc_spring_with_options(
                SharedString::from(format!("arc-barchart-bar-{:?}-{}", self.id, d.key)),
                d.value.max(0.0) as f32,
                SpringOptions::new(SpringSpec::visual(0.38, 0.0)),
                window,
                cx,
            )
            .value
            .max(0.0);
            anim_values.push(v);
        }

        let scrubbing = active_idx.is_some();
        let cursor_target = active_idx.map(|i| i as f32).unwrap_or(0.0);
        let cursor_slot = arc_spring_with_options(
            SharedString::from(format!("arc-barchart-cursor-{:?}", self.id)),
            cursor_target,
            SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
            window,
            cx,
        )
        .value;

        let shown_val = active_idx
            .and_then(|i| self.data.get(i))
            .map(|d| d.value)
            .unwrap_or(average);
        let heading_sub = if scrubbing {
            self.value_label.clone()
        } else {
            self.average_label.clone()
        };
        let period_text = active_idx
            .and_then(|i| self.data.get(i))
            .map(|d| d.label.clone())
            .unwrap_or_else(|| self.period.clone());
        let unit_suffix = if self.unit.is_empty() {
            String::new()
        } else {
            format!(" {}", self.unit)
        };
        let headline_num = format!("{}{}", format_grouped(shown_val.round(), 0), unit_suffix);

        let bar_color = colors.accent;
        let bar_dim_color = oklab_mix(colors.accent, colors.surface, 0.45);
        let grid_color = colors.border_subtle;
        let avg_color = colors.text_muted;
        let cursor_color = colors.border_strong;
        let ticks = scale.ticks.clone();
        let show_avg = self.show_average;
        let plot_height = self.height;

        let st_paint = st_rc.clone();
        let st_down = st_rc.clone();
        let st_move = st_rc.clone();
        let st_leave = st_rc.clone();
        let st_key = st_rc.clone();

        let plot_canvas = canvas(
            move |bounds, _w, _cx| {
                st_paint.borrow_mut().plot_bounds = Some(bounds);
                bounds
            },
            move |bounds, _, window, _cx| {
                let left: f32 = bounds.origin.x.into();
                let top: f32 = bounds.origin.y.into();
                let w: f32 = bounds.size.width.into();
                let h: f32 = bounds.size.height.into();
                if w <= 2.0 || h <= 2.0 {
                    return;
                }
                let usable_h = (h - BAR_CHART_TOP_PAD).max(8.0);
                let to_y = |v: f32| -> f32 { top + h - (v / anim_top) * usable_h };

                // Horizontal gridlines
                for &t in &ticks {
                    let y = to_y(t as f32).round();
                    window.paint_quad(fill(
                        Bounds::new(point(px(left), px(y)), size(px(w), px(1.0))),
                        grid_color,
                    ));
                }

                // Scrubbing cursor guide behind bars
                if scrubbing && count > 0 {
                    let slot_w = w / count as f32;
                    let cx_px = left + (cursor_slot + 0.5) * slot_w;
                    window.paint_quad(fill(
                        Bounds::new(point(px(cx_px - 0.5), px(top)), size(px(1.0), px(h))),
                        cursor_color,
                    ));
                }

                // Bars with rounded top corners
                if count > 0 {
                    let slot_w = w / count as f32;
                    let bar_w = (slot_w * BAR_CHART_FILL_RATIO).clamp(3.0, BAR_CHART_MAX_BAR_W);
                    for (i, &val) in anim_values.iter().enumerate() {
                        let bar_h = ((val / anim_top) * usable_h).clamp(0.0, usable_h);
                        if bar_h <= 0.5 {
                            continue;
                        }
                        let center = left + (i as f32 + 0.5) * slot_w;
                        let x = center - bar_w * 0.5;
                        let y = top + h - bar_h;
                        let r = BAR_CHART_RADIUS.min(bar_w * 0.5).min(bar_h);
                        let is_active = active_idx == Some(i);
                        let col = if scrubbing && !is_active {
                            bar_dim_color
                        } else {
                            bar_color
                        };
                        window.paint_quad(
                            fill(
                                Bounds::new(point(px(x), px(y)), size(px(bar_w), px(bar_h))),
                                col,
                            )
                            .corner_radii(Corners {
                                top_left: px(r),
                                top_right: px(r),
                                bottom_right: px(0.0),
                                bottom_left: px(0.0),
                            }),
                        );
                    }
                }

                // Dashed average reference line
                if show_avg && anim_avg > 0.0 {
                    let ay_min = top + 2.0;
                    let ay_max = (top + h - 1.0).max(ay_min);
                    let ay = to_y(anim_avg).clamp(ay_min, ay_max);
                    let dashes = build_dashed_polyline(
                        &[point(px(left), px(ay)), point(px(left + w), px(ay))],
                        1.25,
                        4.0,
                        4.0,
                    );
                    for dash in dashes {
                        window.paint_path(dash, avg_color);
                    }
                }
            },
        )
        .w_full()
        .h(px(plot_height));

        let visible_axis = bar_chart_visible_axis_indices(&self.data, plot_w);

        // Y-axis tick labels column on right
        let mut y_axis = div().w(px(44.0)).h(px(plot_height)).flex_none().relative();
        let usable_h = (plot_height - BAR_CHART_TOP_PAD).max(8.0);
        for &t in &scale.ticks {
            let y = (plot_height - (t as f32 / anim_top) * usable_h - 7.0)
                .clamp(0.0, (plot_height - 14.0).max(0.0));
            y_axis = y_axis.child(
                div()
                    .absolute()
                    .top(px(y))
                    .right_0()
                    .text_size(Typography::TEXT_XS)
                    .text_color(colors.text_muted)
                    .child(format_grouped(t, 0)),
            );
        }

        // X-axis label row
        let mut x_axis = div().w_full().h(px(20.0)).relative();
        if count > 0 {
            let slot_w = plot_w / count as f32;
            for idx in visible_axis {
                if let Some(ref text) = self.data[idx].axis_label {
                    let left_px =
                        ((idx as f32 + 0.5) * slot_w - 22.0).clamp(0.0, (plot_w - 44.0).max(0.0));
                    x_axis = x_axis.child(
                        div()
                            .absolute()
                            .left(px(left_px))
                            .top(px(2.0))
                            .w(px(44.0))
                            .flex()
                            .justify_center()
                            .text_size(Typography::TEXT_XS)
                            .text_color(if active_idx == Some(idx) {
                                colors.foreground
                            } else {
                                colors.text_muted
                            })
                            .child(text.clone()),
                    );
                }
            }
        }

        div()
            .id(self.id)
            .w_full()
            .p(Spacing::S5)
            .rounded(Radii::PANEL)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface)
            .flex()
            .flex_col()
            .gap(Spacing::S3)
            .child(
                // Headline readout
                div()
                    .flex()
                    .items_baseline()
                    .justify_between()
                    .gap(Spacing::S2)
                    .child(
                        div()
                            .flex()
                            .flex_col()
                            .gap(px(2.0))
                            .child(
                                div()
                                    .text_size(Typography::TEXT_XS)
                                    .font_medium()
                                    .text_color(colors.text_muted)
                                    .child(heading_sub),
                            )
                            .child(
                                div()
                                    .text_size(Typography::TEXT_2XL)
                                    .font_semibold()
                                    .text_color(colors.foreground)
                                    .child(headline_num),
                            ),
                    )
                    .child(
                        div()
                            .flex()
                            .flex_col()
                            .items_end()
                            .gap(px(2.0))
                            .child(
                                div()
                                    .text_size(Typography::TEXT_XS)
                                    .font_medium()
                                    .text_color(colors.text_secondary)
                                    .child(self.label),
                            )
                            .child(
                                div()
                                    .text_size(Typography::TEXT_XS)
                                    .text_color(colors.text_muted)
                                    .child(period_text),
                            ),
                    ),
            )
            .child(
                div()
                    .w_full()
                    .flex()
                    .items_start()
                    .gap(Spacing::S2)
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .flex()
                            .flex_col()
                            .child(
                                div()
                                    .id(SharedString::from(format!("arc-barchart-plot-{}", count)))
                                    .w_full()
                                    .h(px(plot_height))
                                    .track_focus(&focus_handle)
                                    .role(Role::Slider)
                                    .cursor_pointer()
                                    .on_mouse_down(
                                        MouseButton::Left,
                                        move |ev: &MouseDownEvent, window, _cx| {
                                            if count == 0 {
                                                return;
                                            }
                                            let bounds = st_down.borrow().plot_bounds;
                                            if let Some(b) = bounds {
                                                let x: f32 = ev.position.x.into();
                                                let left: f32 = b.origin.x.into();
                                                let w: f32 = b.size.width.into();
                                                st_down.borrow_mut().active =
                                                    Some(bar_chart_index_at(x, left, w, count));
                                                window.refresh();
                                            }
                                        },
                                    )
                                    .on_mouse_move(move |ev: &MouseMoveEvent, window, _cx| {
                                        if count == 0 {
                                            return;
                                        }
                                        let bounds = st_move.borrow().plot_bounds;
                                        if let Some(b) = bounds {
                                            let x: f32 = ev.position.x.into();
                                            let y: f32 = ev.position.y.into();
                                            let left: f32 = b.origin.x.into();
                                            let top: f32 = b.origin.y.into();
                                            let w: f32 = b.size.width.into();
                                            let h: f32 = b.size.height.into();
                                            let inside = x >= left
                                                && x <= left + w
                                                && y >= top
                                                && y <= top + h;
                                            let next = if inside {
                                                Some(bar_chart_index_at(x, left, w, count))
                                            } else {
                                                None
                                            };
                                            let mut st = st_move.borrow_mut();
                                            if st.active != next {
                                                st.active = next;
                                                window.refresh();
                                            }
                                        }
                                    })
                                    .on_hover(move |hovered, window, _cx| {
                                        if !*hovered {
                                            let mut st = st_leave.borrow_mut();
                                            if st.active.is_some() {
                                                st.active = None;
                                                window.refresh();
                                            }
                                        }
                                    })
                                    .on_key_down(move |ev: &KeyDownEvent, window, _cx| {
                                        if count == 0 {
                                            return;
                                        }
                                        let mut st = st_key.borrow_mut();
                                        let cur = st.active.unwrap_or(last);
                                        let next = match ev.keystroke.key.as_str() {
                                            "escape" => {
                                                st.active = None;
                                                window.refresh();
                                                return;
                                            }
                                            "left" | "down" => cur.saturating_sub(1),
                                            "right" | "up" => (cur + 1).min(last),
                                            "home" => 0,
                                            "end" => last,
                                            _ => return,
                                        };
                                        st.active = Some(next);
                                        window.refresh();
                                    })
                                    .child(plot_canvas),
                            )
                            .child(x_axis),
                    )
                    .child(y_axis),
            )
    }
}

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

    #[test]
    fn bar_chart_stats_axis_thinning_and_pointer_hit() {
        let data = vec![
            BarChartDatum::new("d1", "Mon", 30.0).axis_label("M"),
            BarChartDatum::new("d2", "Tue", 60.0).axis_label("T"),
            BarChartDatum::new("d3", "Wed", 45.0).axis_label("W"),
            BarChartDatum::new("d4", "Thu", 85.0).axis_label("T"),
        ];
        let (avg, peak) = bar_chart_stats(&data);
        assert!((avg - 55.0).abs() < 1e-6);
        assert!((peak - 85.0).abs() < 1e-6);

        let picks = bar_chart_visible_axis_indices(&data, 320.0);
        assert_eq!(picks, vec![0, 1, 2, 3]);
        let tight = bar_chart_visible_axis_indices(&data, 96.0);
        assert_eq!(*tight.last().unwrap(), 3);

        assert_eq!(bar_chart_index_at(10.0, 0.0, 100.0, 4), 0);
        assert_eq!(bar_chart_index_at(55.0, 0.0, 100.0, 4), 2);
        assert_eq!(bar_chart_index_at(99.0, 0.0, 100.0, 4), 3);
    }
}