mod frame;
mod layout;
mod marks;
mod paint;
mod plot;
use std::rc::Rc;
use gpui_kit::component::{h_flex, v_flex};
use gpui_kit::{
App, Div, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, Pixels,
RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px, rgb,
};
use subspace_charts::ChartModel;
use crate::Tokens;
pub use layout::{format_tick, format_value, format_x_full};
pub const DEFAULT_HEIGHT: f32 = 240.;
const SWATCH: f32 = 8.;
const SWATCH_RADIUS: f32 = 2.;
const LEGEND_WIDTH: f32 = 160.;
const TITLE_FONT: f32 = 13.;
const SUBTITLE_FONT: f32 = 11.;
const SHADE_STEP: f32 = 0.14;
const SHADE_LIMITS: (f32, f32) = (0.25, 0.85);
pub fn palette(tokens: &Tokens) -> Vec<Hsla> {
let mut palette: Vec<Hsla> = Vec::new();
for color in [
tokens.accent,
tokens.green,
tokens.orange,
tokens.magenta,
tokens.blue,
tokens.red,
tokens.cyan,
tokens.yellow,
] {
if !palette.iter().any(|held| same(*held, color)) {
palette.push(color);
}
}
palette
}
const SAME_TOLERANCE: f32 = 0.005;
fn same(left: Hsla, right: Hsla) -> bool {
let near = |left: f32, right: f32| (left - right).abs() < SAME_TOLERANCE;
near(left.h, right.h) && near(left.s, right.s) && near(left.l, right.l)
}
pub fn series_color(index: usize, palette: &[Hsla]) -> Hsla {
let Some(color) = palette.get(index % palette.len().max(1)) else {
return Hsla::default();
};
let turn = (index / palette.len().max(1)) as f32;
Hsla {
l: (color.l + SHADE_STEP * turn).clamp(SHADE_LIMITS.0, SHADE_LIMITS.1),
..*color
}
}
pub fn colors(model: &ChartModel, tokens: &Tokens) -> Vec<Hsla> {
let palette = palette(tokens);
model
.series
.iter()
.enumerate()
.map(|(index, series)| match series.color {
Some(color) => Hsla::from(rgb(color)),
None => series_color(index, &palette),
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Height {
Fixed(Pixels),
Fill,
}
#[derive(IntoElement)]
pub struct Chart {
name: SharedString,
model: Rc<ChartModel>,
height: Height,
label: Option<SharedString>,
}
impl Chart {
pub fn new(name: impl Into<SharedString>, model: impl Into<Rc<ChartModel>>) -> Self {
Self {
name: name.into(),
model: model.into(),
height: Height::Fixed(px(DEFAULT_HEIGHT)),
label: None,
}
}
pub fn height(mut self, height: Pixels) -> Self {
self.height = Height::Fixed(height);
self
}
pub fn fill(mut self) -> Self {
self.height = Height::Fill;
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
}
fn sized(frame: Div, height: Height) -> Div {
match height {
Height::Fixed(height) => frame.h(height),
Height::Fill => frame.flex_1().min_h_0(),
}
}
impl RenderOnce for Chart {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let tokens = Tokens::current(cx);
let colors = Rc::new(colors(&self.model, &tokens));
let label = self
.label
.clone()
.unwrap_or_else(|| self.model.description().into());
let frame = ElementId::Name(format!("{}-chart", self.name).into());
let height = self.height;
sized(v_flex().w_full(), height)
.id(frame)
.gap_1()
.role(gpui_kit::accesskit::Role::Image)
.aria_label(label)
.children(heading(&self.model, &tokens))
.child(body(self, colors, &tokens))
}
}
fn heading(model: &ChartModel, tokens: &Tokens) -> Vec<gpui_kit::AnyElement> {
let mut lines = Vec::new();
if !model.title.is_empty() {
lines.push(
div()
.text_size(tokens.heading_size(TITLE_FONT))
.font_weight(gpui_kit::FontWeight::MEDIUM)
.text_color(tokens.fg_strong)
.child(SharedString::from(model.title.clone()))
.into_any_element(),
);
}
if !model.subtitle.is_empty() {
lines.push(
div()
.text_size(tokens.heading_size(SUBTITLE_FONT))
.text_color(tokens.muted)
.child(SharedString::from(model.subtitle.clone()))
.into_any_element(),
);
}
lines
}
fn body(chart: Chart, colors: Rc<Vec<Hsla>>, tokens: &Tokens) -> impl IntoElement {
let model = chart.model;
if model.is_empty() {
return empty(tokens).into_any_element();
}
let plot = plot::ChartPlot::new(
ElementId::Name(chart.name),
model.clone(),
colors.clone(),
*tokens,
);
h_flex()
.flex_1()
.min_h_0()
.gap_2()
.child(div().flex_1().min_w_0().h_full().child(plot))
.children(legend(&model, &colors, tokens))
.into_any_element()
}
fn empty(tokens: &Tokens) -> impl IntoElement {
div()
.flex_1()
.flex()
.items_center()
.justify_center()
.text_size(tokens.row_font)
.text_color(tokens.muted)
.child("No data")
}
fn legend(model: &ChartModel, colors: &[Hsla], tokens: &Tokens) -> Option<impl IntoElement> {
if !model.legend || model.series.is_empty() {
return None;
}
let rows = model.series.iter().enumerate().map(|(index, series)| {
let color = colors.get(index).copied().unwrap_or(tokens.accent);
h_flex()
.gap_1p5()
.items_center()
.child(div().size(px(SWATCH)).rounded(px(SWATCH_RADIUS)).bg(color))
.child(
div()
.min_w_0()
.truncate()
.child(SharedString::from(series.label.clone())),
)
});
Some(
v_flex()
.max_w(px(LEGEND_WIDTH))
.flex_none()
.gap_1()
.justify_center()
.text_size(tokens.heading_size(SUBTITLE_FONT))
.text_color(tokens.fg)
.children(rows),
)
}
#[cfg(test)]
mod tests {
use crate::Tokens;
use crate::chart::{colors, palette};
use gpui_kit::{Hsla, rgb};
use subspace_charts::{ChartModel, Series};
#[test]
fn the_palette_comes_from_the_theme_tokens_without_a_repeat() {
let tokens = Tokens::one_dark();
let one_dark = palette(&tokens);
assert_eq!(one_dark[0], tokens.accent);
assert_eq!(
one_dark.len(),
8,
"One Dark maps every tone to its own colour"
);
let shared = Hsla::from(rgb(0x81ccd9));
let shell = Tokens {
accent: shared,
blue: shared,
..tokens
};
let shell = palette(&shell);
assert_eq!(shell.len(), 7, "the shared colour is listed once");
assert_eq!(shell.iter().filter(|color| **color == shared).count(), 1);
}
#[test]
fn a_series_colour_wins_over_the_palette_and_a_repeat_changes_shade() {
let tokens = Tokens::one_dark();
let model = ChartModel {
series: (0..10)
.map(|index| Series::new(format!("s{index}"), vec![Some(1.0)]))
.chain([Series::new("fixed", vec![Some(1.0)]).color(0x36a2eb)])
.collect(),
..ChartModel::default()
};
let colors = colors(&model, &tokens);
assert_eq!(colors[0], tokens.accent);
assert_eq!(colors[8].h, colors[0].h, "the palette starts again");
assert!(colors[8].l > colors[0].l, "a second turn is lighter");
assert_eq!(colors[10], Hsla::from(rgb(0x36a2eb)));
}
}