Skip to main content

arc_ui/chart/
common.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Shared chart primitives: nice scales, monotone cubic Hermite splines, polyline/area/arc
3//! path builders, compact number formatting, and unified semantic series palettes.
4
5use std::f32::consts::{FRAC_PI_2, TAU};
6
7use arc_tokens::{ArcColors, oklab_mix};
8use gpui_kit::{Hsla, Path, PathBuilder, Pixels, Point, point, px};
9
10/// Semantic tone for single-series charts (`Sparkline`, `Gauge`).
11#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
12pub enum ChartTone {
13    #[default]
14    Accent,
15    Success,
16    Warning,
17    Danger,
18}
19
20impl ChartTone {
21    pub fn color(self, colors: &ArcColors) -> Hsla {
22        match self {
23            Self::Accent => colors.accent,
24            Self::Success => colors.success,
25            Self::Warning => colors.warning,
26            Self::Danger => colors.danger,
27        }
28    }
29}
30
31/// Resolve series color from the Arc semantic `--series-1..4` tokens followed by quiet neutral steps.
32pub fn chart_series_color(colors: &ArcColors, index: usize) -> Hsla {
33    match index {
34        0 => colors.series.series_1,
35        1 => colors.series.series_2,
36        2 => colors.series.series_3,
37        3 => colors.series.series_4,
38        n => {
39            const STEPS: [f32; 3] = [0.56, 0.42, 0.32];
40            let weight = STEPS[(n - 4) % STEPS.len()];
41            oklab_mix(colors.foreground, colors.surface, weight)
42        }
43    }
44}
45
46/// Subtle neutral color for grouped "Other" segments or reference series.
47pub fn chart_other_color(colors: &ArcColors) -> Hsla {
48    oklab_mix(colors.foreground, colors.surface, 0.26)
49}
50
51/// Nice axis scale covering `[min, max]` in at most `max_rows` (default 4) evenly spaced steps.
52#[derive(Clone, Debug, PartialEq)]
53pub struct NiceScale {
54    pub min: f64,
55    pub max: f64,
56    pub ticks: Vec<f64>,
57}
58
59fn clean_float(v: f64) -> f64 {
60    if v.abs() < 1e-12 {
61        0.0
62    } else {
63        (v * 1e9).round() / 1e9
64    }
65}
66
67/// Compute clean gridlines using `{1, 2, 2.5, 5, 10}` steps covering `[min(0, low), max(high, low + 1)]`.
68pub fn nice_scale(low: f64, high: f64, max_rows: usize) -> NiceScale {
69    let rows_limit = max_rows.max(2) as f64;
70    let lo = low.min(0.0);
71    let hi = high.max(lo + 1.0);
72    let span = (hi - lo).max(1e-9);
73    let magnitude = 10f64.powf((span / rows_limit).log10().floor());
74
75    for factor in [1.0, 2.0, 2.5, 5.0, 10.0] {
76        let step = factor * magnitude;
77        let bottom = (lo / step).floor() * step;
78        let top = (hi / step).ceil() * step;
79        let rows = (top - bottom) / step;
80        if rows <= rows_limit + 1e-9 {
81            let mut ticks = Vec::new();
82            let mut v = bottom;
83            let count = rows.round() as usize;
84            for _ in 0..=count {
85                ticks.push(clean_float(v));
86                v += step;
87            }
88            return NiceScale {
89                min: clean_float(bottom),
90                max: clean_float(top),
91                ticks,
92            };
93        }
94    }
95    NiceScale {
96        min: clean_float(lo),
97        max: clean_float(hi),
98        ticks: vec![clean_float(lo), clean_float(hi)],
99    }
100}
101
102/// Compute clean positive-only gridlines for bar charts using `{1, 2, 3, 5, 10}` steps from `0`.
103pub fn nice_scale_positive(max: f64) -> NiceScale {
104    let safe = max.max(1.0);
105    let magnitude = 10f64.powf((safe / 4.0).log10().floor());
106    for factor in [1.0, 2.0, 3.0, 5.0, 10.0] {
107        let step = factor * magnitude;
108        let rows = (safe / step).ceil() as usize;
109        if rows <= 4 {
110            let ticks = (0..=rows).map(|r| clean_float(r as f64 * step)).collect();
111            return NiceScale {
112                min: 0.0,
113                max: clean_float(rows as f64 * step),
114                ticks,
115            };
116        }
117    }
118    NiceScale {
119        min: 0.0,
120        max: clean_float(safe),
121        ticks: vec![0.0, clean_float(safe)],
122    }
123}
124
125/// Format an integer or float with thousands separators (`12345.6` -> `"12,345.6"`).
126pub fn format_grouped(value: f64, max_decimals: usize) -> String {
127    if !value.is_finite() {
128        return "0".to_string();
129    }
130    let neg = value < 0.0;
131    let abs = value.abs();
132    let formatted = if max_decimals == 0 || (abs - abs.round()).abs() < 1e-6 {
133        format!("{:.0}", abs.round())
134    } else {
135        let s = format!("{:.prec$}", abs, prec = max_decimals);
136        s.trim_end_matches('0').trim_end_matches('.').to_string()
137    };
138    let (int_part, frac_part) = match formatted.split_once('.') {
139        Some((i, f)) => (i, Some(f)),
140        None => (formatted.as_str(), None),
141    };
142    let bytes = int_part.as_bytes();
143    let mut out = String::with_capacity(formatted.len() + bytes.len() / 3 + 1);
144    if neg && abs >= 0.5f64 * 10f64.powi(-(max_decimals as i32)) {
145        out.push('-');
146    }
147    for (idx, &b) in bytes.iter().enumerate() {
148        if idx > 0 && (bytes.len() - idx) % 3 == 0 {
149            out.push(',');
150        }
151        out.push(b as char);
152    }
153    if let Some(f) = frac_part
154        && !f.is_empty()
155    {
156        out.push('.');
157        out.push_str(f);
158    }
159    out
160}
161
162/// Format a number compactly for axis ticks (`1200` -> `"1.2K"`, `1_500_000` -> `"1.5M"`).
163pub fn format_compact(value: f64) -> String {
164    if !value.is_finite() {
165        return "0".to_string();
166    }
167    let abs = value.abs();
168    let (scaled, suffix) = if abs >= 1_000_000_000.0 {
169        (value / 1_000_000_000.0, "B")
170    } else if abs >= 1_000_000.0 {
171        (value / 1_000_000.0, "M")
172    } else if abs >= 1_000.0 {
173        (value / 1_000.0, "K")
174    } else {
175        return format_grouped(value, 1);
176    };
177    let s = format!("{:.1}", scaled);
178    let trimmed = s.trim_end_matches('0').trim_end_matches('.');
179    format!("{trimmed}{suffix}")
180}
181
182/// Format a share in `0.0..=1.0` as percentage (`"<1%"` for tiny non-zero shares).
183pub fn format_share(share: f64) -> String {
184    if share > 0.0 && share < 0.01 {
185        "<1%".to_string()
186    } else {
187        format!("{}%", (share.clamp(0.0, 1.0) * 100.0).round() as i64)
188    }
189}
190
191/// Sample a series of values into dense `(x_norm, y_value)` points in `x ∈ [0, 1]`.
192/// When `smooth` is true, uses Fritsch-Carlson monotone cubic Hermite interpolation so
193/// curves never overshoot past neighboring data points.
194pub fn sample_monotone_curve(values: &[f64], smooth: bool, max_samples: usize) -> Vec<(f64, f64)> {
195    if values.is_empty() {
196        return Vec::new();
197    }
198    if values.len() == 1 {
199        return vec![(0.0, values[0]), (1.0, values[0])];
200    }
201    let last = values.len() - 1;
202    let step = 1.0 / last as f64;
203    if !smooth {
204        return values
205            .iter()
206            .enumerate()
207            .map(|(i, &v)| (i as f64 * step, v))
208            .collect();
209    }
210
211    let mut slopes = Vec::with_capacity(last);
212    for i in 0..last {
213        slopes.push((values[i + 1] - values[i]) / step);
214    }
215
216    let mut tangents = vec![0.0f64; values.len()];
217    if last == 1 {
218        tangents[0] = slopes[0];
219        tangents[1] = slopes[0];
220    } else {
221        for i in 1..last {
222            let s0 = slopes[i - 1];
223            let s1 = slopes[i];
224            if s0 * s1 > 0.0 {
225                let sign = s0.signum() + s1.signum();
226                let m = s0.abs().min(s1.abs()).min((s0 + s1).abs() * 0.25);
227                tangents[i] = sign * m;
228            }
229        }
230        tangents[0] = (3.0 * slopes[0] - tangents[1]) * 0.5;
231        tangents[last] = (3.0 * slopes[last - 1] - tangents[last - 1]) * 0.5;
232    }
233
234    let per_seg = ((max_samples.max(last) as f64 / last as f64).round() as usize).clamp(1, 16);
235    let mut out = Vec::with_capacity(last * per_seg + 1);
236    for i in 0..last {
237        let low = values[i].min(values[i + 1]);
238        let high = values[i].max(values[i + 1]);
239        for s in 0..per_seg {
240            let t = s as f64 / per_seg as f64;
241            let t2 = t * t;
242            let t3 = t2 * t;
243            let y = (2.0 * t3 - 3.0 * t2 + 1.0) * values[i]
244                + (t3 - 2.0 * t2 + t) * step * tangents[i]
245                + (3.0 * t2 - 2.0 * t3) * values[i + 1]
246                + (t3 - t2) * step * tangents[i + 1];
247            out.push(((i as f64 + t) * step, y.clamp(low, high)));
248        }
249    }
250    out.push((1.0, values[last]));
251    out
252}
253
254/// Evaluate a sampled `(x, y)` curve at any `x ∈ [0, 1]` using binary search + linear interpolation.
255pub fn sample_curve_at(curve: &[(f64, f64)], x: f64) -> f64 {
256    if curve.is_empty() {
257        return 0.0;
258    }
259    if x <= curve[0].0 {
260        return curve[0].1;
261    }
262    let last = curve.len() - 1;
263    if x >= curve[last].0 {
264        return curve[last].1;
265    }
266    let mut lo = 0usize;
267    let mut hi = last;
268    while hi - lo > 1 {
269        let mid = (lo + hi) >> 1;
270        if curve[mid].0 < x {
271            lo = mid;
272        } else {
273            hi = mid;
274        }
275    }
276    let (x0, y0) = curve[lo];
277    let (x1, y1) = curve[hi];
278    if (x1 - x0).abs() <= 1e-12 {
279        y1
280    } else {
281        y0 + (y1 - y0) * ((x - x0) / (x1 - x0))
282    }
283}
284
285/// Slice a screen-space polyline by arc-length progress `t ∈ [0.0, 1.0]`, returning the prefix points.
286pub fn slice_polyline_by_progress(pts: &[Point<Pixels>], progress: f32) -> Vec<Point<Pixels>> {
287    let p = progress.clamp(0.0, 1.0);
288    if pts.len() < 2 || p <= 0.0005 {
289        return Vec::new();
290    }
291    if p >= 0.9995 {
292        return pts.to_vec();
293    }
294    let mut seg_lens = Vec::with_capacity(pts.len() - 1);
295    let mut total = 0.0f32;
296    for w in pts.windows(2) {
297        let dx: f32 = (w[1].x - w[0].x).into();
298        let dy: f32 = (w[1].y - w[0].y).into();
299        let d = dx.hypot(dy);
300        seg_lens.push(d);
301        total += d;
302    }
303    let mut remaining = total * p;
304    let mut out = vec![pts[0]];
305    for (i, &len) in seg_lens.iter().enumerate() {
306        if remaining <= len || i + 1 == seg_lens.len() {
307            let frac = if len > 1e-4 {
308                (remaining / len).clamp(0.0, 1.0)
309            } else {
310                1.0
311            };
312            let x0: f32 = pts[i].x.into();
313            let y0: f32 = pts[i].y.into();
314            let x1: f32 = pts[i + 1].x.into();
315            let y1: f32 = pts[i + 1].y.into();
316            out.push(point(px(x0 + (x1 - x0) * frac), px(y0 + (y1 - y0) * frac)));
317            break;
318        }
319        out.push(pts[i + 1]);
320        remaining -= len;
321    }
322    out
323}
324
325/// Build a stroked polyline path in GPUI.
326pub fn build_polyline_stroke(pts: &[Point<Pixels>], stroke_width: f32) -> Option<Path> {
327    if pts.len() < 2 {
328        return None;
329    }
330    let mut pb = PathBuilder::stroke(px(stroke_width));
331    pb.move_to(pts[0]);
332    for &p in &pts[1..] {
333        pb.line_to(p);
334    }
335    pb.build().ok()
336}
337
338/// Build a dashed polyline as individual short dash paths.
339pub fn build_dashed_polyline(
340    pts: &[Point<Pixels>],
341    stroke_width: f32,
342    dash_px: f32,
343    gap_px: f32,
344) -> Vec<Path> {
345    if pts.len() < 2 {
346        return Vec::new();
347    }
348    let mut paths = Vec::new();
349    let period = (dash_px + gap_px).max(2.0);
350    let mut dist = 0.0f32;
351    for w in pts.windows(2) {
352        let x0: f32 = w[0].x.into();
353        let y0: f32 = w[0].y.into();
354        let x1: f32 = w[1].x.into();
355        let y1: f32 = w[1].y.into();
356        let seg = (x1 - x0).hypot(y1 - y0);
357        if seg <= 1e-4 {
358            continue;
359        }
360        let mut cursor = 0.0f32;
361        while cursor < seg {
362            let phase = (dist + cursor) % period;
363            if phase < dash_px {
364                let take = (dash_px - phase).min(seg - cursor);
365                let t0 = cursor / seg;
366                let t1 = (cursor + take) / seg;
367                let mut pb = PathBuilder::stroke(px(stroke_width));
368                pb.move_to(point(px(x0 + (x1 - x0) * t0), px(y0 + (y1 - y0) * t0)));
369                pb.line_to(point(px(x0 + (x1 - x0) * t1), px(y0 + (y1 - y0) * t1)));
370                if let Ok(path) = pb.build() {
371                    paths.push(path);
372                }
373                cursor += take;
374            } else {
375                cursor += (period - phase).min(seg - cursor);
376            }
377        }
378        dist += seg;
379    }
380    paths
381}
382
383/// Build a closed area fill path beneath a polyline down to `baseline_y`.
384pub fn build_area_fill(pts: &[Point<Pixels>], baseline_y: Pixels) -> Option<Path> {
385    if pts.len() < 2 {
386        return None;
387    }
388    let mut pb = PathBuilder::fill();
389    pb.move_to(pts[0]);
390    for &p in &pts[1..] {
391        pb.line_to(p);
392    }
393    let last = *pts.last().unwrap();
394    pb.line_to(point(last.x, baseline_y));
395    pb.line_to(point(pts[0].x, baseline_y));
396    pb.close();
397    pb.build().ok()
398}
399
400/// Build a closed ribbon/band fill path bounded by an `upper` polyline (left to right)
401/// and a `lower` polyline (right to left). Used by `Streamgraph` and `BrushChart`.
402pub fn build_band_fill(upper: &[Point<Pixels>], lower: &[Point<Pixels>]) -> Option<Path> {
403    if upper.len() < 2 || lower.len() < 2 {
404        return None;
405    }
406    let mut pb = PathBuilder::fill();
407    pb.move_to(upper[0]);
408    for &p in &upper[1..] {
409        pb.line_to(p);
410    }
411    for &p in lower.iter().rev() {
412        pb.line_to(p);
413    }
414    pb.close();
415    pb.build().ok()
416}
417
418/// Build a filled circle path centered at `(cx, cy)` with radius `r`.
419pub fn build_circle_fill(cx: f32, cy: f32, r: f32, steps: usize) -> Option<Path> {
420    if r <= 0.1 {
421        return None;
422    }
423    let n = steps.max(12);
424    let mut pb = PathBuilder::fill();
425    for i in 0..n {
426        let a = (i as f32 / n as f32) * TAU;
427        let pt = point(px(cx + r * a.cos()), px(cy + r * a.sin()));
428        if i == 0 {
429            pb.move_to(pt);
430        } else {
431            pb.line_to(pt);
432        }
433    }
434    pb.close();
435    pb.build().ok()
436}
437
438/// Build a stroked circular arc sampled smoothly between `start_deg` and `end_deg`
439/// (clockwise from 12 o'clock, matching Arc `Gauge` convention: `-135°` to `+135°`).
440pub fn build_clock_arc_stroke(
441    cx: f32,
442    cy: f32,
443    radius: f32,
444    start_deg: f32,
445    end_deg: f32,
446    stroke_width: f32,
447    segments: usize,
448) -> Option<Path> {
449    if (end_deg - start_deg).abs() < 0.05 {
450        return None;
451    }
452    let n = segments.max(8);
453    let mut pb = PathBuilder::stroke(px(stroke_width));
454    for i in 0..=n {
455        let deg = start_deg + (end_deg - start_deg) * (i as f32 / n as f32);
456        let rad = deg.to_radians();
457        let x = cx + radius * rad.sin();
458        let y = cy - radius * rad.cos();
459        let pt = point(px(x), px(y));
460        if i == 0 {
461            pb.move_to(pt);
462        } else {
463            pb.line_to(pt);
464        }
465    }
466    pb.build().ok()
467}
468
469/// Build a filled annular sector polygon between normalized turns `[t0, t1]` (`0.0` at 12 o'clock,
470/// clockwise) with outer radius `outer_r`, inner radius `inner_r`, and angular gap inset `gap_px`.
471pub fn build_annular_sector_fill(
472    cx: f32,
473    cy: f32,
474    outer_r: f32,
475    inner_r: f32,
476    t0: f32,
477    t1: f32,
478    gap_px: f32,
479) -> Option<Path> {
480    let turns = (t1 - t0).clamp(0.0, 1.0);
481    if turns <= 1e-4 || outer_r <= inner_r + 0.5 {
482        return None;
483    }
484    let a0 = t0 * TAU - FRAC_PI_2;
485    let a1 = t1 * TAU - FRAC_PI_2;
486    let gap_half = if turns >= 0.999 {
487        0.0
488    } else {
489        (gap_px * 0.5).min(((1.0 - turns) * TAU * outer_r) * 0.5)
490    };
491
492    let d_out = if outer_r > 1.0 {
493        (gap_half / outer_r).min((a1 - a0) * 0.45)
494    } else {
495        0.0
496    };
497    let d_in = if inner_r > 1.0 {
498        (gap_half / inner_r).min((a1 - a0) * 0.45)
499    } else {
500        0.0
501    };
502
503    let oa0 = a0 + d_out;
504    let oa1 = a1 - d_out;
505    let ia0 = a0 + d_in;
506    let ia1 = a1 - d_in;
507    if oa1 <= oa0 + 1e-4 {
508        return None;
509    }
510
511    let steps = ((turns * 72.0).ceil() as usize).clamp(8, 96);
512    let mut pb = PathBuilder::fill();
513    for i in 0..=steps {
514        let a = oa0 + (oa1 - oa0) * (i as f32 / steps as f32);
515        let pt = point(px(cx + outer_r * a.cos()), px(cy + outer_r * a.sin()));
516        if i == 0 {
517            pb.move_to(pt);
518        } else {
519            pb.line_to(pt);
520        }
521    }
522    if ia1 > ia0 + 1e-4 {
523        for i in (0..=steps).rev() {
524            let a = ia0 + (ia1 - ia0) * (i as f32 / steps as f32);
525            pb.line_to(point(
526                px(cx + inner_r * a.cos()),
527                px(cy + inner_r * a.sin()),
528            ));
529        }
530    } else {
531        let mid = (a0 + a1) * 0.5;
532        let tip_r = inner_r.max(gap_half / ((a1 - a0) * 0.5).sin().max(0.05));
533        pb.line_to(point(
534            px(cx + tip_r.min(outer_r) * mid.cos()),
535            px(cy + tip_r.min(outer_r) * mid.sin()),
536        ));
537    }
538    pb.close();
539    pb.build().ok()
540}
541
542/// Lightweight damped harmonic oscillator for per-instance interactive chart animations
543/// (swell, morph, lift, presence, reveal) integrated directly in component state.
544#[derive(Clone, Copy, Debug)]
545pub struct ChartSpring {
546    pub value: f32,
547    pub velocity: f32,
548    pub target: f32,
549}
550
551impl ChartSpring {
552    pub const fn new(initial: f32) -> Self {
553        Self {
554            value: initial,
555            velocity: 0.0,
556            target: initial,
557        }
558    }
559
560    pub fn snap(&mut self, value: f32) {
561        self.value = value;
562        self.target = value;
563        self.velocity = 0.0;
564    }
565
566    pub fn set_target(&mut self, target: f32) {
567        self.target = target;
568    }
569
570    pub fn position(&self) -> f32 {
571        self.value
572    }
573
574    pub fn is_settled(&self) -> bool {
575        (self.value - self.target).abs() < 0.002 && self.velocity.abs() < 0.01
576    }
577
578    pub fn is_settled_at(&self, target: f32, eps: f32) -> bool {
579        (self.value - target).abs() <= eps && self.velocity.abs() <= eps * 4.0
580    }
581
582    /// Semi-implicit Euler step derived from `(visual_duration_secs, bounce)`.
583    pub fn step_to(&mut self, target: f32, duration_secs: f32, bounce: f32, dt_secs: f32) {
584        self.target = target;
585        let dt = dt_secs.clamp(0.0, 0.05);
586        if dt <= 0.0 {
587            return;
588        }
589        let dur = duration_secs.max(0.05);
590        let omega = std::f32::consts::TAU / (dur * 1.2);
591        let stiffness = omega * omega;
592        let damping = 2.0 * (1.0 - bounce.clamp(-0.5, 0.85)) * omega;
593        // Sub-step for numerical stability
594        let steps = 4usize;
595        let h = dt / steps as f32;
596        for _ in 0..steps {
597            let accel = -stiffness * (self.value - target) - damping * self.velocity;
598            self.velocity += accel * h;
599            self.value += self.velocity * h;
600        }
601        if (self.value - target).abs() < 0.001 && self.velocity.abs() < 0.005 {
602            self.value = target;
603            self.velocity = 0.0;
604        }
605    }
606
607    pub fn step(&mut self, duration_secs: f32, bounce: f32, dt_secs: f32) {
608        let t = self.target;
609        self.step_to(t, duration_secs, bounce, dt_secs);
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    #[test]
618    fn chart_math_scales_formatting_and_monotone_curve() {
619        let sc = nice_scale(0.0, 93.0, 4);
620        assert_eq!(sc.min, 0.0);
621        assert_eq!(sc.max, 100.0);
622        assert_eq!(sc.ticks, vec![0.0, 25.0, 50.0, 75.0, 100.0]);
623
624        let pos = nice_scale_positive(64.0);
625        assert_eq!(pos.min, 0.0);
626        assert!(pos.max >= 64.0 && pos.ticks.len() <= 5);
627
628        assert_eq!(format_grouped(12_345.0, 0), "12,345");
629        assert_eq!(format_grouped(-4200.5, 1), "-4,200.5");
630        assert_eq!(format_compact(1_260.0), "1.3K");
631        assert_eq!(format_compact(2_000_000.0), "2M");
632        assert_eq!(format_share(0.004), "<1%");
633        assert_eq!(format_share(0.376), "38%");
634
635        let curve = sample_monotone_curve(&[10.0, 50.0, 20.0, 20.0, 80.0], true, 64);
636        assert!(curve.len() >= 5);
637        // Monotone clamp guarantees no point swings outside [10, 80]
638        assert!(curve.iter().all(|&(_, y)| (10.0..=80.0).contains(&y)));
639        assert!((sample_curve_at(&curve, 0.0) - 10.0).abs() < 1e-6);
640        assert!((sample_curve_at(&curve, 1.0) - 80.0).abs() < 1e-6);
641    }
642}