#![cfg(feature = "canvas")]
mod frame;
mod legend;
mod scale;
mod tooltip;
use std::{
hash::{Hash, Hasher},
sync::Arc,
};
pub use frame::{ChartFrame, ChartProps, ChartRenderer, ChartView, chart_motion, chart_recipe, snap};
pub use legend::{
ChartLegend, ChartLegendItem, ChartLegendPart, ChartLegendRenderer, ChartLegendShape, ChartLegendState,
ChartLegendView,
};
pub use scale::{BandScale, LinearScale};
pub use tooltip::{ChartTooltip, ChartTooltipPart, ChartTooltipRenderer, ChartTooltipRow, ChartTooltipView};
use super::{
names,
recipe::{Name, ResolvedPart, ResolvedRecipe},
};
use crate::{
app::theme::{PaletteColor, Theme},
canvas::{CanvasItem, Context2D},
node::{BackgroundColor, color::Color},
ui::part_style::Opacity,
};
#[derive(Clone, Debug, PartialEq)]
pub struct ChartSeries {
name: Arc<str>,
values: Arc<[f64]>,
points: Arc<[(f64, f64)]>,
color: Option<BackgroundColor>,
}
impl ChartSeries {
pub fn new<V: Into<f64>>(name: &str, values: impl IntoIterator<Item = V>) -> Self {
Self {
name: Arc::from(name),
values: values.into_iter().map(Into::into).collect(),
points: Arc::from(Vec::new()),
color: None,
}
}
pub fn points(name: &str, points: impl IntoIterator<Item = (f64, f64)>) -> Self {
Self {
name: Arc::from(name),
values: Arc::from(Vec::new()),
points: points.into_iter().collect(),
color: None,
}
}
pub fn color(mut self, color: impl Into<BackgroundColor>) -> Self {
self.color = Some(color.into());
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn values(&self) -> &[f64] {
&self.values
}
pub fn point_list(&self) -> &[(f64, f64)] {
&self.points
}
pub fn given_color(&self) -> Option<&BackgroundColor> {
self.color.as_ref()
}
pub fn len(&self) -> usize {
self.values.len().max(self.points.len())
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub fn series_color(index: usize) -> PaletteColor {
match index % 5 {
0 => PaletteColor::Chart1,
1 => PaletteColor::Chart2,
2 => PaletteColor::Chart3,
3 => PaletteColor::Chart4,
_ => PaletteColor::Chart5,
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ChartPoint {
pub series: usize,
pub index: usize,
}
impl crate::app::component::DevtoolsInspectable for ChartPoint {}
impl ChartPoint {
pub fn new(series: usize, index: usize) -> Self {
Self { series, index }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ChartSize {
Sm,
#[default]
Md,
}
names!(ChartSize {
Sm => "sm",
Md => "md",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChartPart {
Root,
Header,
Title,
Description,
Plot,
Grid,
Baseline,
Cursor,
Axis,
AxisLabel,
ValueLabel,
Empty,
Body,
}
names!(ChartPart {
Root => "root",
Header => "header",
Title => "title",
Description => "description",
Plot => "plot",
Grid => "grid",
Baseline => "baseline",
Cursor => "cursor",
Axis => "axis",
AxisLabel => "axis_label",
ValueLabel => "value_label",
Empty => "empty",
Body => "body",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChartState {
Empty,
Loading,
Header,
}
names!(ChartState {
Empty => "empty",
Loading => "loading",
Header => "header",
});
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ChartArea {
pub width: f32,
pub height: f32,
}
pub type ValueTextFn = Arc<dyn Fn(f64) -> String + Send + Sync>;
pub fn default_value_text(value: f64) -> String {
if !value.is_finite() {
return String::from("–");
}
if (value - value.round()).abs() < 1e-9 {
return format!("{value:.0}");
}
let text = format!("{value:.2}");
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
#[derive(Clone)]
pub struct ChartLook {
pub recipe: ResolvedRecipe,
pub series: Arc<[Color]>,
pub value_text: ValueTextFn,
}
impl ChartLook {
pub fn new(recipe: ResolvedRecipe, series: &[ChartSeries], value_text: ValueTextFn) -> Self {
let theme = recipe.theme().clone();
let colors = series
.iter()
.enumerate()
.map(|(index, series)| resolve(&theme, series.color.clone().unwrap_or(series_color(index).into())))
.collect();
Self {
recipe,
series: colors,
value_text,
}
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn series(&self, index: usize) -> Color {
self
.series
.get(index)
.copied()
.unwrap_or_else(|| self.theme().palette_color(series_color(index)))
}
pub fn color(&self, part: impl Into<Name>) -> Color {
let rest = self.part(part).rest();
let color = rest
.background
.map(|background| resolve(self.theme(), background))
.unwrap_or(Color::new(0, 0, 0, 0));
match rest.opacity {
Some(Opacity::Value(opacity)) => color.with_opacity(opacity),
_ => color,
}
}
pub fn hash_into(&self, state: &mut impl Hasher) {
for color in self.series.iter() {
color_key(*color).hash(state);
}
for part in [ChartPart::Grid, ChartPart::Baseline, ChartPart::Cursor] {
color_key(self.color(part)).hash(state);
}
color_key(self.theme().palette_color(PaletteColor::Card)).hash(state);
}
}
pub fn color_key(color: Color) -> u32 {
u32::from_be_bytes([color.r(), color.g(), color.b(), color.a()])
}
pub fn resolve(theme: &Theme, color: BackgroundColor) -> Color {
match color {
BackgroundColor::Color(color) => color,
BackgroundColor::Palette(role) => theme.palette_color(role),
BackgroundColor::CurrentForeground => theme.palette_color(PaletteColor::Foreground),
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChartTick {
pub position: f32,
pub text: String,
pub baseline: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub enum ChartAxis {
#[default]
None,
Bands { labels: Vec<String>, gap: f32 },
Spread(Vec<String>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChartLabel {
pub x: f32,
pub y: f32,
pub text: String,
pub offset: (f32, f32),
pub part: Name,
}
impl ChartLabel {
pub fn new(x: f32, y: f32, text: impl Into<String>, offset: (f32, f32)) -> Self {
Self {
x,
y,
text: text.into(),
offset,
part: ChartPart::AxisLabel.into(),
}
}
pub fn part(mut self, part: impl Into<Name>) -> Self {
self.part = part.into();
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TipPlace {
#[default]
Over,
Beside,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ChartTip {
pub title: String,
pub rows: Vec<(usize, f64)>,
}
pub trait ChartPlot: std::any::Any + Send + Sync + 'static {
fn paint(&self, canvas: &Context2D, area: ChartArea, look: &ChartLook, active: Option<ChartPoint>);
fn ticks(&self, _area: ChartArea, _look: &ChartLook) -> Vec<ChartTick> {
Vec::new()
}
fn axis(&self) -> ChartAxis {
ChartAxis::None
}
fn across(&self) -> bool {
false
}
fn point_at(&self, area: ChartArea, x: f32, y: f32) -> Option<ChartPoint>;
fn anchor(&self, area: ChartArea, point: ChartPoint) -> Option<(f32, f32)>;
fn tip_place(&self) -> TipPlace {
TipPlace::Over
}
fn counts(&self) -> Vec<usize>;
fn tip(&self, point: ChartPoint) -> ChartTip;
fn items(&self, area: ChartArea, look: &ChartLook) -> Vec<CanvasItem>;
fn signature(&self) -> u64;
fn is_empty(&self) -> bool {
self.counts().iter().all(|count| *count == 0)
}
fn labels(&self, _area: ChartArea, _look: &ChartLook) -> Vec<ChartLabel> {
Vec::new()
}
fn tip_color(&self, _point: ChartPoint, _series: usize, _look: &ChartLook) -> Option<Color> {
None
}
fn height_for(&self, _width: f32) -> Option<f32> {
None
}
fn paint_moving(
&self,
canvas: &Context2D,
area: ChartArea,
look: &ChartLook,
active: Option<ChartPoint>,
motion: ChartMotion<'_>,
) {
if motion.at_rest() {
return self.paint(canvas, area, look, active);
}
let Some(from) = motion.from else {
canvas.save();
canvas.begin_path();
canvas.rect(0.0, 0.0, area.width * motion.progress, area.height);
canvas.clip();
self.paint(canvas, area, look, active);
canvas.restore();
return;
};
canvas.save();
canvas.set_global_alpha(1.0 - motion.progress);
from.paint(canvas, area, look, None);
canvas.set_global_alpha(motion.progress);
self.paint(canvas, area, look, active);
canvas.restore();
}
}
#[derive(Clone, Copy)]
pub struct ChartMotion<'a> {
pub from: Option<&'a dyn ChartPlot>,
pub progress: f32,
}
impl<'a> ChartMotion<'a> {
pub const AT_REST: ChartMotion<'static> = ChartMotion {
from: None,
progress: 1.0,
};
pub fn at_rest(&self) -> bool {
self.progress >= 1.0
}
pub fn entering(&self) -> bool {
self.from.is_none() && !self.at_rest()
}
pub fn from_as<T: ChartPlot>(&self) -> Option<&'a T> {
let from: &'a dyn std::any::Any = self.from?;
from.downcast_ref::<T>()
}
pub fn lerp(&self, from: f32, to: f32) -> f32 {
from + (to - from) * self.progress
}
}
pub fn nearest(
candidates: impl IntoIterator<Item = (ChartPoint, f32, f32)>,
x: f32,
y: f32,
reach: f32,
along_x: bool,
) -> Option<ChartPoint> {
candidates
.into_iter()
.map(|(point, px, py)| {
let distance = if along_x {
(px - x).abs()
} else {
((px - x).powi(2) + (py - y).powi(2)).sqrt()
};
(point, distance)
})
.filter(|(_, distance)| *distance <= reach)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(point, _)| point)
}
pub fn nearest_sorted(sorted: &[f32], x: f32) -> Option<usize> {
if sorted.is_empty() {
return None;
}
let after = sorted.partition_point(|value| *value < x);
match after {
0 => Some(0),
_ if after >= sorted.len() => Some(sorted.len() - 1),
_ => Some(if (sorted[after] - x).abs() < (x - sorted[after - 1]).abs() {
after
} else {
after - 1
}),
}
}
pub fn step(counts: &[usize], from: ChartPoint, key: &str) -> Option<ChartPoint> {
let count = |series: usize| counts.get(series).copied().unwrap_or(0);
let index = |series: usize, index: usize| index.min(count(series).saturating_sub(1));
let to = match key {
"ArrowLeft" => ChartPoint::new(from.series, from.index.saturating_sub(1)),
"ArrowRight" => ChartPoint::new(from.series, index(from.series, from.index + 1)),
"Home" => ChartPoint::new(from.series, 0),
"End" => ChartPoint::new(from.series, count(from.series).saturating_sub(1)),
"ArrowUp" | "ArrowDown" => {
let series = if key == "ArrowUp" {
(0..from.series).rev().find(|series| count(*series) > 0)?
} else {
(from.series + 1..counts.len()).find(|series| count(*series) > 0)?
};
ChartPoint::new(series, index(series, from.index))
}
_ => return None,
};
(count(to.series) > 0).then_some(to)
}
pub fn signature_of(data: impl Hash) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
data.hash(&mut hasher);
hasher.finish()
}
pub fn bits(value: f64) -> u64 {
value.to_bits()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BarEnd {
Top,
Bottom,
Start,
End,
}
pub fn fill_bar(canvas: &Context2D, (x, y, width, height): (f32, f32, f32, f32), radius: f32, end: BarEnd) {
if width <= 0.0 || height <= 0.0 {
return;
}
let r = radius.min(width / 2.0).min(height / 2.0).max(0.0);
if r <= 0.0 {
canvas.fill_rect(x, y, width, height);
return;
}
let (right, bottom) = (x + width, y + height);
canvas.begin_path();
let corner = |cx: f32, cy: f32, tx: f32, ty: f32| {
let _ = canvas.arc_to(cx, cy, tx, ty, r);
};
match end {
BarEnd::Top => {
canvas.move_to(x, bottom);
canvas.line_to(x, y + r);
corner(x, y, x + r, y);
corner(right, y, right, y + r);
canvas.line_to(right, bottom);
}
BarEnd::Bottom => {
canvas.move_to(x, y);
canvas.line_to(right, y);
canvas.line_to(right, bottom - r);
corner(right, bottom, right - r, bottom);
corner(x, bottom, x, bottom - r);
}
BarEnd::End => {
canvas.move_to(x, y);
canvas.line_to(right - r, y);
corner(right, y, right, y + r);
corner(right, bottom, right - r, bottom);
canvas.line_to(x, bottom);
}
BarEnd::Start => {
canvas.move_to(right, y);
canvas.line_to(right, bottom);
canvas.line_to(x + r, bottom);
corner(x, bottom, x, bottom - r);
corner(x, y, x + r, y);
}
}
canvas.close_path();
canvas.fill();
}