Bar, line and area charts with axes, gridlines, a legend and a hover tooltip, drawn natively.
use gpui::{div, prelude::*, px};
use crate::ui::chart::{Chart, ChartKind, ChartSeries};
pub fn chart_demo() -> impl IntoElement {
div().w(px(560.0)).child(
Chart::new("visitors", ChartKind::Bar)
.categories(["January", "February", "March", "April", "May", "June"])
.series(ChartSeries::new("Desktop", [186.0, 305.0, 237.0, 73.0, 209.0, 214.0]))
.series(ChartSeries::new("Mobile", [80.0, 200.0, 120.0, 190.0, 130.0, 140.0])),
)
}Installation
Copies src/ui/chart.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/chart.rs.src/ui/chart.rs //! Bar, line, area, pie, radar and radial charts drawn natively. shadcn/ui wraps Recharts; GPUI has no //! charting library, so this file scales the axes, paints shapes on a `canvas()` and lays text //! out as ordinary divs around it. //! //! The file has three layers. Use a lower one to draw a chart it doesn't ship: //! - [`scale`]: maps values to positions and picks round tick values. //! - [`shape`]: turns points into GPUI paths (curves, pie sectors). //! - [`Chart`], [`PieChart`], [`RadarChart`] and [`RadialChart`]: ready-made charts with //! axes, tooltips and legends. //! - [`OrderBook`] and [`PortfolioChart`]: market blocks, ported from spectrum-ui (Apache-2.0). use std::cell::{Cell, RefCell}; use std::f32::consts::TAU; use std::hash::{DefaultHasher, Hash, Hasher}; use std::rc::Rc; use std::time::Duration; use gpui::{ Animation, AnimationExt, App, Background, Global, BorderStyle, Bounds, ContentMask, Corners, ElementId, Entity, FontWeight, Hsla, LineCap, LineJoin, PaintQuad, PathBuilder, PathStyle, Pixels, SharedString, StrokeOptions, TextAlign, TextRun, Window, canvas, div, fill, hsla, linear_color_stop, linear_gradient, point, prelude::*, px, relative, svg, }; use crate::theme::{ActiveTheme, Theme}; use self::scale::{BandScale, LinearScale}; use self::shape::{sector, slice_at, trace}; pub use self::shape::Curve; const MONO: &str = "Geist Mono"; const Y_AXIS_WIDTH: Pixels = px(44.0); /// Room for category names down the left of a horizontal bar chart. const CATEGORY_AXIS_WIDTH: Pixels = px(64.0); /// About how many y-axis ticks to aim for; the "nice" step decides the exact count. const TICKS: usize = 5; /// Share of each category's slot left empty on either side of its bars. const BAND_GAP: f32 = 0.12; const BAR_GAP: f32 = 4.0; const LINE_WIDTH: f32 = 2.0; const AREA_OPACITY: f32 = 0.4; const DOT_SIZE: f32 = 12.0; const SMALL_DOT: f32 = 7.0; /// Text is 12px on a 16px line; labels are centered on their tick by half of that. const LABEL_HALF_HEIGHT: Pixels = px(8.0); /// Above this many categories, x-axis labels are thinned so they don't collide. const MAX_X_LABELS: usize = 12; type Formatter = Rc<dyn Fn(f64) -> SharedString + 'static>; /// The five chart colors shadcn/ui ships, picked for the theme's light or dark background. pub fn chart_colors(theme: &Theme) -> [Hsla; 5] { let c = |h: f32, s: f32, l: f32| hsla(h / 360.0, s / 100.0, l / 100.0, 1.0); if theme.background.l < 0.5 { [c(220.0, 70.0, 50.0), c(160.0, 60.0, 45.0), c(30.0, 80.0, 55.0), c(280.0, 65.0, 60.0), c(340.0, 75.0, 55.0)] } else { [c(12.0, 76.0, 61.0), c(173.0, 58.0, 39.0), c(197.0, 37.0, 24.0), c(43.0, 74.0, 66.0), c(27.0, 87.0, 67.0)] } } /// Replaces the default chart colors app-wide: `cx.set_global(ChartColors([...]))`. Charts read it /// each frame, so setting it again re-colors them. #[derive(Clone, Copy, Debug)] pub struct ChartColors(pub [Hsla; 5]); impl Global for ChartColors {} /// The palette charts draw with: [`ChartColors`] when the app set one, else [`chart_colors`]. pub fn palette(cx: &App) -> [Hsla; 5] { cx.try_global::<ChartColors>() .map(|colors| colors.0) .unwrap_or_else(|| chart_colors(cx.theme())) } #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum ChartKind { /// Vertical bars, side by side when there are several series. #[default] Bar, /// A line per series. Line, /// A line per series with the area below it filled in. Area, } /// How the tooltip marks each series' color. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum Indicator { #[default] Dot, Line, Dashed, None, } /// One named row of values, one per category. NaN or a missing value leaves a gap. pub struct ChartSeries { label: SharedString, values: Vec<f64>, color: Option<Hsla>, colors: Option<Vec<Hsla>>, icon: Option<&'static [u8]>, } impl ChartSeries { pub fn new(label: impl Into<SharedString>, values: impl IntoIterator<Item = f64>) -> Self { Self { label: label.into(), values: values.into_iter().collect(), color: None, colors: None, icon: None } } /// An SVG icon shown in the legend in place of the color square. pub fn icon(mut self, svg: &'static [u8]) -> Self { self.icon = Some(svg); self } /// Overrides the series color. Pass a theme token or one of [`chart_colors`] so dark mode follows. pub fn color(mut self, color: Hsla) -> Self { self.color = Some(color); self } /// A color per category instead of one for the whole series, e.g. a bar per browser. pub fn colors(mut self, colors: impl IntoIterator<Item = Hsla>) -> Self { self.colors = Some(colors.into_iter().collect()); self } } /// Pointer and legend state that lives as long as the chart is on screen. #[derive(Default)] struct ChartState { hover: Option<usize>, hidden: Vec<bool>, /// The data fingerprint the current draw-in animation runs toward. key: Option<u64>, /// Where each line or area series stood when the data last changed, which the new points /// grow out of. Empty on first show, so every series reveals instead. from: Rc<Vec<SeriesPoints>>, /// Where each series was last painted, updated every frame, so a change made mid-animation /// starts from what is on screen. painted: Rc<RefCell<Vec<SeriesPoints>>>, } /// One series' points as fractions of the plot: x, the value's y and the floor's y. `None` /// for a hidden series, and per point for a missing value. type SeriesPoints = Option<Vec<Option<[f32; 3]>>>; #[derive(IntoElement)] pub struct Chart { id: ElementId, kind: ChartKind, categories: Vec<SharedString>, series: Vec<ChartSeries>, stacked: bool, expanded: bool, horizontal: bool, curve: Curve, dots: bool, gradient: bool, labels: bool, category_labels: bool, inside_labels: bool, active: Option<usize>, open_tooltip: Option<usize>, tooltip_total: bool, tooltip_title: Option<Rc<dyn Fn(&SharedString) -> SharedString>>, height: Pixels, y_axis: bool, x_axis: bool, legend: bool, tooltip: bool, tooltip_label: bool, indicator: Indicator, bar_radius: Pixels, format: Option<Formatter>, } impl Chart { pub fn new(id: impl Into<ElementId>, kind: ChartKind) -> Self { Self { id: id.into(), kind, categories: Vec::new(), series: Vec::new(), stacked: false, expanded: false, horizontal: false, curve: Curve::Monotone, dots: false, gradient: false, labels: false, category_labels: false, inside_labels: false, active: None, open_tooltip: None, tooltip_total: false, tooltip_title: None, height: px(220.0), y_axis: true, x_axis: true, legend: true, tooltip: true, tooltip_label: true, indicator: Indicator::Dot, bar_radius: px(4.0), format: None, } } pub fn categories<S: Into<SharedString>>(mut self, categories: impl IntoIterator<Item = S>) -> Self { self.categories = categories.into_iter().map(Into::into).collect(); self } pub fn series(mut self, series: ChartSeries) -> Self { self.series.push(series); self } /// Stacks series on top of each other instead of side by side or overlapping. pub fn stacked(mut self, stacked: bool) -> Self { self.stacked = stacked; self } /// Stacks series and scales every category to 100%, so the chart shows each series' share. pub fn expanded(mut self, expanded: bool) -> Self { self.expanded = expanded; self } /// Lays bars out sideways: categories down the left, values along the bottom. pub fn horizontal(mut self, horizontal: bool) -> Self { self.horizontal = horizontal; self } /// How lines pass through their points. Smooth by default. pub fn curve(mut self, curve: Curve) -> Self { self.curve = curve; self } /// Draws a dot on every point of a line or area, not only the hovered one. pub fn dots(mut self, dots: bool) -> Self { self.dots = dots; self } /// Fills areas with a gradient that fades toward the axis, instead of a flat tint. pub fn gradient(mut self, gradient: bool) -> Self { self.gradient = gradient; self } /// Writes each value at the end of its bar or above its point. pub fn labels(mut self, labels: bool) -> Self { self.labels = labels; self } /// With `labels(true)`, writes each point's category name instead of its value. pub fn category_labels(mut self, category_labels: bool) -> Self { self.category_labels = category_labels; self } /// For horizontal bars: writes the category name inside each bar instead of on an axis. pub fn inside_labels(mut self, inside: bool) -> Self { self.inside_labels = inside; self } /// Emphasizes one category's bar with a dashed outline, e.g. the current month. pub fn active(mut self, index: usize) -> Self { self.active = Some(index); self } /// Height of the plot, without axis labels and legend. pub fn height(mut self, height: Pixels) -> Self { self.height = height; self } pub fn y_axis(mut self, y_axis: bool) -> Self { self.y_axis = y_axis; self } pub fn x_axis(mut self, x_axis: bool) -> Self { self.x_axis = x_axis; self } /// A row of series names under the chart. Clicking one hides or shows that series. pub fn legend(mut self, legend: bool) -> Self { self.legend = legend; self } /// Whether hovering shows a card with every series' value. pub fn tooltip(mut self, tooltip: bool) -> Self { self.tooltip = tooltip; self } /// Whether the tooltip starts with the category's name. pub fn tooltip_label(mut self, label: bool) -> Self { self.tooltip_label = label; self } /// Shows the tooltip for one category from the start, before the pointer arrives. The /// pointer still moves it, and it returns to this category when the pointer leaves. pub fn open_tooltip(mut self, index: usize) -> Self { self.open_tooltip = Some(index); self } /// Adds a last tooltip row with the sum of every shown series. pub fn tooltip_total(mut self, total: bool) -> Self { self.tooltip_total = total; self } /// Rewrites the tooltip's title from the category, e.g. "Jan 1" to "January 1, 2024". pub fn tooltip_title(mut self, title: impl Fn(&SharedString) -> SharedString + 'static) -> Self { self.tooltip_title = Some(Rc::new(title)); self } /// How the tooltip marks each series: a dot, a line, a dashed line or nothing. pub fn indicator(mut self, indicator: Indicator) -> Self { self.indicator = indicator; self } pub fn bar_radius(mut self, radius: Pixels) -> Self { self.bar_radius = radius; self } /// Formats values on the value axis, in labels and in the tooltip, e.g. as currency. pub fn format(mut self, format: impl Fn(f64) -> SharedString + 'static) -> Self { self.format = Some(Rc::new(format)); self } } /// How long a chart takes to draw itself in: Recharts' 1500ms for lines, areas, pies, radars /// and radial bars, and its 400ms for bars. const GROW: Duration = Duration::from_millis(1500); const BAR_GROW: Duration = Duration::from_millis(400); /// CSS `ease`, `cubic-bezier(0.25, 0.1, 0.25, 1)`, which Recharts animates with. fn css_ease(t: f32) -> f32 { cubic_bezier(0.25, 0.1, 0.25, 1.0, t) } /// A CSS cubic-bézier timing function: solves the curve's x for `t` by Newton's method, then /// returns its y there. fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 { let t = t.clamp(0.0, 1.0); let at = |a: f32, b: f32, s: f32| 3.0 * a * s * (1.0 - s).powi(2) + 3.0 * b * s * s * (1.0 - s) + s.powi(3); let slope = |a: f32, b: f32, s: f32| 3.0 * a * (1.0 - s).powi(2) + 6.0 * (b - a) * s * (1.0 - s) + 3.0 * (1.0 - b) * s * s; let mut s = t; for _ in 0..8 { let dx = slope(x1, x2, s); if dx.abs() < 1e-6 { break; } s = (s - (at(x1, x2, s) - t) / dx).clamp(0.0, 1.0); } at(y1, y2, s) } /// Draws `plot` in over `duration`: each frame stores how far along it is (0 to 1, eased) in /// `progress`, which the plot's canvas reads as it paints. The animation is keyed by `data`, so /// it plays when the chart first shows and again whenever its data changes, but not on hover. fn grow_in( wrapper: gpui::Div, plot: impl IntoElement, progress: Rc<Cell<f32>>, data: u64, duration: Duration, ) -> impl IntoElement { wrapper.child(plot).with_animation( ("chart-grow", data as usize), Animation::new(duration).with_easing(css_ease), move |this, t| { progress.set(t); this }, ) } /// A fingerprint of a chart's values, to restart [`grow_in`] when they change. fn data_key<'a>(values: impl IntoIterator<Item = &'a f64>, extra: impl Hash) -> u64 { let mut hasher = DefaultHasher::new(); for value in values { value.to_bits().hash(&mut hasher); } extra.hash(&mut hasher); hasher.finish() } /// A value's place on the plot: bars run from `lo` to `hi`, lines pass through `at`. #[derive(Clone, Copy, Debug)] struct Span { lo: f64, hi: f64, at: f64, } /// Turns series values into spans per category, stacking them when asked. Positives stack /// upward from zero and negatives downward, as Recharts does. `expanded` divides each /// category by its total so stacks reach 1. fn layout(values: &[Vec<Option<f64>>], visible: &[bool], stacked: bool, expanded: bool, count: usize) -> Vec<Vec<Option<Span>>> { let stacked = stacked || expanded; let mut spans = vec![vec![None; count]; values.len()]; for ix in 0..count { let total: f64 = (0..values.len()).filter(|&s| visible[s]).filter_map(|s| values[s][ix]).map(f64::abs).sum(); let scale = if expanded && total > 0.0 { 1.0 / total } else { 1.0 }; let (mut up, mut down) = (0.0, 0.0); for (s, series) in values.iter().enumerate() { if !visible[s] { continue; } let Some(v) = series[ix].map(|v| v * scale) else { continue }; spans[s][ix] = Some(match (stacked, v >= 0.0) { (false, _) => Span { lo: v.min(0.0), hi: v.max(0.0), at: v }, (true, true) => { let span = Span { lo: up, hi: up + v, at: up + v }; up += v; span } (true, false) => { let span = Span { lo: down + v, hi: down, at: down + v }; down += v; span } }); } } spans } fn default_value_text(value: f64) -> SharedString { if value.fract() == 0.0 && value.abs() < 1e15 { format!("{value:.0}").into() } else { format!("{value:.2}").into() } } /// A small mark in a series' color, as the tooltip and legend show it. fn swatch(indicator: Indicator, color: Hsla) -> Option<gpui::AnyElement> { let mark = match indicator { Indicator::None => return None, Indicator::Dot => div().size(px(10.0)).rounded(px(2.0)).bg(color), Indicator::Line => div().w(px(4.0)).h(px(16.0)).rounded(px(2.0)).bg(color), Indicator::Dashed => div().w(px(0.0)).h(px(16.0)).border_l_1().border_dashed().border_color(color), }; Some(mark.flex_none().into_any_element()) } impl RenderOnce for Chart { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let series_count = self.series.len(); let state = window.use_keyed_state(self.id.clone(), cx, |_, _| ChartState::default()); state.update(cx, |state, _| state.hidden.resize(series_count, false)); let theme = cx.theme().clone(); let palette = palette(cx); let count = self.categories.len(); let horizontal = self.horizontal && self.kind == ChartKind::Bar; let (hovered, visible) = { let state = state.read(cx); ( state.hover.or(self.open_tooltip).filter(|&ix| ix < count && self.tooltip), state.hidden.iter().map(|hidden| !hidden).collect::<Vec<_>>(), ) }; // Each series' own color draws its line, fill and legend mark; a per-category color, when // given, wins for that category's bar or dot. let base_colors: Vec<Hsla> = self.series.iter().enumerate().map(|(s, series)| series.color.unwrap_or(palette[s % palette.len()])).collect(); let colors: Vec<Vec<Hsla>> = self .series .iter() .zip(&base_colors) .map(|(series, &base)| { (0..count) .map(|ix| series.colors.as_ref().and_then(|colors| colors.get(ix).copied()).unwrap_or(base)) .collect() }) .collect(); let values: Vec<Vec<Option<f64>>> = self .series .iter() .map(|series| (0..count).map(|ix| series.values.get(ix).copied().filter(|v| v.is_finite())).collect()) .collect(); let spans = layout(&values, &visible, self.stacked, self.expanded, count); let scale = if self.expanded { LinearScale { min: 0.0, max: 1.0, step: 0.25 } } else { let (lo, hi) = spans .iter() .flatten() .flatten() .fold((0.0f64, 0.0f64), |(lo, hi), span| (lo.min(span.lo), hi.max(span.hi))); LinearScale::nice(lo, hi, TICKS) }; let ticks = scale.ticks(); let expanded = self.expanded; let value_text: Rc<dyn Fn(f64) -> SharedString> = { let format = self.format.clone(); Rc::new(move |value: f64| match (&format, expanded) { (_, true) => SharedString::from(format!("{:.0}%", value * 100.0)), (Some(format), false) => format(value), (None, false) => default_value_text(value), }) }; let axis_text = { let format = self.format.clone(); move |value: f64| match (&format, expanded) { (_, true) => SharedString::from(format!("{:.0}%", value * 100.0)), (Some(format), false) => format(value), (None, false) => scale.label(value), } }; let progress = Rc::new(Cell::new(1.0f32)); let grow_key = data_key(values.iter().flatten().flatten(), (&visible, self.kind as u8, self.stacked, self.expanded)); // A new fingerprint starts a new animation, from wherever the series were last painted. let (from, painted) = state.update(cx, |state, _| { if state.key != Some(grow_key) { state.from = Rc::new(if state.key.is_some() { state.painted.borrow().clone() } else { Vec::new() }); state.key = Some(grow_key); } (state.from.clone(), state.painted.clone()) }); let plot = { let progress = progress.clone(); let (spans, colors, base_colors, visible, ticks, theme) = (spans.clone(), colors.clone(), base_colors.clone(), visible.clone(), ticks.clone(), theme.clone()); let categories = self.categories.clone(); let value_text = value_text.clone(); let style = PlotStyle { kind: self.kind, stacked: self.stacked || self.expanded, horizontal, curve: self.curve, dots: self.dots, gradient: self.gradient, labels: self.labels, category_labels: self.category_labels, inside_labels: self.inside_labels && horizontal, active: self.active, bar_radius: self.bar_radius, }; canvas( |_, _, _| {}, move |bounds, _, window, cx| { if count > 0 { // As in Recharts: bars grow out of the zero line, areas are wiped in // from the left, lines draw along their length, and on a data change // lines and areas move from their old points. Value labels wait for // the end. let t = progress.get(); let mut style = style; if t < 1.0 { style.labels = false; } let grown; let spans = if t < 1.0 && style.kind == ChartKind::Bar { let t = f64::from(t); grown = spans .iter() .map(|row| row.iter().map(|span| span.map(|s| Span { lo: s.lo * t, hi: s.hi * t, at: s.at * t })).collect()) .collect::<Vec<Vec<Option<Span>>>>(); &grown } else { &spans }; let data = PlotData { spans, visible: &visible, colors: &colors, base_colors: &base_colors, ticks: &ticks, categories: &categories, }; let motion = Motion { t, from: &from, painted: &painted }; paint_plot(window, cx, bounds, style, scale, hovered, data, motion, &*value_text, &theme); } }, ) .absolute() .size_full() }; // One hover target per category. Leave and enter events between neighbors arrive in // no fixed order, so a band only clears the hover if it still owns it. let bands = div().absolute().size_full().flex().when(horizontal, |this| this.flex_col()).children((0..count).map(|ix| { let state = state.clone(); div().id(("chart-band", ix)).flex_1().size_full().on_hover(move |hovered, _, cx| { state.update(cx, |state, cx| { let next = match (*hovered, state.hover) { (true, _) => Some(ix), (false, Some(owner)) if owner == ix => None, (false, other) => other, }; if state.hover != next { state.hover = next; cx.notify(); } }); }) })); let tooltip = hovered.map(|ix| { let center = (ix as f32 + 0.5) / count as f32; let rows = self.series.iter().enumerate().filter(|(s, _)| visible[*s]).filter_map(|(s, series)| { let value = values[s][ix]?; Some( div() .flex() .items_center() .gap_2() .children(match series.icon { Some(icon) => Some(svg().data(icon).flex_none().size(px(12.0)).text_color(theme.muted_foreground).into_any_element()), None => swatch(self.indicator, colors[s][ix]), }) .child(div().flex_1().text_color(theme.muted_foreground).child(series.label.clone())) .child(div().pl_4().font_family(MONO).text_color(theme.foreground).child(value_text(value))), ) }); let card = div() .absolute() .min_w(px(136.0)) .flex() .flex_col() .gap(px(6.0)) .px(px(10.0)) .py(px(8.0)) .rounded(theme.radius) .border_1() .border_color(theme.border) .bg(theme.background) .shadow_lg() .when(self.tooltip_label, |this| { let category = &self.categories[ix]; let title = self.tooltip_title.as_ref().map_or_else(|| category.clone(), |title| title(category)); this.child(div().font_weight(FontWeight::MEDIUM).text_color(theme.foreground).child(title)) }) .children(rows) .when(self.tooltip_total, |this| { let total: f64 = (0..series_count).filter(|&s| visible[s]).filter_map(|s| values[s][ix]).sum(); this.child( div() .flex() .items_center() .gap_2() .pt(px(6.0)) .border_t_1() .border_color(theme.border) .child(div().flex_1().font_weight(FontWeight::MEDIUM).text_color(theme.foreground).child("Total")) .child(div().pl_4().font_family(MONO).text_color(theme.foreground).child(value_text(total))), ) }); if horizontal { // Beside the row, at the right, so it never covers the bar being read. div().absolute().right(px(8.0)).top(relative(center)).h(px(0.0)).child(card.right_0().top(px(-20.0))) } else { // Beside the slot rather than under the pointer, so it never steals the hover, // and on the left in the right half so it stays inside the chart. let card = card.top(px(8.0)); let card = if center > 0.5 { card.right(px(14.0)) } else { card.left(px(14.0)) }; div().absolute().top_0().left(relative(center)).w(px(0.0)).child(card) } }); let height = self.height; // The axis down the left: values for vertical charts, categories for horizontal bars. let left_axis = if horizontal { (self.y_axis && !self.inside_labels).then(|| { div().flex().flex_col().flex_none().w(CATEGORY_AXIS_WIDTH).h(height).children(self.categories.iter().map(|category| { div().flex_1().flex().items_center().justify_end().pr_2().whitespace_nowrap().child(category.clone()) })) }) } else { self.y_axis.then(|| { div().relative().flex_none().w(Y_AXIS_WIDTH).h(height).children(ticks.iter().map(|&tick| { div() .absolute() .right_0() .pr_2() .whitespace_nowrap() .font_family(MONO) .top(height * scale.ratio(tick) - LABEL_HALF_HEIGHT) .child(axis_text(tick)) })) }) }; let left_width = left_axis.as_ref().map(|_| if horizontal { CATEGORY_AXIS_WIDTH } else { Y_AXIS_WIDTH }); // The axis along the bottom: categories for vertical charts, values for horizontal bars. // Many categories (a day per point) get every n-th label, so labels never overlap. let every = count.div_ceil(MAX_X_LABELS).max(1); let bottom_axis = self.x_axis.then(|| { let row = div().pt_2().when_some(left_width, |this, width| this.pl(width)); if horizontal { row.child(div().relative().h(px(16.0)).children(ticks.iter().map(|&tick| { div() .absolute() .top_0() .left(relative(1.0 - scale.ratio(tick))) .w(px(0.0)) .flex() .justify_center() .whitespace_nowrap() .font_family(MONO) .child(axis_text(tick)) }))) } else { row.flex().children(self.categories.iter().enumerate().map(|(ix, category)| { div() .flex_1() .min_w_0() .flex() .justify_center() .whitespace_nowrap() .when(ix % every == 0, |this| this.child(category.clone())) })) } }); let legend = self.legend.then(|| { div() .flex() .flex_wrap() .justify_center() .gap_4() .pt_3() .when_some(left_width, |this, width| this.pl(width)) .children(self.series.iter().enumerate().map(|(s, series)| { let state = state.clone(); div() .id(("chart-legend", s)) .flex() .items_center() .gap(px(6.0)) .cursor_pointer() .text_color(theme.foreground) .when(!visible[s], |this| this.opacity(0.4)) .on_click(move |_, _, cx| { state.update(cx, |state, cx| { // Never hide the last visible series; an empty chart helps no one. let shown = state.hidden.iter().filter(|hidden| !**hidden).count(); if state.hidden[s] || shown > 1 { state.hidden[s] = !state.hidden[s]; cx.notify(); } }); }) .child(match series.icon { Some(icon) => svg().data(icon).flex_none().size(px(12.0)).text_color(theme.muted_foreground).into_any_element(), None => div() .size(px(8.0)) .flex_none() .rounded(px(2.0)) .bg(base_colors[s]) .into_any_element(), }) .child(series.label.clone()) })) }); div() .id(self.id) .w_full() .flex() .flex_col() .text_xs() .line_height(px(16.0)) .text_color(theme.muted_foreground) .child( div() .flex() .children(left_axis) .child( div() .relative() .flex_1() .h(height) .child(grow_in(div().absolute().size_full(), plot, progress, grow_key, if self.kind == ChartKind::Bar { BAR_GROW } else { GROW })) .child(bands) .children(tooltip), ), ) .children(bottom_axis) .children(legend) } } #[derive(Clone, Copy)] struct PlotStyle { kind: ChartKind, stacked: bool, horizontal: bool, curve: Curve, dots: bool, gradient: bool, labels: bool, category_labels: bool, inside_labels: bool, active: Option<usize>, bar_radius: Pixels, } /// How far a chart's draw-in has run, and the points it runs from. struct Motion<'a> { t: f32, from: &'a [SeriesPoints], painted: &'a RefCell<Vec<SeriesPoints>>, } struct PlotData<'a> { spans: &'a [Vec<Option<Span>>], visible: &'a [bool], colors: &'a [Vec<Hsla>], base_colors: &'a [Hsla], ticks: &'a [f64], categories: &'a [SharedString], } /// Where text sits relative to the point it's painted at. #[derive(Clone, Copy)] enum Anchor { /// Centered above the point. Above, /// Centered below the point. Below, /// Starting at the point, vertically centered on it. Right, /// Ending at the point, vertically centered on it. Left, } /// Paints one line of 12px text on the canvas, such as a value label. fn paint_text(window: &mut Window, cx: &mut App, text: SharedString, x: f32, y: f32, anchor: Anchor, color: Hsla) { let font_size = px(12.0); let run = TextRun { len: text.len(), font: window.text_style().font(), color, background_color: None, underline: None, strikethrough: None, }; let line = window.text_system().shape_line(text, font_size, &[run], None); let width = f32::from(line.width); let height = 16.0; let (left, top) = match anchor { Anchor::Above => (x - width / 2.0, y - height - 4.0), Anchor::Below => (x - width / 2.0, y + 4.0), Anchor::Right => (x, y - height / 2.0), Anchor::Left => (x - width, y - height / 2.0), }; line.paint(point(px(left), px(top)), px(height), TextAlign::Left, None, window, cx).ok(); } #[allow(clippy::too_many_arguments)] fn paint_plot( window: &mut Window, cx: &mut App, bounds: Bounds<Pixels>, style: PlotStyle, scale: LinearScale, hovered: Option<usize>, data: PlotData, motion: Motion, value_text: &dyn Fn(f64) -> SharedString, theme: &Theme, ) { let PlotStyle { kind, stacked, horizontal, curve, dots, gradient, labels, category_labels, inside_labels, active, bar_radius } = style; let PlotData { spans, visible, colors, base_colors, ticks, categories } = data; let count = spans.first().map_or(0, Vec::len); let ox = f32::from(bounds.origin.x); let oy = f32::from(bounds.origin.y); let width = f32::from(bounds.size.width); let height = f32::from(bounds.size.height); let rect = |x0: f32, y0: f32, x1: f32, y1: f32| { Bounds::from_corners(point(px(x0.min(x1)), px(y0.min(y1))), point(px(x0.max(x1)), px(y0.max(y1)))) }; let shown: Vec<usize> = (0..spans.len()).filter(|&s| visible[s]).collect(); if horizontal { // Values run left to right, categories top to bottom. let bands = BandScale { count, length: height }; let x = |value: f64| ox + width * (1.0 - scale.ratio(value)); for &tick in ticks { let left = x(tick).round().min(ox + width - 1.0); window.paint_quad(fill(rect(left, oy, left + 1.0, oy + height), theme.border)); } if let Some(ix) = hovered { let y0 = oy + bands.start(ix); window.paint_quad(fill(rect(ox, y0, ox + width, y0 + bands.band()), theme.muted)); } let group = bands.band() * (1.0 - 2.0 * BAND_GAP); let slots = if stacked { 1.0 } else { shown.len().max(1) as f32 }; let bar = ((group - BAR_GAP * (slots - 1.0)) / slots).max(1.0); for ix in 0..count { for (slot, &s) in shown.iter().enumerate() { let Some(span) = spans[s][ix] else { continue }; let slot = if stacked { 0 } else { slot }; let y0 = oy + bands.start(ix) + bands.band() * BAND_GAP + (bar + BAR_GAP) * slot as f32; let (x0, x1) = (x(span.lo), x(span.hi)); let color = colors[s][ix]; window.paint_quad(fill(rect(x0, y0, x1, y0 + bar), color).corner_radii(bar_radius)); if inside_labels && slot == 0 { paint_text(window, cx, categories[ix].clone(), x0 + 8.0, y0 + bar / 2.0, Anchor::Right, theme.background); } if labels { let end = if span.at < 0.0 { x0 } else { x1 }; let (at, anchor) = if span.at < 0.0 { (end - 6.0, Anchor::Left) } else { (end + 6.0, Anchor::Right) }; paint_text(window, cx, value_text(span.at), at, y0 + bar / 2.0, anchor, theme.foreground); } } } return; } let bands = BandScale { count, length: width }; let y = |value: f64| oy + height * scale.ratio(value); let x = |ix: usize| ox + bands.center(ix); // Grid lines are 1px quads, not stroked paths, so they stay crisp on every backend. for &tick in ticks { let top = y(tick).round().min(oy + height - 1.0); window.paint_quad(fill(rect(ox, top, ox + width, top + 1.0), theme.border)); } if let Some(ix) = hovered { if kind == ChartKind::Bar { let x0 = ox + bands.start(ix); window.paint_quad(fill(rect(x0, oy, x0 + bands.band(), oy + height), theme.muted)); } else { let cx = x(ix).floor(); window.paint_quad(fill(rect(cx, oy, cx + 1.0, oy + height), theme.border)); } } match kind { ChartKind::Bar => { let group = bands.band() * (1.0 - 2.0 * BAND_GAP); let slots = if stacked { 1.0 } else { shown.len().max(1) as f32 }; let bar = ((group - BAR_GAP * (slots - 1.0)) / slots).max(1.0); let top_round = Corners { top_left: bar_radius, top_right: bar_radius, ..Default::default() }; let bottom_round = Corners { bottom_left: bar_radius, bottom_right: bar_radius, ..Default::default() }; for ix in 0..count { // In a stack only the outermost segments get rounded ends. let top = shown.iter().rev().find(|&&s| spans[s][ix].is_some_and(|span| span.hi > 0.0)).copied(); let bottom = shown.iter().rev().find(|&&s| spans[s][ix].is_some_and(|span| span.lo < 0.0)).copied(); for (slot, &s) in shown.iter().enumerate() { let Some(span) = spans[s][ix] else { continue }; let slot = if stacked { 0 } else { slot }; let x0 = ox + bands.start(ix) + bands.band() * BAND_GAP + (bar + BAR_GAP) * slot as f32; let corners = match (stacked, span.hi > 0.0) { (false, true) => top_round, (false, false) => bottom_round, (true, _) if top == Some(s) && span.hi > 0.0 => top_round, (true, _) if bottom == Some(s) && span.lo < 0.0 => bottom_round, _ => Corners::default(), }; let color = colors[s][ix]; let quad = fill(rect(x0, y(span.hi), x0 + bar, y(span.lo)), color).corner_radii(corners); window.paint_quad(if active == Some(ix) { PaintQuad { border_style: BorderStyle::Dashed, ..quad.background(color.opacity(0.8)).border_widths(px(2.0)).border_color(color) } } else { quad }); // In a stack only the top segment is labeled, with the category's total. if labels && (!stacked || top == Some(s)) { let (at, anchor) = if span.at < 0.0 { (y(span.lo), Anchor::Below) } else { (y(span.hi), Anchor::Above) }; paint_text(window, cx, value_text(span.at), x0 + bar / 2.0, at, anchor, theme.foreground); } } } } ChartKind::Line | ChartKind::Area => { // A stacked area's floor is the far end of its segment (the series below it); a // plain area's is zero. let floor = |span: Span| match stacked { false => 0.0, true if span.at == span.hi => span.lo, true => span.hi, }; let Motion { t, from, painted } = motion; let animating = t < 1.0; // Each series' points this frame. A series that was on screen before the data // changed moves from its old points, matched by index the way Recharts matches // them when the count changes; any other series is revealed by a clip below. let frame: Vec<(usize, Vec<Option<[f32; 3]>>, bool)> = shown .iter() .map(|&s| { let prev = from.get(s).and_then(Option::as_ref).filter(|prev| animating && !prev.is_empty()); let points = (0..count) .map(|ix| { let span = spans[s][ix]?; let next = [x(ix), y(span.at), y(floor(span))]; let old = prev.and_then(|prev| prev[ix * prev.len() / count]); Some(match old { Some([fx, fy, ff]) => { let old = [ox + fx * width, oy + fy * height, oy + ff * height]; [0, 1, 2].map(|k| old[k] + (next[k] - old[k]) * t) } None => next, }) }) .collect(); (s, points, animating && prev.is_none()) }) .collect(); { let mut painted = painted.borrow_mut(); painted.clear(); painted.resize(spans.len(), None); for (s, points, _) in &frame { let normal = |p: [f32; 3]| [(p[0] - ox) / width, (p[1] - oy) / height, (p[2] - oy) / height]; painted[*s] = Some(points.iter().map(|p| p.map(normal)).collect()); } } let curves: Vec<(usize, Vec<Vec<(usize, (f32, f32), (f32, f32))>>, Option<Bounds<Pixels>>)> = frame .iter() .map(|(s, points, reveal)| { let mut runs = vec![Vec::new()]; for (ix, point) in points.iter().enumerate() { match point { Some([px_, at, fl]) => runs.last_mut().map_or((), |run| run.push((ix, (*px_, *at), (*px_, *fl)))), None => runs.push(Vec::new()), } } runs.retain(|run| !run.is_empty()); let clip = reveal.then(|| { let tops: Vec<Vec<(f32, f32)>> = runs.iter().map(|run| run.iter().map(|(_, at, _)| *at).collect()).collect(); let first = tops.first().and_then(|run| run.first()).map_or(ox, |p| p.0); let last = tops.last().and_then(|run| run.last()).map_or(ox + width, |p| p.0); let edge = if kind == ChartKind::Area { first + (last - first) * t } else { drawn_to(&tops, t) }; rect(first, oy - DOT_SIZE, edge, oy + height + DOT_SIZE) }); (*s, runs, clip) }) .collect(); let clipped = |window: &mut Window, clip: Option<Bounds<Pixels>>, paint: &mut dyn FnMut(&mut Window)| match clip { Some(bounds) => window.with_content_mask(Some(ContentMask { bounds }), |window| paint(window)), None => paint(window), }; // Every fill goes down before any line, so no area covers another series' line. if kind == ChartKind::Area { for (s, runs, clip) in &curves { for run in runs { let upper: Vec<(f32, f32)> = run.iter().map(|(_, at, _)| *at).collect(); let mut lower: Vec<(f32, f32)> = run.iter().map(|(_, _, floor)| *floor).collect(); lower.reverse(); let (Some(first), Some(lower_start)) = (upper.first(), lower.first()) else { continue }; let mut builder = PathBuilder::fill(); builder.move_to(point(px(first.0), px(first.1))); trace(&mut builder, &upper, curve); builder.line_to(point(px(lower_start.0), px(lower_start.1))); trace(&mut builder, &lower, curve); builder.close(); if let Ok(path) = builder.build() { let color = base_colors[*s]; let background: Background = if gradient { linear_gradient(180.0, linear_color_stop(color.opacity(0.8), 0.0), linear_color_stop(color.opacity(0.1), 1.0)) } else { color.opacity(AREA_OPACITY).into() }; clipped(window, *clip, &mut |window| window.paint_path(path.clone(), background)); } } } } for (s, runs, clip) in &curves { for run in runs { let upper: Vec<(f32, f32)> = run.iter().map(|(_, at, _)| *at).collect(); let Some(first) = upper.first() else { continue }; let mut builder = PathBuilder::fill().with_style(PathStyle::Stroke(StrokeOptions { line_width: LINE_WIDTH, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Default::default() })); builder.move_to(point(px(first.0), px(first.1))); trace(&mut builder, &upper, curve); if let Ok(path) = builder.build() { clipped(window, *clip, &mut |window| window.paint_path(path.clone(), base_colors[*s])); } // Recharts clips an area's dots with its fill but shows a line's at once. let dot_clip = if kind == ChartKind::Area { *clip } else { None }; for &(ix, (cx_, cy), _) in run { if dots { clipped(window, dot_clip, &mut |window| paint_dot(window, cx_, cy, SMALL_DOT, colors[*s][ix], None)); } if labels { let text = if category_labels { categories[ix].clone() } else { value_text(spans[*s][ix].map_or(0.0, |span| span.at)) }; paint_text(window, cx, text, cx_, cy - 4.0, Anchor::Above, theme.foreground); } } } } if let Some(ix) = hovered { for &s in &shown { let Some(span) = spans[s][ix] else { continue }; paint_dot(window, x(ix), y(span.at), DOT_SIZE, colors[s][ix], Some(theme.background)); } } } } } /// How far right a line is drawn once `t` of its length is: Recharts draws lines in with a /// growing dash, so steep stretches take longer than flat ones. Measured along the points. fn drawn_to(runs: &[Vec<(f32, f32)>], t: f32) -> f32 { let segments: Vec<((f32, f32), (f32, f32))> = runs.iter().flat_map(|run| run.windows(2).map(|w| (w[0], w[1]))).collect(); let length = |(a, b): &((f32, f32), (f32, f32))| (b.0 - a.0).hypot(b.1 - a.1); let total: f32 = segments.iter().map(length).sum(); let mut left = total * t; for segment in &segments { let piece = length(segment); if left <= piece { let (a, b) = segment; return a.0 + (b.0 - a.0) * if piece > 0.0 { left / piece } else { 1.0 }; } left -= piece; } segments.last().map_or(f32::MAX, |(_, b)| b.0) } /// A round dot; with `ring`, outlined in the background color so it stands off the line. fn paint_dot(window: &mut Window, cx: f32, cy: f32, size: f32, color: Hsla, ring: Option<Hsla>) { let half = size / 2.0; let quad = fill(Bounds::from_corners(point(px(cx - half), px(cy - half)), point(px(cx + half), px(cy + half))), color) .corner_radii(px(half)); window.paint_quad(match ring { Some(ring) => quad.border_widths(px(2.0)).border_color(ring), None => quad, }); } /// Room left around a pie so the hovered slice can grow outward. const HOVER_GROW: f32 = 6.0; /// Gap between slices, in radians at the outer edge. const PIE_PAD: f32 = 0.012; /// Extra room around a pie whose values are written outside it. const LABEL_ROOM: f32 = 22.0; pub struct Slice { label: SharedString, value: f64, color: Option<Hsla>, } impl Slice { pub fn new(label: impl Into<SharedString>, value: f64) -> Self { Self { label: label.into(), value, color: None } } pub fn color(mut self, color: Hsla) -> Self { self.color = Some(color); self } } /// One ring of slices: its values, colors and where each slice ends, clockwise from 12 o'clock. #[derive(Clone)] struct Ring { labels: Vec<SharedString>, values: Vec<f64>, colors: Vec<Hsla>, ends: Vec<f32>, } impl Ring { fn new(slices: &[Slice], palette: &[Hsla; 5]) -> Self { // Negative or non-finite values count as zero, keeping slice indexes aligned. let values: Vec<f64> = slices.iter().map(|slice| if slice.value.is_finite() { slice.value.max(0.0) } else { 0.0 }).collect(); let total: f64 = values.iter().sum(); let ends = values .iter() .scan(0.0, |acc, v| { *acc += if total > 0.0 { (v / total) as f32 * TAU } else { 0.0 }; Some(*acc) }) .collect(); Self { labels: slices.iter().map(|slice| slice.label.clone()).collect(), colors: slices.iter().enumerate().map(|(ix, slice)| slice.color.unwrap_or(palette[ix % palette.len()])).collect(), values, ends, } } fn total(&self) -> f64 { self.values.iter().sum() } } /// A pie, or a donut with the total in its middle. #[derive(IntoElement)] pub struct PieChart { id: ElementId, slices: Vec<Slice>, rings: Vec<Vec<Slice>>, size: Pixels, inner_radius: f32, caption: SharedString, legend: bool, separator: bool, labels: bool, inside_labels: bool, active: Option<usize>, format: Option<Formatter>, } impl PieChart { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), slices: Vec::new(), rings: Vec::new(), size: px(200.0), inner_radius: 0.0, caption: "Total".into(), legend: true, separator: true, labels: false, inside_labels: false, active: None, format: None, } } pub fn slice(mut self, slice: Slice) -> Self { self.slices.push(slice); self } /// Adds a ring of slices around the pie, for comparing two breakdowns of the same whole. pub fn ring(mut self, slices: impl IntoIterator<Item = Slice>) -> Self { self.rings.push(slices.into_iter().collect()); self } pub fn size(mut self, size: Pixels) -> Self { self.size = size; self } /// Hole size as a share of the radius: 0 is a pie, 0.6 a donut. A donut shows the total /// in the middle, or the hovered or active slice. pub fn inner_radius(mut self, ratio: f32) -> Self { self.inner_radius = ratio.clamp(0.0, 0.95); self } /// The word under the total in a donut's center. pub fn caption(mut self, caption: impl Into<SharedString>) -> Self { self.caption = caption.into(); self } pub fn legend(mut self, legend: bool) -> Self { self.legend = legend; self } /// Whether a thin gap separates the slices. On by default. pub fn separator(mut self, separator: bool) -> Self { self.separator = separator; self } /// Writes each slice's value just outside it. pub fn labels(mut self, labels: bool) -> Self { self.labels = labels; self } /// Writes each slice's name inside it. pub fn inside_labels(mut self, inside: bool) -> Self { self.inside_labels = inside; self } /// Pulls one slice out, as if hovered, and shows it in a donut's middle. pub fn active(mut self, index: usize) -> Self { self.active = Some(index); self } pub fn format(mut self, format: impl Fn(f64) -> SharedString + 'static) -> Self { self.format = Some(Rc::new(format)); self } } impl RenderOnce for PieChart { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let hover = window.use_keyed_state(self.id.clone(), cx, |_, _| None::<usize>); let theme = cx.theme().clone(); let palette = palette(cx); let pie = Ring::new(&self.slices, &palette); let rings: Vec<Ring> = self.rings.iter().map(|slices| Ring::new(slices, &palette)).collect(); let highlighted = hover.read(cx).or(self.active).filter(|&ix| ix < self.slices.len()); let value_text: Rc<dyn Fn(f64) -> SharedString> = { let format = self.format.clone(); Rc::new(move |value: f64| format.as_ref().map_or_else(|| default_value_text(value), |format| format(value))) }; // The pie keeps room outside for value labels, and a stacked pie shares its radius with // its rings: the pie takes the inner half, each ring an equal band outside it. let room = HOVER_GROW + if self.labels { LABEL_ROOM } else { 0.0 }; let ring_count = rings.len(); let inner_ratio = self.inner_radius; let radii = move |b: Bounds<Pixels>| { let outer = f32::from(b.size.width.min(b.size.height)) / 2.0 - room; let pie_outer = if ring_count == 0 { outer } else { outer * 0.55 }; (outer, pie_outer, pie_outer * inner_ratio) }; // The canvas reports where it was laid out, so pointer positions can become angles. let bounds = Rc::new(Cell::new(None::<Bounds<Pixels>>)); let progress = Rc::new(Cell::new(1.0f32)); let grow_key = data_key( pie.values.iter().chain(rings.iter().flat_map(|ring| ring.values.iter())), ring_count, ); let plot = { let (bounds, pie, progress) = (bounds.clone(), pie.clone(), progress.clone()); let value_text = value_text.clone(); let (separator, labels, inside_labels) = (self.separator, self.labels, self.inside_labels); // Names inside slices are white: chart colors are mid-tone in both themes, so the // page background (near-black in dark mode) would vanish on them. let on_slice = hsla(0.0, 0.0, 1.0, 0.95); let foreground = theme.foreground; canvas( move |b, _, _| bounds.set(Some(b)), move |b, _, window, cx| { let center = (f32::from(b.center().x), f32::from(b.center().y)); let (outer, pie_outer, pie_inner) = radii(b); let pad = |ring: &Ring| if separator && ring.ends.len() > 1 { PIE_PAD } else { 0.0 }; // Slices sweep in clockwise from 12 o'clock; labels wait for the end. let t = progress.get(); let (labels, inside_labels) = (labels && t >= 1.0, inside_labels && t >= 1.0); let mut start = 0.0; for (ix, end) in pie.ends.iter().map(|end| end * t).enumerate() { let grow = if highlighted == Some(ix) { HOVER_GROW } else { 0.0 }; if let Some(path) = sector(center, pie_inner, pie_outer + grow, start + pad(&pie), end - pad(&pie)) { window.paint_path(path, pie.colors[ix]); } let mid = (start + end) / 2.0; let at = |r: f32| (center.0 + r * mid.sin(), center.1 - r * mid.cos()); if inside_labels && end > start { let (x, y) = at((pie_inner + pie_outer) / 2.0); paint_text(window, cx, pie.labels[ix].clone(), x, y + 8.0, Anchor::Above, on_slice); } if labels && end > start { // Outside the slice, on the side the slice points to. let (x, y) = at(pie_outer + grow + 8.0); let anchor = if mid.sin() >= 0.0 { Anchor::Right } else { Anchor::Left }; paint_text(window, cx, value_text(pie.values[ix]), x, y, anchor, foreground); } start = end; } // Each ring sits in an equal band between the pie and the outer edge. let band = if ring_count == 0 { 0.0 } else { (outer - pie_outer) / ring_count as f32 }; for (k, ring) in rings.iter().enumerate() { let inner = pie_outer + band * k as f32 + 6.0; let mut start = 0.0; for (ix, end) in ring.ends.iter().map(|end| end * t).enumerate() { if let Some(path) = sector(center, inner, inner + band - 6.0, start + pad(ring), end - pad(ring)) { window.paint_path(path, ring.colors[ix]); } start = end; } } }, ) .size_full() }; let center = (self.inner_radius > 0.0).then(|| { let (value, caption) = match highlighted { Some(ix) => (pie.values[ix], pie.labels[ix].clone()), None => (pie.total(), self.caption.clone()), }; div() .absolute() .inset_0() .flex() .flex_col() .items_center() .justify_center() .child( div() .text_size(px(24.0)) .line_height(px(30.0)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme.foreground) .child(value_text(value)), ) .child(div().text_xs().text_color(theme.muted_foreground).child(caption)) }); let pointer = { let (hover, ends) = (hover.clone(), pie.ends.clone()); move |position: gpui::Point<Pixels>, cx: &mut App| { let Some(b) = bounds.get() else { return }; let dx = f32::from(position.x - b.center().x); let dy = f32::from(position.y - b.center().y); let (_, pie_outer, pie_inner) = radii(b); let r = dx.hypot(dy); let next = if r > pie_outer + HOVER_GROW || r < pie_inner { None } else { slice_at(dx.atan2(-dy).rem_euclid(TAU), &ends) }; hover.update(cx, |hover, cx| { if *hover != next { *hover = next; cx.notify(); } }); } }; let clear = hover.clone(); let legend = self.legend.then(|| { div().flex().flex_wrap().justify_center().gap_x_4().gap_y_1().pt_3().children( self.slices.iter().enumerate().map(|(ix, slice)| { div() .flex() .items_center() .gap(px(6.0)) .text_color(theme.foreground) .when(highlighted.is_some_and(|h| h != ix), |this| this.opacity(0.5)) .child(div().size(px(8.0)).flex_none().rounded(px(2.0)).bg(pie.colors[ix])) .child(slice.label.clone()) }), ) }); div() .id(self.id) .flex() .flex_col() .items_center() .text_xs() .line_height(px(16.0)) .text_color(theme.muted_foreground) .child( div() .id("pie-plot") .relative() .size(self.size) .on_mouse_move(move |event, _, cx| pointer(event.position, cx)) .on_hover(move |hovered, _, cx| { if !*hovered { clear.update(cx, |hover, cx| { *hover = None; cx.notify(); }); } }) .child(grow_in(div().size_full(), plot, progress, grow_key, GROW)) .children(center), ) .children(legend) } } /// The web behind a radar chart. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum RadarGrid { /// Polygons through each tick, joined by spokes, as Recharts draws by default. #[default] Polygon, /// Circles through each tick, joined by spokes. Circle, /// Only the spokes. Spokes, /// Nothing behind the data. None, } /// Values around a circle, one spoke per category: good for comparing profiles. #[derive(IntoElement)] pub struct RadarChart { id: ElementId, categories: Vec<SharedString>, series: Vec<ChartSeries>, size: Pixels, grid: RadarGrid, grid_fill: bool, fill: bool, dots: bool, labels: bool, legend: bool, format: Option<Formatter>, } impl RadarChart { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), categories: Vec::new(), series: Vec::new(), size: px(240.0), grid: RadarGrid::Polygon, grid_fill: false, fill: true, dots: false, labels: false, legend: true, format: None, } } pub fn categories<S: Into<SharedString>>(mut self, categories: impl IntoIterator<Item = S>) -> Self { self.categories = categories.into_iter().map(Into::into).collect(); self } pub fn series(mut self, series: ChartSeries) -> Self { self.series.push(series); self } pub fn size(mut self, size: Pixels) -> Self { self.size = size; self } pub fn grid(mut self, grid: RadarGrid) -> Self { self.grid = grid; self } /// Shades the grid's rings in alternating tints. pub fn grid_fill(mut self, grid_fill: bool) -> Self { self.grid_fill = grid_fill; self } /// Whether each series' shape is filled. Off draws only its outline. pub fn fill(mut self, fill: bool) -> Self { self.fill = fill; self } pub fn dots(mut self, dots: bool) -> Self { self.dots = dots; self } /// Writes each category's values beside its spoke label. pub fn labels(mut self, labels: bool) -> Self { self.labels = labels; self } pub fn legend(mut self, legend: bool) -> Self { self.legend = legend; self } pub fn format(mut self, format: impl Fn(f64) -> SharedString + 'static) -> Self { self.format = Some(Rc::new(format)); self } } /// Room around a radar chart for its spoke labels. const SPOKE_LABEL_ROOM: f32 = 34.0; impl RenderOnce for RadarChart { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let hover = window.use_keyed_state(self.id.clone(), cx, |_, _| None::<usize>); let theme = cx.theme().clone(); let palette = palette(cx); let count = self.categories.len(); let hovered = hover.read(cx).filter(|&ix| ix < count); let colors: Vec<Hsla> = self.series.iter().enumerate().map(|(s, series)| series.color.unwrap_or(palette[s % palette.len()])).collect(); let values: Vec<Vec<f64>> = self .series .iter() .map(|series| (0..count).map(|ix| series.values.get(ix).copied().filter(|v| v.is_finite()).unwrap_or(0.0).max(0.0)).collect()) .collect(); let max = values.iter().flatten().fold(0.0f64, |max, &v| max.max(v)); let scale = LinearScale::nice(0.0, max, TICKS); let value_text: Rc<dyn Fn(f64) -> SharedString> = { let format = self.format.clone(); Rc::new(move |value: f64| format.as_ref().map_or_else(|| default_value_text(value), |format| format(value))) }; // Spoke `ix` points straight up for the first category, then clockwise. let angle = move |ix: usize| ix as f32 / count.max(1) as f32 * TAU; let bounds = Rc::new(Cell::new(None::<Bounds<Pixels>>)); let progress = Rc::new(Cell::new(1.0f32)); let grow_key = data_key(values.iter().flatten(), count); let plot = { let progress = progress.clone(); let bounds = bounds.clone(); let (categories, values, colors, value_text) = (self.categories.clone(), values.clone(), colors.clone(), value_text.clone()); let (grid, grid_fill, fill_shapes, dots, labels) = (self.grid, self.grid_fill, self.fill, self.dots, self.labels); let (border, muted, foreground, muted_foreground, background) = (theme.border, theme.muted, theme.foreground, theme.muted_foreground, theme.background); canvas( move |b, _, _| bounds.set(Some(b)), move |b, _, window, cx| { if count < 3 { return; } let (cx_, cy) = (f32::from(b.center().x), f32::from(b.center().y)); let radius = f32::from(b.size.width.min(b.size.height)) / 2.0 - SPOKE_LABEL_ROOM; let at = |r: f32, ix: usize| (cx_ + r * angle(ix).sin(), cy - r * angle(ix).cos()); let ring = |r: f32| -> Vec<(f32, f32)> { (0..count).map(|ix| at(r, ix)).collect() }; let polygon = |points: &[(f32, f32)], filled: bool| { let mut builder = if filled { PathBuilder::fill() } else { PathBuilder::fill().with_style(PathStyle::Stroke(StrokeOptions { line_width: 1.0, ..Default::default() })) }; builder.move_to(point(px(points[0].0), px(points[0].1))); for p in &points[1..] { builder.line_to(point(px(p.0), px(p.1))); } builder.close(); builder.build().ok() }; let circle = |r: f32, filled: bool| { let mut builder = if filled { PathBuilder::fill() } else { PathBuilder::fill().with_style(PathStyle::Stroke(StrokeOptions { line_width: 1.0, ..Default::default() })) }; builder.move_to(point(px(cx_), px(cy - r))); builder.arc_to(point(px(r), px(r)), px(0.0), false, true, point(px(cx_), px(cy + r))); builder.arc_to(point(px(r), px(r)), px(0.0), false, true, point(px(cx_), px(cy - r))); builder.close(); builder.build().ok() }; // Rings from the outside in, so inner fills sit on top of outer ones. let ticks: Vec<f64> = scale.ticks().into_iter().filter(|&t| t > 0.0).collect(); for (k, &tick) in ticks.iter().enumerate().rev() { let r = radius * (1.0 - scale.ratio(tick)); if grid_fill && grid != RadarGrid::None { let tint = if k % 2 == 0 { muted } else { background }; let path = if grid == RadarGrid::Circle { circle(r, true) } else { polygon(&ring(r), true) }; if let Some(path) = path { window.paint_path(path, tint); } } let outline = match grid { RadarGrid::Polygon => polygon(&ring(r), false), RadarGrid::Circle => circle(r, false), RadarGrid::Spokes | RadarGrid::None => None, }; if let Some(path) = outline { window.paint_path(path, border); } } if grid != RadarGrid::None { for ix in 0..count { let (x, y) = at(radius, ix); let mut builder = PathBuilder::fill().with_style(PathStyle::Stroke(StrokeOptions { line_width: 1.0, ..Default::default() })); builder.move_to(point(px(cx_), px(cy))); builder.line_to(point(px(x), px(y))); if let Ok(path) = builder.build() { window.paint_path(path, border); } } } // Each shape spreads out from the center to its values. let t = progress.get(); for (s, series) in values.iter().enumerate() { let points: Vec<(f32, f32)> = series.iter().enumerate().map(|(ix, &v)| at(radius * (1.0 - scale.ratio(v)) * t, ix)).collect(); if fill_shapes { if let Some(path) = polygon(&points, true) { window.paint_path(path, colors[s].opacity(0.6)); } } let mut builder = PathBuilder::fill().with_style(PathStyle::Stroke(StrokeOptions { line_width: LINE_WIDTH, line_join: LineJoin::Round, ..Default::default() })); builder.move_to(point(px(points[0].0), px(points[0].1))); for p in &points[1..] { builder.line_to(point(px(p.0), px(p.1))); } builder.close(); if let Ok(path) = builder.build() { window.paint_path(path, colors[s]); } for (ix, &(x, y)) in points.iter().enumerate() { if dots || hovered == Some(ix) { let ring = (hovered == Some(ix)).then_some(background); paint_dot(window, x, y, if ring.is_some() { DOT_SIZE } else { SMALL_DOT }, colors[s], ring); } } } // Spoke labels: the category, and with `labels`, its values under it. for ix in 0..count { let a = angle(ix); let (x, y) = at(radius + 10.0, ix); let anchor = match (a.sin(), a.cos()) { (s, _) if s > 0.3 => Anchor::Right, (s, _) if s < -0.3 => Anchor::Left, (_, c) if c > 0.0 => Anchor::Above, _ => Anchor::Below, }; let color = if hovered == Some(ix) { foreground } else { muted_foreground }; let text = if labels { let numbers: Vec<String> = values.iter().map(|series| value_text(series[ix]).to_string()).collect(); SharedString::from(format!("{} {}", categories[ix], numbers.join(" / "))) } else { categories[ix].clone() }; paint_text(window, cx, text, x, y, anchor, color); } }, ) .size_full() }; let pointer = { let hover = hover.clone(); move |position: gpui::Point<Pixels>, cx: &mut App| { let Some(b) = bounds.get() else { return }; let dx = f32::from(position.x - b.center().x); let dy = f32::from(position.y - b.center().y); // The nearest spoke to the pointer's angle. let turn = dx.atan2(-dy).rem_euclid(TAU) / TAU; let next = (count > 0).then(|| ((turn * count as f32).round() as usize) % count); hover.update(cx, |hover, cx| { if *hover != next { *hover = next; cx.notify(); } }); } }; let clear = hover.clone(); let tooltip = hovered.map(|ix| { div() .absolute() .top_0() .right_0() .min_w(px(120.0)) .flex() .flex_col() .gap(px(6.0)) .px(px(10.0)) .py(px(8.0)) .rounded(theme.radius) .border_1() .border_color(theme.border) .bg(theme.background) .shadow_lg() .child(div().font_weight(FontWeight::MEDIUM).text_color(theme.foreground).child(self.categories[ix].clone())) .children(self.series.iter().enumerate().map(|(s, series)| { div() .flex() .items_center() .gap_2() .children(swatch(Indicator::Dot, colors[s])) .child(div().flex_1().text_color(theme.muted_foreground).child(series.label.clone())) .child(div().pl_4().font_family(MONO).text_color(theme.foreground).child(value_text(values[s][ix]))) })) }); let legend = self.legend.then(|| { div().flex().flex_wrap().justify_center().gap_4().pt_3().children(self.series.iter().enumerate().map(|(s, series)| { div() .flex() .items_center() .gap(px(6.0)) .text_color(theme.foreground) .child(div().size(px(8.0)).flex_none().rounded(px(2.0)).bg(colors[s])) .child(series.label.clone()) })) }); div() .id(self.id) .w_full() .flex() .flex_col() .items_center() .text_xs() .line_height(px(16.0)) .text_color(theme.muted_foreground) .child( div() .relative() .w_full() .flex() .justify_center() .child( div() .id("radar-plot") .relative() .size(self.size) .on_mouse_move(move |event, _, cx| pointer(event.position, cx)) .on_hover(move |hovered, _, cx| { if !*hovered { clear.update(cx, |hover, cx| { *hover = None; cx.notify(); }); } }) .child(grow_in(div().size_full(), plot, progress, grow_key, GROW)), ) .children(tooltip), ) .children(legend) } } /// Bars bent into arcs: one ring per value, or the values stacked along a single arc. #[derive(IntoElement)] pub struct RadialChart { id: ElementId, bars: Vec<Slice>, size: Pixels, start: f32, sweep: f32, inner_radius: f32, max: Option<f64>, stacked: bool, track: bool, labels: bool, center: Option<(SharedString, SharedString)>, format: Option<Formatter>, } impl RadialChart { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), bars: Vec::new(), size: px(240.0), start: 0.0, sweep: 360.0, inner_radius: 0.3, max: None, stacked: false, track: false, labels: false, center: None, format: None, } } pub fn bar(mut self, bar: Slice) -> Self { self.bars.push(bar); self } pub fn size(mut self, size: Pixels) -> Self { self.size = size; self } /// The arc the bars run along, in degrees clockwise from 12 o'clock. The default is a /// full circle; `(-90.0, 180.0)` is a half circle opening downward. pub fn arc(mut self, start_degrees: f32, sweep_degrees: f32) -> Self { self.start = start_degrees; self.sweep = sweep_degrees.clamp(1.0, 360.0); self } /// Hole size as a share of the radius. pub fn inner_radius(mut self, ratio: f32) -> Self { self.inner_radius = ratio.clamp(0.0, 0.95); self } /// The value a full arc stands for. Defaults to the largest bar, or the total when stacked. pub fn max(mut self, max: f64) -> Self { self.max = Some(max); self } /// Puts every bar end to end along one arc instead of one ring each. pub fn stacked(mut self, stacked: bool) -> Self { self.stacked = stacked; self } /// Draws each ring's full length in a muted tint behind its bar. pub fn track(mut self, track: bool) -> Self { self.track = track; self } /// Writes each bar's name at its start. pub fn labels(mut self, labels: bool) -> Self { self.labels = labels; self } /// A large value and a caption in the middle. pub fn center(mut self, value: impl Into<SharedString>, caption: impl Into<SharedString>) -> Self { self.center = Some((value.into(), caption.into())); self } pub fn format(mut self, format: impl Fn(f64) -> SharedString + 'static) -> Self { self.format = Some(Rc::new(format)); self } } impl RenderOnce for RadialChart { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme().clone(); let palette = palette(cx); let bars: Vec<(SharedString, f64, Hsla)> = self .bars .iter() .enumerate() .map(|(ix, bar)| (bar.label.clone(), if bar.value.is_finite() { bar.value.max(0.0) } else { 0.0 }, bar.color.unwrap_or(palette[ix % palette.len()]))) .collect(); let total: f64 = bars.iter().map(|bar| bar.1).sum(); let largest = bars.iter().fold(0.0f64, |max, bar| max.max(bar.1)); let max = self.max.unwrap_or(if self.stacked { total } else { largest }).max(f64::MIN_POSITIVE); let (start, sweep) = (self.start.to_radians(), self.sweep.to_radians()); let (stacked, track, labels, inner_ratio) = (self.stacked, self.track, self.labels, self.inner_radius); let muted = theme.muted; let on_bar = hsla(0.0, 0.0, 1.0, 0.95); let progress = Rc::new(Cell::new(1.0f32)); let grow_key = data_key(bars.iter().map(|bar| &bar.1), (stacked, bars.len())); let plot_progress = progress.clone(); let plot = canvas( |_, _, _| {}, move |b, _, window, cx| { // Bars sweep out from their start angle; labels wait for the end. let t = plot_progress.get(); let labels = labels && t >= 1.0; let center = (f32::from(b.center().x), f32::from(b.center().y)); let outer = f32::from(b.size.width.min(b.size.height)) / 2.0 - 4.0; let inner = outer * inner_ratio; if stacked { // One band; each bar picks up where the previous one ended. let mut at = start; if track { if let Some(path) = sector(center, inner, outer, start, start + sweep) { window.paint_path(path, muted); } } for (_, value, color) in &bars { let end = at + sweep * (*value / max) as f32 * t; if let Some(path) = sector(center, inner, outer, at, end) { window.paint_path(path, *color); } at = end; } return; } // One ring per bar, the first on the outside. let n = bars.len().max(1) as f32; let band = (outer - inner) / n; for (ix, (label, value, color)) in bars.iter().enumerate() { let r_out = outer - band * ix as f32; let r_in = r_out - band * 0.8; if track { if let Some(path) = sector(center, r_in, r_out, start, start + sweep) { window.paint_path(path, muted); } } let end = start + sweep * (*value / max) as f32 * t; if let Some(path) = sector(center, r_in, r_out, start, end) { window.paint_path(path, *color); } if labels { // Just past the bar's start, along the middle of its ring. let a = start + 0.08; let r = (r_in + r_out) / 2.0; let (x, y) = (center.0 + r * a.sin(), center.1 - r * a.cos()); paint_text(window, cx, label.clone(), x, y, Anchor::Right, on_bar); } } }, ) .size_full(); let center = self.center.map(|(value, caption)| { div() .absolute() .inset_0() .flex() .flex_col() .items_center() .justify_center() .child( div() .text_size(px(28.0)) .line_height(px(34.0)) .font_weight(FontWeight::BOLD) .text_color(theme.foreground) .child(value), ) .child(div().text_xs().text_color(theme.muted_foreground).child(caption)) }); div() .id(self.id) .w_full() .flex() .justify_center() .child(div().relative().size(self.size).child(grow_in(div().size_full(), plot, progress, grow_key, GROW)).children(center)) } } /// Scales map data values to positions. They know nothing about elements, so they work for /// any chart you draw yourself. pub mod scale { use gpui::SharedString; /// A value axis whose ends and step are round numbers (1, 2 or 5 times a power of ten). #[derive(Clone, Copy, Debug, PartialEq)] pub struct LinearScale { pub min: f64, pub max: f64, pub step: f64, } impl LinearScale { /// Covers `lo..=hi` and zero with about `ticks` round ticks. pub fn nice(lo: f64, hi: f64, ticks: usize) -> Self { // Bars and areas grow from zero, so zero is always on the axis. let (lo, hi) = (lo.min(0.0), hi.max(0.0)); // Empty or all-zero data still gets a usable 0..1 axis instead of dividing by zero. let (lo, hi) = if hi > lo { (lo, hi) } else { (0.0, 1.0) }; let step = nice_number(nice_number(hi - lo, false) / ticks.saturating_sub(1).max(1) as f64, true); Self { min: (lo / step).floor() * step, max: (hi / step).ceil() * step, step } } /// Distance from the top as a fraction of the axis: 0 at `max`, 1 at `min`. pub fn ratio(&self, value: f64) -> f32 { ((self.max - value) / (self.max - self.min)) as f32 } pub fn ticks(&self) -> Vec<f64> { let count = ((self.max - self.min) / self.step).round() as usize; // Snapped to the step's decimals, so a formatter never sees `0.6000000000000001`. let unit = 10f64.powi(self.decimals() as i32); (0..=count).map(|k| ((self.min + self.step * k as f64) * unit).round() / unit + 0.0).collect() } fn decimals(&self) -> usize { (-self.step.log10().floor()).clamp(0.0, 6.0) as usize } /// A tick label with just enough decimals to tell ticks apart. pub fn label(&self, value: f64) -> SharedString { let decimals = self.decimals(); // Rounding can leave `-0`, which would print with a minus sign. let value = if value.abs() < self.step * 1e-9 { 0.0 } else { value }; format!("{value:.decimals$}").into() } } fn nice_number(x: f64, round: bool) -> f64 { let exponent = x.log10().floor(); let fraction = x / 10f64.powf(exponent); let nice = match (round, fraction) { (true, f) if f < 1.5 => 1.0, (true, f) if f < 3.0 => 2.0, (true, f) if f < 7.0 => 5.0, (false, f) if f <= 1.0 => 1.0, (false, f) if f <= 2.0 => 2.0, (false, f) if f <= 5.0 => 5.0, _ => 10.0, }; nice * 10f64.powf(exponent) } /// Equal-width slots for categories along an axis. #[derive(Clone, Copy, Debug)] pub struct BandScale { pub count: usize, pub length: f32, } impl BandScale { pub fn band(&self) -> f32 { self.length / self.count.max(1) as f32 } pub fn start(&self, ix: usize) -> f32 { self.band() * ix as f32 } pub fn center(&self, ix: usize) -> f32 { self.band() * (ix as f32 + 0.5) } } } /// Shape generators: pixel points in, GPUI path segments out. pub mod shape { use std::f32::consts::{PI, TAU}; use gpui::{Path, PathBuilder, Pixels, Point, point, px}; /// How a line passes through its points. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum Curve { /// Smooth, but never overshooting above a peak or below zero between points /// (Fritsch-Carlson, Recharts' `monotone`). #[default] Monotone, /// Straight segments. Linear, /// Flat until halfway, then a vertical jump. Step, } /// Continues `builder` from `points[0]` through the rest of `points`. pub fn trace(builder: &mut PathBuilder, points: &[(f32, f32)], curve: Curve) { match curve { Curve::Linear => { for &(x, y) in points.iter().skip(1) { builder.line_to(pt(x, y)); } } Curve::Step => { for pair in points.windows(2) { let ((x0, y0), (x1, y1)) = (pair[0], pair[1]); let mid = (x0 + x1) / 2.0; builder.line_to(pt(mid, y0)); builder.line_to(pt(mid, y1)); builder.line_to(pt(x1, y1)); } } Curve::Monotone => { let tangents = monotone_tangents(points); for i in 0..points.len().saturating_sub(1) { let ((x0, y0), (x1, y1)) = (points[i], points[i + 1]); let third = (x1 - x0) / 3.0; builder.cubic_bezier_to( pt(x1, y1), pt(x0 + third, y0 + tangents[i] * third), pt(x1 - third, y1 - tangents[i + 1] * third), ); } } } } fn monotone_tangents(points: &[(f32, f32)]) -> Vec<f32> { let n = points.len(); let mut tangents = vec![0.0; n]; if n < 2 { return tangents; } let slopes: Vec<f32> = points .windows(2) .map(|w| { let dx = w[1].0 - w[0].0; if dx == 0.0 { 0.0 } else { (w[1].1 - w[0].1) / dx } }) .collect(); tangents[0] = slopes[0]; tangents[n - 1] = slopes[n - 2]; for i in 1..n - 1 { tangents[i] = if slopes[i - 1] * slopes[i] <= 0.0 { 0.0 } else { (slopes[i - 1] + slopes[i]) / 2.0 }; } for (i, &slope) in slopes.iter().enumerate() { if slope == 0.0 { tangents[i] = 0.0; tangents[i + 1] = 0.0; continue; } let (a, b) = (tangents[i] / slope, tangents[i + 1] / slope); let length = a.hypot(b); if length > 3.0 { let t = 3.0 / length; tangents[i] = t * a * slope; tangents[i + 1] = t * b * slope; } } tangents } /// A pie or donut slice. Angles are radians clockwise from 12 o'clock; `inner` 0 makes a wedge. pub fn sector(center: (f32, f32), inner: f32, outer: f32, start: f32, end: f32) -> Option<Path> { let sweep = end - start; if sweep <= 0.0 || outer <= 0.0 { return None; } // An arc can't end where it starts, so a full ring is drawn as two halves. if sweep >= TAU - 1e-4 { let mut builder = PathBuilder::fill(); ring(&mut builder, center, outer, true); if inner > 0.0 { ring(&mut builder, center, inner, false); } return builder.build().ok(); } let at = |r: f32, a: f32| pt(center.0 + r * a.sin(), center.1 - r * a.cos()); let large = sweep > PI; let mut builder = PathBuilder::fill(); builder.move_to(at(outer, start)); builder.arc_to(pt(outer, outer), px(0.0), large, true, at(outer, end)); if inner > 0.0 { builder.line_to(at(inner, end)); builder.arc_to(pt(inner, inner), px(0.0), large, false, at(inner, start)); } else { builder.line_to(pt(center.0, center.1)); } builder.close(); builder.build().ok() } fn ring(builder: &mut PathBuilder, (cx, cy): (f32, f32), r: f32, clockwise: bool) { builder.move_to(pt(cx, cy - r)); builder.arc_to(pt(r, r), px(0.0), false, clockwise, pt(cx, cy + r)); builder.arc_to(pt(r, r), px(0.0), false, clockwise, pt(cx, cy - r)); builder.close(); } /// Which slice an angle falls in, given the slices' end angles in order. pub fn slice_at(angle: f32, ends: &[f32]) -> Option<usize> { ends.iter().position(|&end| angle <= end) } fn pt(x: f32, y: f32) -> Point<Pixels> { point(px(x), px(y)) } } // --------------------------------------------------------------------------------------------- // Markets: an order book ladder and a portfolio chart. // // Ported from spectrum-ui's Order Book and Portfolio Chart blocks // (https://github.com/arihantcodes/spectrum-ui, Apache-2.0), including its seeded sample data, // so the numbers match the originals. // --------------------------------------------------------------------------------------------- /// Rising, bid and profit green, as in spectrum-ui. pub fn market_up(theme: &Theme) -> Hsla { if is_dark(theme) { rgb_hex(0x34d399) } else { rgb_hex(0x059669) } } /// Falling, ask and loss red, as in spectrum-ui. pub fn market_down(theme: &Theme) -> Hsla { if is_dark(theme) { rgb_hex(0xfb7185) } else { rgb_hex(0xe11d48) } } fn is_dark(theme: &Theme) -> bool { theme.background.l < 0.5 } fn rgb_hex(hex: u32) -> Hsla { gpui::rgb(hex).into() } /// A small seeded random generator (mulberry32), so sample data is the same on every load and /// matches spectrum-ui's JavaScript bit for bit. pub fn mulberry32(seed: u32) -> impl FnMut() -> f64 { let mut a = seed; move || { a = a.wrapping_add(0x6d2b_79f5); let mut t = (a ^ (a >> 15)).wrapping_mul(1 | a); t = t.wrapping_add((t ^ (t >> 7)).wrapping_mul(61 | t)) ^ t; f64::from(t ^ (t >> 14)) / 4_294_967_296.0 } } fn round2(value: f64) -> f64 { (value * 100.0).round() / 100.0 } /// Groups an integer's digits in threes: `1234567` becomes `1,234,567`. fn group_thousands(digits: &str) -> String { let mut out = String::with_capacity(digits.len() + digits.len() / 3); for (ix, ch) in digits.chars().enumerate() { if ix > 0 && (digits.len() - ix) % 3 == 0 { out.push(','); } out.push(ch); } out } /// `$3,842.60`: two decimals, or four under a dollar. pub fn format_money(value: f64) -> SharedString { let digits = if value.abs() >= 1.0 { 2 } else { 4 }; let text = format!("{:.*}", digits, value.abs()); let (int, frac) = text.split_once('.').unwrap_or((&text, "")); let sign = if value < 0.0 { "-" } else { "" }; format!("{sign}${}.{frac}", group_thousands(int)).into() } /// `$96.82K`: thousands, millions and billions with up to two decimals. pub fn format_money_compact(value: f64) -> SharedString { let sign = if value < 0.0 { "-" } else { "" }; format!("{sign}${}", compact_number(value.abs(), 2)).into() } /// `8.3K`, `816`: a size with a K, M or B suffix and at most `decimals` decimals. fn compact_number(value: f64, decimals: usize) -> String { let (scaled, suffix) = match value.abs() { v if v >= 1e12 => (value / 1e12, "T"), v if v >= 1e9 => (value / 1e9, "B"), v if v >= 1e6 => (value / 1e6, "M"), v if v >= 1e3 => (value / 1e3, "K"), _ => (value, ""), }; let mut text = format!("{scaled:.decimals$}"); if text.contains('.') { text = text.trim_end_matches('0').trim_end_matches('.').to_string(); } format!("{text}{suffix}") } /// An order size: one decimal from 100 up, two below, as spectrum-ui shows them. fn compact_size(value: f64) -> String { compact_number(value, if value >= 100.0 { 1 } else { 2 }) } /// `+45.44%`, `−5.33%` (with a true minus sign). pub fn format_signed_pct(value: f64) -> SharedString { let sign = if value > 0.0 { "+" } else if value < 0.0 { "\u{2212}" } else { "" }; format!("{sign}{:.2}%", value.abs()).into() } const MONTH_NAMES: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /// The calendar date of a day counted from 1970-01-01 (Howard Hinnant's `civil_from_days`). fn civil_from_days(day: i64) -> (i64, usize, i64) { let z = day + 719_468; let era = z.div_euclid(146_097); let doe = z - era * 146_097; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = yoe + era * 400 + i64::from(m <= 2); (y, (m - 1) as usize, d) } /// Days from 1970-01-01 to a calendar date (`month` counts from 1). pub fn days_from_civil(year: i64, month: u32, day: u32) -> i64 { let (m, d) = (i64::from(month), i64::from(day)); let y = if m <= 2 { year - 1 } else { year }; let era = y.div_euclid(400); let yoe = y - era * 400; let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146_097 + doe - 719_468 } /// `Aug 21`. pub fn date_short(day: i64) -> SharedString { let (_, month, d) = civil_from_days(day); format!("{} {d}", MONTH_NAMES[month]).into() } /// `Aug 21, 2026`. pub fn date_full(day: i64) -> SharedString { let (y, month, d) = civil_from_days(day); format!("{} {d}, {y}", MONTH_NAMES[month]).into() } /// Round tick values for a price axis, about `target` of them (spectrum-ui's `niceTicks`). fn price_ticks(lo: f64, hi: f64, target: usize) -> Vec<f64> { if !lo.is_finite() || !hi.is_finite() || hi <= lo { return vec![lo]; } let raw = (hi - lo) / target as f64; let magnitude = 10f64.powf(raw.log10().floor()); let norm = raw / magnitude; let step = magnitude * if norm >= 7.5 { 10.0 } else if norm >= 3.5 { 5.0 } else if norm >= 2.25 { 2.5 } else if norm >= 1.5 { 2.0 } else { 1.0 }; let mut ticks = Vec::new(); let mut value = (lo / step).ceil() * step; while value <= hi + step * 0.001 { ticks.push((value / step).round() * step); value += step; } ticks } /// A price on an axis: compact from $10K up. fn axis_price(value: f64) -> SharedString { if value.abs() >= 10_000.0 { format_money_compact(value) } else { format_money(value) } } /// Paints one line of monospaced text with its left edge at `x` and its middle at `y`, or with /// its center at `x` when `centered`. Returns the text's width. #[allow(clippy::too_many_arguments)] fn paint_mono( window: &mut Window, cx: &mut App, text: SharedString, x: f32, y: f32, size: f32, color: Hsla, weight: FontWeight, centered: bool, ) -> f32 { let run = TextRun { len: text.len(), font: gpui::Font { weight, ..gpui::font(MONO) }, color, background_color: None, underline: None, strikethrough: None, }; let line = window.text_system().shape_line(text, px(size), &[run], None); let width = f32::from(line.width); let line_height = size * 1.4; let left = if centered { x - width / 2.0 } else { x }; line.paint(point(px(left), px(y - line_height / 2.0)), px(line_height), TextAlign::Left, None, window, cx).ok(); width } /// Adds `points` to a stroke path as dashes `on` long with `off` gaps, measured along the line. fn dash(builder: &mut PathBuilder, points: &[(f32, f32)], on: f32, off: f32) { let period = on + off; let mut walked = 0.0f32; for pair in points.windows(2) { let ((x0, y0), (x1, y1)) = (pair[0], pair[1]); let length = (x1 - x0).hypot(y1 - y0); if length <= f32::EPSILON { continue; } let mut at = 0.0; while at < length { let phase = (walked + at) % period; let (drawing, left) = if phase < on { (true, on - phase) } else { (false, period - phase) }; let end = (at + left).min(length); if drawing { let lerp = |s: f32| (x0 + (x1 - x0) * s / length, y0 + (y1 - y0) * s / length); let (a, b) = (lerp(at), lerp(end)); builder.move_to(point(px(a.0), px(a.1))); builder.line_to(point(px(b.0), px(b.1))); } at = end; } walked += length; } } fn stroke_builder(width: f32) -> PathBuilder { PathBuilder::fill().with_style(PathStyle::Stroke(StrokeOptions { line_width: width, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Default::default() })) } /// One price level of an order book: the price, the size resting there, and the running total /// from the spread out to this level. #[derive(Clone, Copy, Debug, PartialEq)] pub struct BookLevel { pub price: f64, pub size: f64, pub total: f64, } /// The two sides of an order book, best price first on each side. #[derive(Clone, Debug, PartialEq)] pub struct Book { pub mid: f64, pub bids: Vec<BookLevel>, pub asks: Vec<BookLevel>, } impl Book { /// A book from `(price, size)` pairs, best price first. Totals are summed for you. pub fn new(mid: f64, bids: impl IntoIterator<Item = (f64, f64)>, asks: impl IntoIterator<Item = (f64, f64)>) -> Self { let side = |levels: Vec<(f64, f64)>| { let mut total = 0.0; levels .into_iter() .map(|(price, size)| { total += size; BookLevel { price, size, total } }) .collect() }; Self { mid, bids: side(bids.into_iter().collect()), asks: side(asks.into_iter().collect()) } } /// A seeded sample book around `mid`: `levels` per side, `tick` apart (6 bps of the mid by /// default), sizes growing with distance and the odd large order. pub fn sample(mid: f64, seed: u32, levels: usize, tick: Option<f64>, depth: f64) -> Self { let mut rand = mulberry32(seed); let step = tick.unwrap_or_else(|| round2(mid * 0.0006).max(0.01)); let mut side = |direction: f64| { let mut total = 0.0; (0..levels) .map(|i| { let distance = (i + 1) as f64 / levels as f64; let base = depth * (0.18 + distance * 0.9); let whale = if rand() > 0.87 { 2.4 } else { 1.0 }; let size = (base * (0.55 + rand() * 0.9) * whale).round(); total += size; BookLevel { price: round2(mid + direction * step * (i + 1) as f64), size, total } }) .collect::<Vec<_>>() }; let asks = side(1.0); let bids = side(-1.0); Self { mid, bids, asks } } /// The gap between the best ask and the best bid. pub fn spread(&self) -> f64 { let bid = self.bids.first().map_or(self.mid, |level| level.price); let ask = self.asks.first().map_or(self.mid, |level| level.price); ask - bid } /// The same book with every size nudged by up to ±20%, as a stand-in for a live feed. fn jittered(&self, tick: u32) -> Self { let mut rand = mulberry32(0xb00c_u32.wrapping_add(tick)); let mut jitter = |levels: &[BookLevel]| { let mut total = 0.0; levels .iter() .map(|level| { let size = (level.size * (0.82 + rand() * 0.4)).round().max(1.0); total += size; BookLevel { size, total, ..*level } }) .collect::<Vec<_>>() }; let bids = jitter(&self.bids); let asks = jitter(&self.asks); Self { mid: self.mid, bids, asks } } } /// Which side of the book a level is on. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BookSide { Bid, Ask, } #[derive(Default)] struct BookState { hover: Option<(BookSide, usize)>, tick: u32, ticker: Option<gpui::Task<()>>, } const BOOK_ROW: f32 = 22.0; const BOOK_FLASH: Duration = Duration::from_millis(520); /// A trading ladder: asks above, bids below, a spread row between them, and a bar behind each /// level for the cumulative size out to it. Hovering a level highlights the depth up to it. /// With [`OrderBook::live`], sizes change every 1.4s and changed levels flash. #[derive(IntoElement)] pub struct OrderBook { id: ElementId, book: Book, symbol: SharedString, live: bool, interval: Duration, } impl OrderBook { pub fn new(id: impl Into<ElementId>, book: Book) -> Self { Self { id: id.into(), book, symbol: "SOL".into(), live: false, interval: Duration::from_millis(1_400) } } /// The ticker shown in the header. pub fn symbol(mut self, symbol: impl Into<SharedString>) -> Self { self.symbol = symbol.into(); self } /// Simulates a live feed: a pulsing Live badge, sizes that change, and flashing levels. pub fn live(mut self, live: bool) -> Self { self.live = live; self } /// How often a live book updates. pub fn interval(mut self, interval: Duration) -> Self { self.interval = interval; self } } impl RenderOnce for OrderBook { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let state = window.use_keyed_state(self.id.clone(), cx, |_, _| BookState::default()); if self.live && state.read(cx).ticker.is_none() { let interval = self.interval; state.update(cx, |state, cx| { state.ticker = Some(cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(interval).await; let ticked = this.update(cx, |state, cx| { state.tick = state.tick.wrapping_add(1); cx.notify(); }); if ticked.is_err() { break; } } })); }); } let (hover, tick) = { let state = state.read(cx); (state.hover, if self.live { state.tick } else { 0 }) }; let theme = cx.theme().clone(); let (up, down) = (market_up(&theme), market_down(&theme)); let book = if tick == 0 { self.book.clone() } else { self.book.jittered(tick) }; // Each update flashes about a third of the levels, picked by the same seeded draw. let mut flashed = Vec::new(); if tick > 0 { let mut rand = mulberry32(0xf1a5_u32.wrapping_add(tick)); for (side, len) in [(BookSide::Bid, book.bids.len()), (BookSide::Ask, book.asks.len())] { for ix in 0..len { if rand() > 0.62 { flashed.push((side, ix)); } } } } let max_total = book .bids .last() .map_or(1.0, |level| level.total) .max(book.asks.last().map_or(1.0, |level| level.total)) .max(1.0); let spread = book.spread(); let spread_digits = if book.mid >= 100.0 { 2 } else if book.mid >= 1.0 { 3 } else { 5 }; let row = |side: BookSide, ix: usize, level: BookLevel| { let color = if side == BookSide::Bid { up } else { down }; let depth = (level.total / max_total).max(0.02) as f32; let highlighted = hover.is_some_and(|(s, h)| s == side && ix <= h); let state = state.clone(); let id = match side { BookSide::Bid => ElementId::NamedInteger("bid".into(), ix as u64), BookSide::Ask => ElementId::NamedInteger("ask".into(), ix as u64), }; div() .id(id) .relative() .flex() .items_center() .h(px(BOOK_ROW)) .px(px(8.0)) .on_hover(move |hovered, _, cx| { state.update(cx, |state, cx| { let next = match (*hovered, state.hover) { (true, _) => Some((side, ix)), (false, Some(owner)) if owner == (side, ix) => None, (false, other) => other, }; if state.hover != next { state.hover = next; cx.notify(); } }); }) .child( div() .absolute() .top(px(1.0)) .bottom(px(1.0)) .left(px(4.0)) .right(px(4.0)) .flex() .justify_end() .child( div() .h_full() .w(relative(depth)) .rounded(px(3.0)) .bg(color.opacity(if highlighted { 0.28 } else { 0.13 })), ), ) .when(flashed.contains(&(side, ix)), |this| { this.child( div().absolute().inset_0().bg(color).with_animation( ElementId::NamedInteger("flash".into(), u64::from(tick)), Animation::new(BOOK_FLASH).with_easing(|t| 1.0 - (1.0 - t).powi(2)), |this, t| this.opacity(0.2 * (1.0 - t)), ), ) }) .child(div().relative().w(relative(0.38)).text_color(color).child(format_money(level.price))) .child( div() .relative() .w(relative(0.31)) .flex() .justify_end() .text_color(theme.foreground.opacity(0.8)) .child(compact_size(level.size)), ) .child( div() .relative() .w(relative(0.31)) .flex() .justify_end() .text_color(theme.muted_foreground) .child(compact_size(level.total)), ) }; let column = |label: &'static str, share: f32, end: bool| { div().w(relative(share)).flex().when(end, |this| this.justify_end()).child(label) }; let clear = state.clone(); div() .id(self.id) .w_full() .overflow_hidden() .rounded(px(12.0)) .border_1() .border_color(theme.border) .bg(theme.card) .font_family(MONO) .text_size(px(11.0)) .line_height(px(16.0)) .on_hover(move |hovered, _, cx| { if !*hovered { clear.update(cx, |state, cx| { state.hover = None; cx.notify(); }); } }) .child( div() .flex() .items_center() .justify_between() .px(px(10.0)) .py(px(8.0)) .border_b_1() .border_color(theme.border) .child( div() .flex() .gap(px(6.0)) .font_weight(FontWeight::MEDIUM) .text_color(theme.foreground) .child(self.symbol.clone()) .child(div().text_color(theme.muted_foreground).child("Order book")), ) .when(self.live, |this| { this.child( div() .flex() .items_center() .gap(px(4.0)) .text_size(px(9.0)) .text_color(theme.muted_foreground) .child(div().size(px(6.0)).rounded_full().bg(up).with_animation( "book-live", Animation::new(Duration::from_millis(2_200)) .repeat() .with_easing(gpui::pulsating_between(0.0, 1.0)), |this, t| this.opacity(t), )) .child("LIVE"), ) }), ) .child( div() .flex() .px(px(8.0)) .py(px(6.0)) .text_size(px(9.5)) .text_color(theme.muted_foreground) .child(column("PRICE", 0.38, false)) .child(column("SIZE", 0.31, true)) .child(column("TOTAL", 0.31, true)), ) .child(div().flex().flex_col().children( book.asks.iter().enumerate().rev().map(|(ix, level)| row(BookSide::Ask, ix, *level)), )) .child( div() .my(px(4.0)) .flex() .items_center() .justify_between() .px(px(8.0)) .py(px(6.0)) .border_y_1() .border_color(theme.border) .bg(theme.foreground.opacity(if is_dark(&theme) { 0.03 } else { 0.02 })) .child(div().font_weight(FontWeight::MEDIUM).text_color(theme.foreground).child(format_money(book.mid))) .child(div().text_size(px(10.0)).text_color(theme.muted_foreground).child(format!( "spread ${spread:.spread_digits$} · {:.3}%", spread / book.mid * 100.0 ))), ) .child( div() .pb(px(4.0)) .flex() .flex_col() .children(book.bids.iter().enumerate().map(|(ix, level)| row(BookSide::Bid, ix, *level))), ) } } /// One day of a portfolio: the account value and the cost basis paid in so far. #[derive(Clone, Copy, Debug, PartialEq)] pub struct PortfolioPoint { /// Days since 1970-01-01. pub day: i64, pub value: f64, pub basis: f64, } /// 420 seeded days of an account ending on Aug 21, 2026, with a deposit every 30 days that /// raises the basis by 4.5% of `start`. pub fn sample_portfolio(seed: u32, start: f64) -> Vec<PortfolioPoint> { const LEN: i64 = 420; let end = days_from_civil(2026, 8, 21); let mut rand = mulberry32(seed); let (mut value, mut basis) = (start, start); (0..LEN) .map(|i| { if i > 0 && i % 30 == 0 { let deposit = (start * 0.045).round(); basis += deposit; value += deposit; } value = (value * (1.0 + (rand() - 0.47) * 0.021)).max(1.0); PortfolioPoint { day: end - (LEN - 1 - i), value: value.round(), basis: basis.round() } }) .collect() } /// A range button: its label and how many trailing days it shows (`None` for all). #[derive(Clone, Debug, PartialEq)] pub struct MarketRange { pub label: SharedString, pub days: Option<usize>, } impl MarketRange { pub fn new(label: impl Into<SharedString>, days: Option<usize>) -> Self { Self { label: label.into(), days } } /// 1W, 1M, 3M, 6M, 1Y and ALL. pub fn defaults() -> Vec<Self> { [("1W", Some(7)), ("1M", Some(30)), ("3M", Some(90)), ("6M", Some(180)), ("1Y", Some(365)), ("ALL", None)] .into_iter() .map(|(label, days)| Self::new(label, days)) .collect() } } /// Percent below the running peak for each point, so 0 at every new high. pub fn drawdowns(points: &[PortfolioPoint]) -> Vec<f64> { let mut peak = f64::NEG_INFINITY; points .iter() .map(|p| { peak = peak.max(p.value); if peak > 0.0 { (p.value - peak) / peak * 100.0 } else { 0.0 } }) .collect() } struct PortfolioState { range: SharedString, hover: Option<usize>, } /// Room around the plot: value labels sit on the right, dates below. const PF_TOP: f32 = 12.0; const PF_RIGHT: f32 = 66.0; const PF_BOTTOM: f32 = 22.0; const PF_LEFT: f32 = 12.0; /// Share of the plot height given to the drawdown strip under the value chart. const PF_DRAWDOWN_SHARE: f32 = 0.24; const PF_GAP: f32 = 14.0; const PF_AXIS_TEXT: f32 = 10.5; /// Account value against cost basis over time, with a range picker and, optionally, the /// drawdown from the running peak shaded in a strip underneath. Hover reads out any day. #[derive(IntoElement)] pub struct PortfolioChart { id: ElementId, data: Rc<Vec<PortfolioPoint>>, label: SharedString, ranges: Vec<MarketRange>, default_range: SharedString, drawdown: bool, height: Pixels, } impl PortfolioChart { pub fn new(id: impl Into<ElementId>, data: impl Into<Rc<Vec<PortfolioPoint>>>) -> Self { Self { id: id.into(), data: data.into(), label: "Portfolio".into(), ranges: MarketRange::defaults(), default_range: "1Y".into(), drawdown: true, height: px(400.0), } } pub fn label(mut self, label: impl Into<SharedString>) -> Self { self.label = label.into(); self } pub fn ranges(mut self, ranges: impl IntoIterator<Item = MarketRange>) -> Self { self.ranges = ranges.into_iter().collect(); self } /// The range selected at first, by label. pub fn default_range(mut self, label: impl Into<SharedString>) -> Self { self.default_range = label.into(); self } /// Whether to draw the drawdown strip under the value chart. pub fn drawdown(mut self, drawdown: bool) -> Self { self.drawdown = drawdown; self } /// The plot's height, axes included. pub fn height(mut self, height: Pixels) -> Self { self.height = height; self } } impl RenderOnce for PortfolioChart { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let default_range = self.default_range.clone(); let state = window.use_keyed_state(self.id.clone(), cx, |_, _| PortfolioState { range: default_range, hover: None }); let theme = cx.theme().clone(); let (up, down) = (market_up(&theme), market_down(&theme)); let (range_label, hover) = { let state = state.read(cx); (state.range.clone(), state.hover) }; let range = self .ranges .iter() .find(|r| r.label == range_label) .or(self.ranges.last()) .cloned() .unwrap_or_else(|| MarketRange::new("ALL", None)); let view: Rc<Vec<PortfolioPoint>> = match range.days { Some(days) if days < self.data.len() => Rc::new(self.data[self.data.len() - days..].to_vec()), _ => self.data.clone(), }; let n = view.len(); let hover = hover.filter(|&ix| ix < n); let dd = Rc::new(drawdowns(&view)); let max_dd = dd.iter().copied().fold(0.0, f64::min); let active_ix = hover.unwrap_or(n.saturating_sub(1)); let active = view.get(active_ix).copied(); let active_dd = dd.get(active_ix).copied().unwrap_or(0.0); let pnl = active.map_or(0.0, |p| p.value - p.basis); let pnl_pct = active.filter(|p| p.basis != 0.0).map_or(0.0, |p| pnl / p.basis * 100.0); let readout = if pnl >= 0.0 { up } else { down }; let direction = match view.last() { Some(last) if last.value < last.basis => down, _ => up, }; let stat = |label: &'static str, value: SharedString, color: Hsla| { div() .flex() .gap(px(4.0)) .text_color(theme.muted_foreground) .child(label) .child(div().text_color(color).child(value)) }; let header = div() .mb(px(12.0)) .flex() .flex_wrap() .items_start() .justify_between() .gap_x(px(16.0)) .gap_y(px(12.0)) .child( div() .flex() .flex_col() .child( div() .text_size(px(12.0)) .line_height(px(16.0)) .font_weight(FontWeight::MEDIUM) .text_color(theme.foreground) .child(self.label.clone()), ) .child( div() .mt(px(4.0)) .flex() .items_end() .gap(px(10.0)) .child( div() .text_size(px(26.0)) .line_height(px(32.0)) .font_weight(FontWeight::MEDIUM) .text_color(theme.foreground) .child(format_money_compact(active.map_or(0.0, |p| p.value))), ) .child( div().mb(px(4.0)).text_size(px(12.0)).line_height(px(16.0)).text_color(readout).child(format!( "{}{} ({})", if pnl >= 0.0 { "+" } else { "\u{2212}" }, format_money_compact(pnl.abs()), format_signed_pct(pnl_pct) )), ), ) .child( div() .mt(px(6.0)) .flex() .flex_wrap() .items_center() .gap_x(px(12.0)) .text_size(px(10.5)) .line_height(px(14.0)) .child( div() .text_color(theme.muted_foreground) .child(active.map_or_else(SharedString::default, |p| date_full(p.day))), ) .child(stat("Basis", format_money_compact(active.map_or(0.0, |p| p.basis)), theme.foreground)) .child(stat( "Drawdown", format!("{active_dd:.2}%").into(), if active_dd < -0.05 { down } else { theme.foreground }, )) .child(stat("Max DD", format!("{max_dd:.2}%").into(), theme.foreground)), ), ) .child(range_selector(&self.ranges, &range.label, state.clone(), &theme)); // The canvas reports where it was laid out, so pointer positions can become days. let bounds = Rc::new(Cell::new(None::<Bounds<Pixels>>)); let progress = Rc::new(Cell::new(1.0f32)); let show_dd = self.drawdown; let plot = { let (bounds, progress, view, dd, theme) = (bounds.clone(), progress.clone(), view.clone(), dd.clone(), theme.clone()); canvas( move |b, _, _| bounds.set(Some(b)), move |b, _, window, cx| { let style = PortfolioPaint { up: direction, down, show_dd, hover, max_dd, t: progress.get() }; paint_portfolio(window, cx, b, &view, &dd, style, &theme); }, ) .absolute() .size_full() }; let pointer = { let (state, bounds) = (state.clone(), bounds.clone()); move |position: gpui::Point<Pixels>, cx: &mut App| { let Some(b) = bounds.get() else { return }; if n == 0 { return; } let x = f32::from(position.x - b.origin.x); let plot_w = (f32::from(b.size.width) - PF_RIGHT - PF_LEFT).max(1.0); let step = plot_w / n as f32; let next = Some((((x - PF_LEFT) / step).floor().max(0.0) as usize).min(n - 1)); state.update(cx, |state, cx| { if state.hover != next { state.hover = next; cx.notify(); } }); } }; let clear = state.clone(); let intro_key = data_key(view.iter().map(|p| &p.value), (range.label.to_string(), show_dd)); div() .id(self.id) .w_full() .flex() .flex_col() .font_family(MONO) .child(header) .child( div() .id("portfolio-plot") .relative() .w_full() .h(self.height) .on_mouse_move(move |event, _, cx| pointer(event.position, cx)) .on_hover(move |hovered, _, cx| { if !*hovered { clear.update(cx, |state, cx| { state.hover = None; cx.notify(); }); } }) .child(div().absolute().size_full().child(plot).with_animation( ("portfolio-intro", intro_key as usize), Animation::new(Duration::from_millis(900)).with_easing(|t| cubic_bezier(0.22, 1.0, 0.36, 1.0, t)), move |this, t| { progress.set(t); this }, )), ) } } /// The 1W … ALL pill: the selected range sits on a raised chip. fn range_selector( ranges: &[MarketRange], selected: &SharedString, state: Entity<PortfolioState>, theme: &Theme, ) -> impl IntoElement { let dark = is_dark(theme); div() .flex() .items_center() .p(px(2.0)) .rounded_full() .bg(theme.foreground.opacity(if dark { 0.07 } else { 0.045 })) .children(ranges.iter().enumerate().map(|(ix, range)| { let active = &range.label == selected; let (state, label) = (state.clone(), range.label.clone()); div() .id(("portfolio-range", ix)) .px(px(10.0)) .py(px(4.0)) .rounded_full() .text_size(px(11.0)) .line_height(px(11.0)) .cursor_pointer() .when(active, |this| { this.text_color(theme.foreground) .bg(if dark { theme.foreground.opacity(0.12) } else { theme.background }) .border_1() .border_color(theme.foreground.opacity(if dark { 0.1 } else { 0.06 })) .shadow_sm() }) .when(!active, |this| { this.border_1() .border_color(gpui::transparent_black()) .text_color(theme.muted_foreground) .hover(|this| this.text_color(theme.foreground.opacity(0.85))) }) .on_click(move |_, _, cx| { state.update(cx, |state, cx| { state.range = label.clone(); state.hover = None; cx.notify(); }); }) .child(range.label.clone()) })) } #[derive(Clone, Copy)] struct PortfolioPaint { /// The value line's color: green while above basis at the end of the range, else red. up: Hsla, down: Hsla, show_dd: bool, hover: Option<usize>, max_dd: f64, /// Intro progress, 0 to 1: the value line draws in left to right. t: f32, } fn paint_portfolio( window: &mut Window, cx: &mut App, b: Bounds<Pixels>, view: &[PortfolioPoint], dd: &[f64], style: PortfolioPaint, theme: &Theme, ) { let n = view.len(); if n == 0 { return; } let (ox, oy) = (f32::from(b.origin.x), f32::from(b.origin.y)); let (w, h) = (f32::from(b.size.width).max(260.0), f32::from(b.size.height)); let (x0, x1) = (ox + PF_LEFT, ox + w - PF_RIGHT); let plot_w = (x1 - x0).max(1.0); let (inner_top, inner_bottom) = (oy + PF_TOP, oy + h - PF_BOTTOM); let dd_h = if style.show_dd { (inner_bottom - inner_top) * PF_DRAWDOWN_SHARE } else { 0.0 }; let value_top = inner_top; let value_bottom = inner_bottom - if style.show_dd { dd_h + PF_GAP } else { 0.0 }; let dd_top = inner_bottom - dd_h; let step = plot_w / n as f32; let cx_at = |i: usize| x0 + step * (i as f32 + 0.5); let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); for p in view { lo = lo.min(p.value.min(p.basis)); hi = hi.max(p.value.max(p.basis)); } let pad = match (hi - lo) * 0.12 { pad if pad > 0.0 => pad, _ if hi.abs() > 0.0 => hi.abs() * 0.05, _ => 1.0, }; let (lo, hi) = (lo - pad, hi + pad); let value_y = |v: f64| value_bottom - ((v - lo) / (hi - lo)) as f32 * (value_bottom - value_top); let max_dd = style.max_dd.abs().max(1.0); let dd_y = |v: f64| dd_top + (v.abs() / max_dd) as f32 * dd_h; let muted = theme.muted_foreground; let grid = theme.foreground.opacity(0.12); // Gridlines and value labels on the right. for tick in price_ticks(lo, hi, 4) { let y = value_y(tick); if y < value_top - 1.0 || y > value_bottom + 1.0 { continue; } let mut builder = stroke_builder(1.0); dash(&mut builder, &[(x0, y), (x1, y)], 2.0, 4.0); if let Ok(path) = builder.build() { window.paint_path(path, grid); } paint_mono(window, cx, axis_price(tick), x1 + 8.0, y, PF_AXIS_TEXT, muted, FontWeight::NORMAL, false); } let value_pts: Vec<(f32, f32)> = view.iter().enumerate().map(|(i, p)| (cx_at(i), value_y(p.value))).collect(); let basis_pts: Vec<(f32, f32)> = view.iter().enumerate().map(|(i, p)| (cx_at(i), value_y(p.basis))).collect(); // The value area fades in while its line draws across. let reveal = Bounds::from_corners(point(px(ox), px(oy)), point(px(x0 + plot_w * style.t), px(oy + h))); let mut area = PathBuilder::fill(); area.move_to(point(px(value_pts[0].0), px(value_pts[0].1))); trace(&mut area, &value_pts, Curve::Monotone); area.line_to(point(px(cx_at(n - 1)), px(value_bottom))); area.line_to(point(px(cx_at(0)), px(value_bottom))); area.close(); if let Ok(path) = area.build() { let fade = style.t.min(1.0); window.paint_path( path, linear_gradient(180.0, linear_color_stop(style.up.opacity(0.26 * fade), 0.0), linear_color_stop(style.up.opacity(0.0), 1.0)), ); } let mut basis = stroke_builder(1.4); dash(&mut basis, &basis_pts, 5.0, 4.0); if let Ok(path) = basis.build() { window.paint_path(path, theme.foreground.opacity(0.4)); } let mut line = stroke_builder(2.0); line.move_to(point(px(value_pts[0].0), px(value_pts[0].1))); trace(&mut line, &value_pts, Curve::Monotone); if let Ok(path) = line.build() { window.with_content_mask(Some(ContentMask { bounds: reveal }), |window| window.paint_path(path, style.up)); } if style.show_dd { let mut rule = stroke_builder(1.0); rule.move_to(point(px(x0), px(dd_top))); rule.line_to(point(px(x1), px(dd_top))); if let Ok(path) = rule.build() { window.paint_path(path, theme.foreground.opacity(0.18)); } let dd_pts: Vec<(f32, f32)> = dd.iter().enumerate().map(|(i, v)| (cx_at(i), dd_y(*v))).collect(); let mut fill_path = PathBuilder::fill(); fill_path.move_to(point(px(dd_pts[0].0), px(dd_pts[0].1))); trace(&mut fill_path, &dd_pts, Curve::Monotone); fill_path.line_to(point(px(cx_at(n - 1)), px(dd_top))); fill_path.line_to(point(px(cx_at(0)), px(dd_top))); fill_path.close(); let fade = style.t.min(1.0); if let Ok(path) = fill_path.build() { window.paint_path( path, linear_gradient( 180.0, linear_color_stop(style.down.opacity(0.32 * fade), 0.0), linear_color_stop(style.down.opacity(0.04 * fade), 1.0), ), ); } let mut edge = stroke_builder(1.2); edge.move_to(point(px(dd_pts[0].0), px(dd_pts[0].1))); trace(&mut edge, &dd_pts, Curve::Monotone); if let Ok(path) = edge.build() { window.paint_path(path, style.down.opacity(0.75 * fade)); } paint_mono(window, cx, "DRAWDOWN".into(), x0 + 2.0, dd_top - 9.0, 9.5, muted.opacity(0.9), FontWeight::SEMIBOLD, false); paint_mono(window, cx, format!("{:.1}%", style.max_dd).into(), x1 + 8.0, dd_top + dd_h, 9.5, muted, FontWeight::NORMAL, false); } // Dates along the bottom, about one per 96px, always ending on the last day. let want = ((plot_w / 96.0).floor() as usize).clamp(2, 6); let gap = ((n - 1) / (want - 1)).max(1); let mut ticks: Vec<usize> = (0..n).step_by(gap).collect(); if ticks.last() != Some(&(n - 1)) { while ticks.last().is_some_and(|&last| cx_at(n - 1) - cx_at(last) < 62.0) { ticks.pop(); } ticks.push(n - 1); } for i in ticks { let x = cx_at(i).clamp(x0 + 14.0, x1 - 14.0); paint_mono(window, cx, date_short(view[i].day), x, inner_bottom + 12.0, PF_AXIS_TEXT, muted, FontWeight::NORMAL, true); } if let Some(i) = style.hover { let x = cx_at(i); let mut cross = stroke_builder(1.0); dash(&mut cross, &[(x, value_top), (x, inner_bottom)], 3.0, 3.0); if let Ok(path) = cross.build() { window.paint_path(path, theme.foreground.opacity(0.42)); } paint_dot(window, x, value_y(view[i].value), 9.0, theme.card, Some(style.up)); paint_dot(window, x, value_y(view[i].basis), 6.0, theme.card, Some(theme.foreground.opacity(0.6))); let pill_x = x.clamp(x0 + 28.0, x1 - 28.0); let pill = Bounds::from_corners(point(px(pill_x - 27.0), px(inner_bottom + 4.0)), point(px(pill_x + 27.0), px(inner_bottom + 20.0))); window.paint_quad(fill(pill, theme.foreground).corner_radii(px(4.0))); paint_mono(window, cx, date_short(view[i].day), pill_x, inner_bottom + 12.0, 10.0, theme.background, FontWeight::SEMIBOLD, true); } } #[cfg(test)] mod tests { use super::scale::LinearScale; use super::*; #[test] fn nice_scale_rounds_outward_and_includes_zero() { let scale = LinearScale::nice(73.0, 305.0, 5); assert_eq!(scale.ticks(), vec![0.0, 100.0, 200.0, 300.0, 400.0]); } #[test] fn stacking_separates_positive_and_negative() { let values = vec![vec![Some(3.0)], vec![Some(-2.0)], vec![Some(4.0)]]; let spans = layout(&values, &[true, true, true], true, false, 1); let get = |s: usize| spans[s][0].unwrap(); assert_eq!((get(0).lo, get(0).hi), (0.0, 3.0)); assert_eq!((get(1).lo, get(1).hi), (-2.0, 0.0)); assert_eq!((get(2).lo, get(2).hi), (3.0, 7.0)); } #[test] fn expanded_stacks_reach_one() { let values = vec![vec![Some(1.0)], vec![Some(3.0)]]; let spans = layout(&values, &[true, true], false, true, 1); assert!((spans[1][0].unwrap().hi - 1.0).abs() < 1e-9); } #[test] fn unstacked_negative_spans_reach_below_zero() { let spans = layout(&[vec![Some(-18.0)]], &[true], false, false, 1); let span = spans[0][0].unwrap(); assert_eq!((span.lo, span.hi, span.at), (-18.0, 0.0, -18.0)); } }Register the module
// src/ui/mod.rs pub mod chart;
Usage
use crate::ui::chart::*;Examples
Line
ChartKind::Line draws a smooth line per series. Hover to see every value for a month.
use gpui::{div, prelude::*, px};
use crate::ui::chart::{Chart, ChartKind, ChartSeries};
pub fn chart_line() -> impl IntoElement {
div().w(px(560.0)).child(
Chart::new("visitors-line", ChartKind::Line)
.categories(["January", "February", "March", "April", "May", "June"])
.series(ChartSeries::new("Desktop", [186.0, 305.0, 237.0, 73.0, 209.0, 214.0]))
.series(ChartSeries::new("Mobile", [80.0, 200.0, 120.0, 190.0, 130.0, 140.0])),
)
}Area
ChartKind::Area fills the space under each line. format sets how values read on the axis and in the tooltip.
use gpui::{div, prelude::*, px, SharedString};
use crate::ui::chart::{Chart, ChartKind, ChartSeries};
pub fn chart_area() -> impl IntoElement {
div().w(px(560.0)).child(
Chart::new("revenue-area", ChartKind::Area)
.categories(["Jan", "Feb", "Mar", "Apr", "May", "Jun"])
.series(ChartSeries::new("Revenue", [4.2, 5.8, 5.1, 7.4, 6.9, 8.6]))
.format(|value| SharedString::from(format!("${value}k"))),
)
}API Reference
ChartKind
ChartKind::BarVertical bars, side by side when there are several series.
ChartKind::LineA line per series.
ChartKind::AreaA line per series with the area below it filled in.
Indicator
How the tooltip marks each series' color.
Indicator::DotIndicator::LineIndicator::DashedIndicator::NoneChartSeries
One named row of values, one per category. NaN or a missing value leaves a gap.
ChartSeries::new(label: impl Into<SharedString>, values: impl IntoIterator<Item = f64>) -> Self.icon(svg: &'static [u8])An SVG icon shown in the legend in place of the color square.
.color(color: Hsla)Overrides the series color. Pass a theme token or one of [chart_colors] so dark mode follows.
.colors(colors: impl IntoIterator<Item = Hsla>)A color per category instead of one for the whole series, e.g. a bar per browser.
Chart
Chart::new(id: impl Into<ElementId>, kind: ChartKind) -> SelfChart::categories<S: Into<SharedString>>(mut self, categories: impl IntoIterator<Item = S>) -> Self.series(series: ChartSeries).stacked(stacked: bool)Stacks series on top of each other instead of side by side or overlapping.
.expanded(expanded: bool)Stacks series and scales every category to 100%, so the chart shows each series' share.
.horizontal(horizontal: bool)Lays bars out sideways: categories down the left, values along the bottom.
.curve(curve: Curve)How lines pass through their points. Smooth by default.
.dots(dots: bool)Draws a dot on every point of a line or area, not only the hovered one.
.gradient(gradient: bool)Fills areas with a gradient that fades toward the axis, instead of a flat tint.
.labels(labels: bool)Writes each value at the end of its bar or above its point.
.category_labels(category_labels: bool)With labels(true), writes each point's category name instead of its value.
.inside_labels(inside: bool)For horizontal bars: writes the category name inside each bar instead of on an axis.
.active(index: usize)Emphasizes one category's bar with a dashed outline, e.g. the current month.
.height(height: Pixels)Height of the plot, without axis labels and legend.
.y_axis(y_axis: bool).x_axis(x_axis: bool).legend(legend: bool)A row of series names under the chart. Clicking one hides or shows that series.
.tooltip(tooltip: bool)Whether hovering shows a card with every series' value.
.tooltip_label(label: bool)Whether the tooltip starts with the category's name.
.open_tooltip(index: usize)Shows the tooltip for one category from the start, before the pointer arrives. The pointer still moves it, and it returns to this category when the pointer leaves.
.tooltip_total(total: bool)Adds a last tooltip row with the sum of every shown series.
.tooltip_title(title: impl Fn(&SharedString) -> SharedString + 'static)Rewrites the tooltip's title from the category, e.g. "Jan 1" to "January 1, 2024".
.indicator(indicator: Indicator)How the tooltip marks each series: a dot, a line, a dashed line or nothing.
.bar_radius(radius: Pixels).format(format: impl Fn(f64) -> SharedString + 'static)Formats values on the value axis, in labels and in the tooltip, e.g. as currency.
Slice
Slice::new(label: impl Into<SharedString>, value: f64) -> Self.color(color: Hsla)PieChart
A pie, or a donut with the total in its middle.
PieChart::new(id: impl Into<ElementId>) -> Self.slice(slice: Slice).ring(slices: impl IntoIterator<Item = Slice>)Adds a ring of slices around the pie, for comparing two breakdowns of the same whole.
.size(size: Pixels).inner_radius(ratio: f32)Hole size as a share of the radius: 0 is a pie, 0.6 a donut. A donut shows the total in the middle, or the hovered or active slice.
.caption(caption: impl Into<SharedString>)The word under the total in a donut's center.
.legend(legend: bool).separator(separator: bool)Whether a thin gap separates the slices. On by default.
.labels(labels: bool)Writes each slice's value just outside it.
.inside_labels(inside: bool)Writes each slice's name inside it.
.active(index: usize)Pulls one slice out, as if hovered, and shows it in a donut's middle.
.format(format: impl Fn(f64) -> SharedString + 'static)RadarGrid
The web behind a radar chart.
RadarGrid::PolygonPolygons through each tick, joined by spokes, as Recharts draws by default.
RadarGrid::CircleCircles through each tick, joined by spokes.
RadarGrid::SpokesOnly the spokes.
RadarGrid::NoneNothing behind the data.
RadarChart
Values around a circle, one spoke per category: good for comparing profiles.
RadarChart::new(id: impl Into<ElementId>) -> SelfRadarChart::categories<S: Into<SharedString>>(mut self, categories: impl IntoIterator<Item = S>) -> Self.series(series: ChartSeries).size(size: Pixels).grid(grid: RadarGrid).grid_fill(grid_fill: bool)Shades the grid's rings in alternating tints.
.fill(fill: bool)Whether each series' shape is filled. Off draws only its outline.
.dots(dots: bool).labels(labels: bool)Writes each category's values beside its spoke label.
.legend(legend: bool).format(format: impl Fn(f64) -> SharedString + 'static)RadialChart
Bars bent into arcs: one ring per value, or the values stacked along a single arc.
RadialChart::new(id: impl Into<ElementId>) -> Self.bar(bar: Slice).size(size: Pixels).arc(start_degrees: f32, sweep_degrees: f32)The arc the bars run along, in degrees clockwise from 12 o'clock. The default is a full circle; (-90.0, 180.0) is a half circle opening downward.
.inner_radius(ratio: f32)Hole size as a share of the radius.
.max(max: f64)The value a full arc stands for. Defaults to the largest bar, or the total when stacked.
.stacked(stacked: bool)Puts every bar end to end along one arc instead of one ring each.
.track(track: bool)Draws each ring's full length in a muted tint behind its bar.
.labels(labels: bool)Writes each bar's name at its start.
.center(value: impl Into<SharedString>, caption: impl Into<SharedString>)A large value and a caption in the middle.
.format(format: impl Fn(f64) -> SharedString + 'static)Book
The two sides of an order book, best price first on each side.
Book::new(mid: f64, bids: impl IntoIterator<Item = (f64, f64)>, asks: impl IntoIterator<Item = (f64, f64)>) -> SelfA book from (price, size) pairs, best price first. Totals are summed for you.
Book::sample(mid: f64, seed: u32, levels: usize, tick: Option<f64>, depth: f64) -> SelfA seeded sample book around mid: levels per side, tick apart (6 bps of the mid by default), sizes growing with distance and the odd large order.
.spread() -> f64The gap between the best ask and the best bid.
BookSide
Which side of the book a level is on.
BookSide::BidBookSide::AskOrderBook
A trading ladder: asks above, bids below, a spread row between them, and a bar behind each level for the cumulative size out to it. Hovering a level highlights the depth up to it. With [OrderBook::live], sizes change every 1.4s and changed levels flash.
OrderBook::new(id: impl Into<ElementId>, book: Book) -> Self.symbol(symbol: impl Into<SharedString>)The ticker shown in the header.
.live(live: bool)Simulates a live feed: a pulsing Live badge, sizes that change, and flashing levels.
.interval(interval: Duration)How often a live book updates.
MarketRange
A range button: its label and how many trailing days it shows (None for all).
MarketRange::new(label: impl Into<SharedString>, days: Option<usize>) -> SelfMarketRange::defaults() -> Vec<Self>1W, 1M, 3M, 6M, 1Y and ALL.
PortfolioChart
Account value against cost basis over time, with a range picker and, optionally, the drawdown from the running peak shaded in a strip underneath. Hover reads out any day.
PortfolioChart::new(id: impl Into<ElementId>, data: impl Into<Rc<Vec<PortfolioPoint>>>) -> Self.label(label: impl Into<SharedString>).ranges(ranges: impl IntoIterator<Item = MarketRange>).default_range(label: impl Into<SharedString>)The range selected at first, by label.
.drawdown(drawdown: bool)Whether to draw the drawdown strip under the value chart.
.height(height: Pixels)The plot's height, axes included.