use std::{
hash::{Hash, Hasher},
marker::PhantomData,
sync::{Arc, Weak},
};
use parking_lot::Mutex;
use super::{
super::Orientation, ChartArea, ChartAxis, ChartLegend, ChartLegendItem, ChartLegendShape, ChartLook, ChartMotion,
ChartPart, ChartPlot, ChartPoint, ChartSeries, ChartSize, ChartState, ChartTooltip, ChartTooltipRow, ValueTextFn,
default_value_text, series_color, step,
};
use crate::{
app::{
component::Component,
ctx::Ctx,
events::{KeyboardEvent, MouseEvent},
theme::{BorderSize, MotionDuration, MotionEasing, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle},
},
canvas::{CanvasHandle, CanvasMotion, CanvasMove},
components::{Canvas, Column, Row, Stack},
core::{ElementRef, Signal},
layout::{Alignment, layout_kind::Justify, stack_alignment::StackAlignment, text_style::FontWeight},
node::{Element, border::Border as Edge, dimension::Dimension, node_kind::TextOverflow, outline::Outline},
ui::{
part_style::{FontFamily, Length},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
skeleton::Skeleton,
theme::current_theme,
},
};
type HiddenWrite = Arc<dyn Fn(&[String]) + Send + Sync>;
type Selected = Arc<dyn Fn(ChartPoint) + Send + Sync>;
pub type ChartRenderer = Arc<dyn Fn(ChartView) -> Element + Send + Sync>;
#[derive(Clone, Default)]
pub struct ChartProps {
pub title: Option<Arc<str>>,
pub description: Option<Arc<str>>,
pub label: Option<Arc<str>>,
pub size: Option<ChartSize>,
pub height: Option<Length>,
pub legend: Option<bool>,
pub hidden: Vec<String>,
pub write_hidden: Option<HiddenWrite>,
pub on_hidden_change: Vec<HiddenWrite>,
pub value_text: Option<ValueTextFn>,
pub grid: Option<bool>,
pub value_axis: Option<bool>,
pub empty_text: Option<Arc<str>>,
pub loading: bool,
pub still: bool,
pub on_select: Vec<Selected>,
pub states: Vec<Name>,
pub rules: Recipe,
pub forced: Option<Interaction>,
pub id: Option<Arc<str>>,
pub key: Option<Arc<str>>,
}
impl ChartProps {
pub fn case(&self, default: ChartSize, empty: bool) -> Case {
let mut case = Case::new()
.size(self.size.unwrap_or(default))
.breakpoint(super::super::current_breakpoint())
.state(ChartState::Header, self.title.is_some() || self.description.is_some())
.state(ChartState::Loading, self.loading)
.state(ChartState::Empty, empty && !self.loading);
case.states.extend(self.states.iter().copied());
case
}
pub fn value_text(&self) -> ValueTextFn {
self.value_text.clone().unwrap_or_else(|| Arc::new(default_value_text))
}
pub fn plot_height(&self, recipe: &ResolvedRecipe) -> f32 {
let length = self.height.or_else(|| recipe.part(ChartPart::Plot).rest().height);
match length.and_then(|length| length.resolve(recipe.theme())) {
Some(Dimension::Px(px)) => px,
_ => 160.0,
}
}
pub fn is_hidden(&self, series: &ChartSeries) -> bool {
self.hidden.iter().any(|name| **name == *series.name())
}
pub fn frame(
&self,
recipe: ResolvedRecipe,
plot: Arc<dyn ChartPlot>,
series: Vec<ChartSeries>,
renderer: Option<ChartRenderer>,
) -> ChartFrame {
let look = ChartLook::new(recipe.clone(), &series, self.value_text());
ChartFrame {
recipe,
plot,
look,
series,
props: self.clone(),
renderer,
plot_width: None,
plot_justify: Justify::Start,
beside: None,
own_legend: None,
laid_width: 0.0,
}
}
}
#[macro_export]
macro_rules! chart_props {
() => {
pub fn title(mut self, title: &str) -> Self {
self.props.title = Some(std::sync::Arc::from(title));
self
}
pub fn description(mut self, description: &str) -> Self {
self.props.description = Some(std::sync::Arc::from(description));
self
}
pub fn label(mut self, label: &str) -> Self {
self.props.label = Some(std::sync::Arc::from(label));
self
}
pub fn size(mut self, size: impl Into<$crate::ui::ChartSize>) -> Self {
self.props.size = Some(size.into());
self
}
pub fn height(mut self, height: impl Into<$crate::ui::Length>) -> Self {
self.props.height = Some(height.into());
self
}
pub fn legend(mut self, legend: bool) -> Self {
self.props.legend = Some(legend);
self
}
pub fn hidden(mut self, hidden: $crate::core::Signal<Vec<String>>) -> Self
where
Vec<String>: $crate::core::SignalValue,
{
self.props.hidden = hidden.get();
self.props.write_hidden = Some(std::sync::Arc::new(move |next: &[String]| hidden.set(next.to_vec())));
self
}
pub fn hidden_controlled(
mut self,
hidden: impl IntoIterator<Item = String>,
on_change: impl Fn(&[String]) + Send + Sync + 'static,
) -> Self {
self.props.hidden = hidden.into_iter().collect();
self.props.write_hidden = Some(std::sync::Arc::new(on_change));
self
}
pub fn on_hidden_change(mut self, handler: impl Fn(&[String]) + Send + Sync + 'static) -> Self {
self.props.on_hidden_change.push(std::sync::Arc::new(handler));
self
}
pub fn value_text(mut self, text: impl Fn(f64) -> String + Send + Sync + 'static) -> Self {
self.props.value_text = Some(std::sync::Arc::new(text));
self
}
pub fn grid(mut self, grid: bool) -> Self {
self.props.grid = Some(grid);
self
}
pub fn value_axis(mut self, value_axis: bool) -> Self {
self.props.value_axis = Some(value_axis);
self
}
pub fn empty_text(mut self, text: &str) -> Self {
self.props.empty_text = Some(std::sync::Arc::from(text));
self
}
pub fn loading(mut self, loading: bool) -> Self {
self.props.loading = loading;
self
}
pub fn motion(mut self, motion: bool) -> Self {
self.props.still = !motion;
self
}
pub fn on_select(mut self, handler: impl Fn($crate::ui::ChartPoint) + Send + Sync + 'static) -> Self {
self.props.on_select.push(std::sync::Arc::new(handler));
self
}
pub fn state(mut self, state: impl Into<$crate::ui::Name>, on: bool) -> Self {
let state = state.into();
self.props.states.retain(|held| *held != state);
if on {
self.props.states.push(state);
}
self
}
pub fn style(
mut self,
part: impl Into<$crate::ui::Name>,
style: impl FnOnce($crate::ui::PartStyle) -> $crate::ui::PartStyle,
) -> Self {
self.props.rules = self.props.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &$crate::ui::Recipe) -> Self {
self.props.rules = self.props.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<$crate::ui::Interaction>) -> Self {
self.props.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<std::sync::Arc<str>>) -> Self {
self.props.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<std::sync::Arc<str>>) -> Self {
self.props.key = Some(key.into());
self
}
};
}
pub struct ChartFrame {
pub recipe: ResolvedRecipe,
pub plot: Arc<dyn ChartPlot>,
pub look: ChartLook,
pub series: Vec<ChartSeries>,
pub props: ChartProps,
renderer: Option<ChartRenderer>,
plot_width: Option<f32>,
plot_justify: Justify,
beside: Option<Beside>,
own_legend: Option<Element>,
laid_width: f32,
}
struct Beside {
values: Vec<String>,
size: ChartSize,
}
pub struct ChartHostState {
hovered: Mutex<Option<ChartPoint>>,
focused: Mutex<Option<ChartPoint>>,
canvas: ElementRef,
revision: Signal<u64>,
}
impl ChartHostState {
fn rebuild(&self) {
self.revision.update(|revision| *revision = revision.wrapping_add(1));
}
fn active(&self) -> Option<ChartPoint> {
let hovered = *self.hovered.lock();
hovered.or_else(|| (*self.focused.lock()).filter(|_| self.canvas.focused()))
}
fn hover(&self, point: Option<ChartPoint>) {
let mut held = self.hovered.lock();
if *held != point {
*held = point;
drop(held);
self.rebuild();
}
}
}
impl ChartFrame {
pub fn plot_width(mut self, width: f32) -> Self {
self.plot_width = Some(width);
self
}
pub fn plot_justify(mut self, justify: Justify) -> Self {
self.plot_justify = justify;
self
}
pub fn legend_beside(mut self, values: Vec<String>, size: ChartSize) -> Self {
self.beside = Some(Beside { values, size });
self
}
pub fn own_legend(mut self, legend: impl Into<Element>) -> Self {
self.own_legend = Some(legend.into());
self
}
fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.props.forced)
}
fn name(&self) -> Arc<str> {
self
.props
.label
.clone()
.or_else(|| self.props.title.clone())
.unwrap_or_else(|| crate::ui::current_locale().data.chart.clone())
}
pub fn build(self) -> Element {
self.render_with(None)
}
fn render_with(mut self, host: Option<Arc<ChartHostState>>) -> Element {
self.laid_width = host.as_ref().map_or(0.0, |host| host.canvas.width());
let plot = self.plot_element(host.as_ref());
let axis = self.axis_element();
let legend = self.legend_element();
let view = ChartView {
beside: self.beside.is_some(),
plot_width: self.plot_width,
title: self.props.title.clone(),
description: self.props.description.clone(),
name: self.name(),
plot,
axis,
legend,
recipe: self.recipe.clone(),
forced: self.props.forced,
id: self.props.id.clone(),
key: self.props.key.clone(),
};
match &self.renderer {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn plot_height(&self) -> f32 {
let width = if self.laid_width > 0.0 {
self.laid_width
} else {
f32::INFINITY
};
self
.plot
.height_for(width)
.unwrap_or_else(|| self.props.plot_height(&self.recipe))
}
fn plot_element(&self, host: Option<&Arc<ChartHostState>>) -> Element {
let height = self.plot_height();
let part = self.part(ChartPart::Plot);
let wide = self.plot_width.map_or(Dimension::Pct(100.0), Dimension::Px);
if self.props.loading {
let block = self.plot_width.map_or(Length::Fill, Length::from);
return self.placed(
Column::new()
.width(wide)
.describe("a11y_busy", "true")
.child(Skeleton::block(block, height).build(self.recipe.theme()))
.into(),
);
}
if self.plot.is_empty() {
let empty = self.part(ChartPart::Empty);
return self.placed(
Row::new()
.width(wide)
.height(height)
.justify(Justify::Center)
.align_items(Alignment::Center)
.part(&empty)
.child(
empty
.text(
self
.props
.empty_text
.as_deref()
.unwrap_or(&crate::ui::current_locale().data.no_data),
)
.part(&empty)
.nowrap(),
)
.into(),
);
}
let active = host.and_then(|host| host.active());
let mut hasher = std::collections::hash_map::DefaultHasher::new();
self.plot.signature().hash(&mut hasher);
self.look.hash_into(&mut hasher);
active.hash(&mut hasher);
self.grid().hash(&mut hasher);
let key = hasher.finish();
let (look, grid) = (self.look.clone(), self.grid());
let follows = host
.filter(|_| self.plot.height_for(f32::INFINITY).is_some())
.map(Arc::downgrade);
let laid = height;
let paint = move |canvas: &CanvasHandle, at: CanvasMove<'_, Arc<dyn ChartPlot>>| {
if let Some(host) = follows.as_ref().and_then(Weak::upgrade)
&& let Some(wanted) = at.to.height_for(canvas.size().width.max(1.0))
&& (wanted - laid).abs() > 0.5
{
host.rebuild();
}
let motion = ChartMotion {
from: at.from.map(|plot| &**plot),
progress: at.progress,
};
draw(canvas, &**at.to, &look, active, grid, motion)
};
let motion = chart_motion(self.recipe.theme());
let motion = if self.props.still {
CanvasMotion::new(std::time::Duration::ZERO)
} else {
motion
};
let mut canvas = Canvas::new()
.paint_moving(key, motion, self.plot.signature(), Arc::new(self.plot.clone()), paint)
.part(&part)
.width(Dimension::Pct(100.0))
.height(Dimension::Pct(100.0))
.describe("a11y_role", "img")
.describe("a11y_name", self.name());
if let Some(id) = &self.props.id {
canvas = canvas.id(format!("{id}-plot"));
}
let width = self
.plot_width
.unwrap_or_else(|| host.map_or(0.0, |host| host.canvas.width()));
let area = ChartArea { width, height };
if let Some(host) = host {
canvas = self.dress(canvas, host);
if let Some(point) = active {
let tip = self.plot.tip(point);
let said = tip
.rows
.iter()
.map(|(series, value)| format!("{}: {}", self.series_name(*series), (self.look.value_text)(*value)))
.collect::<Vec<_>>()
.join(", ");
let said = if said.is_empty() {
tip.title.clone()
} else {
format!("{}, {said}", tip.title)
};
canvas = canvas.describe("a11y_value", said);
}
}
let mut stack = Stack::new().width(wide).height(height).overflow_visible().child(canvas);
let labels = self.plot.labels(area, &self.look);
if !labels.is_empty() {
for placed in labels {
let label = self.part(placed.part);
stack = stack.child(at(
placed.x,
placed.y,
Row::new()
.offset_by_size(placed.offset.0, placed.offset.1)
.child(label.text(&placed.text).part(&label).nowrap())
.into(),
));
}
}
if let Some(point) = active
&& let Some((x, y)) = self.plot.anchor(area, point)
{
let tip = self.plot.tip(point);
let rows = tip.rows.iter().map(|(series, value)| {
ChartTooltipRow::new(
self
.plot
.tip_color(point, *series, &self.look)
.map(crate::node::BackgroundColor::Color)
.unwrap_or_else(|| self.series_color(*series)),
&self.series_name(*series),
&(self.look.value_text)(*value),
)
});
let mut tooltip = ChartTooltip::new(&tip.title).rows(rows);
if let Some(id) = &self.props.id {
tooltip = tooltip.id(format!("{id}-tooltip"));
}
let beside = self.plot.tip_place() == super::TipPlace::Beside;
let across = if beside {
if x >= TIP_WIDTH + TIP_BESIDE { -1.0 } else { 0.0 }
} else if self.beside.is_some() || x < 70.0 {
0.0
} else if width > 0.0 && x + 70.0 > width {
-1.0
} else {
-0.5
};
let tall = 30.0 + 18.0 * tip.rows.len() as f32;
let (x, top, up) = if beside {
let x = if across < 0.0 { x - TIP_BESIDE } else { x + TIP_BESIDE };
(x, TIP_TOP, 0.0)
} else if y - 8.0 >= tall {
(x, y - 8.0, -1.0)
} else {
(x, y + 8.0, 0.0)
};
stack = stack.child(at(
x,
top,
Row::new()
.offset_by_size(across, up)
.child(tooltip.build(self.recipe.theme()))
.into(),
));
}
let gutter = self.gutter(area);
if self.plot.across() {
return self.with_names(stack.into(), gutter, height);
}
if gutter <= 0.0 {
return self.placed(stack.into());
}
let label = self.part(ChartPart::ValueLabel);
let mut numbers = Stack::new().width(gutter).height(height).overflow_visible();
for tick in self.plot.ticks(area, &self.look) {
numbers = numbers.child(at(
0.0,
tick.position,
Row::new()
.width(gutter - GUTTER_GAP)
.justify(Justify::End)
.offset_by_size(0.0, -0.5)
.child(label.text(&tick.text).part(&label).nowrap())
.into(),
));
}
Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Start)
.child(numbers)
.child(
Column::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_width(Dimension::Px(0.0))
.child(stack),
)
.into()
}
fn gutter(&self, area: ChartArea) -> f32 {
if self.props.loading || self.plot.is_empty() {
return 0.0;
}
if self.plot.across() {
let ChartAxis::Bands { labels, .. } = self.plot.axis() else {
return 0.0;
};
let size = self.recipe.part(ChartPart::AxisLabel).rest().text.size.unwrap_or(11.0);
let widest = labels.iter().map(|name| name.chars().count()).max().unwrap_or(0);
return ((widest as f32 * size * 0.6).ceil() + GUTTER_GAP).min(160.0);
}
if !self.value_axis() {
return 0.0;
}
let size = self.recipe.part(ChartPart::ValueLabel).rest().text.size.unwrap_or(11.0);
let Some(widest) = self
.plot
.ticks(area, &self.look)
.iter()
.map(|tick| tick.text.chars().count())
.max()
else {
return 0.0;
};
(widest as f32 * size * 0.6).ceil() + GUTTER_GAP
}
fn placed(&self, plot: Element) -> Element {
if self.plot_width.is_none() || self.beside.is_some() {
return plot;
}
Row::new()
.width(Dimension::Pct(100.0))
.justify(self.plot_justify)
.overflow_visible()
.child(plot)
.into()
}
fn with_names(&self, plot: Element, gutter: f32, height: f32) -> Element {
let ChartAxis::Bands { labels, gap } = self.plot.axis() else {
return plot;
};
let label = self.part(ChartPart::AxisLabel);
let names = Column::new()
.width(gutter)
.height(height)
.spacing(gap)
.describe("a11y_hidden", "true")
.with_children(labels.iter().map(|name| {
Row::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_height(Dimension::Px(0.0))
.width(gutter - GUTTER_GAP)
.justify(Justify::End)
.align_items(Alignment::Center)
.child(
label
.text(name)
.part(&label)
.nowrap()
.text_overflow(TextOverflow::Elipsis)
.min_width(Dimension::Px(0.0)),
)
}));
Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Start)
.child(names)
.child(
Column::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_width(Dimension::Px(0.0))
.child(plot),
)
.into()
}
fn dress(&self, canvas: Canvas, host: &Arc<ChartHostState>) -> Canvas {
let (moved, left, pressed, keyed, focus, blur) = (
host.clone(),
host.clone(),
host.clone(),
host.clone(),
host.clone(),
host.clone(),
);
let (plot, plot_keys, plot_focus) = (self.plot.clone(), self.plot.clone(), self.plot.clone());
let (selected, selected_keys) = (self.props.on_select.clone(), self.props.on_select.clone());
let reference = host.canvas.clone();
canvas
.ref_element(host.canvas.clone())
.tab_index(0)
.on_mouse_move(move |event: MouseEvent| {
let Some(canvas) = moved.canvas.as_canvas() else {
return;
};
let size = canvas.size();
let point = canvas.point_from_window(event.x, event.y).and_then(|(x, y)| {
plot.point_at(
ChartArea {
width: size.width,
height: size.height,
},
x,
y,
)
});
moved.hover(point);
})
.on_mouse_leave(move || left.hover(None))
.on_click(move |_: MouseEvent| {
let point = *pressed.hovered.lock();
if let Some(point) = point {
*pressed.focused.lock() = Some(point);
for handler in &selected {
handler(point);
}
}
})
.on_focus(move || {
let mut focused = focus.focused.lock();
if focused.is_none() {
let counts = plot_focus.counts();
*focused = counts
.iter()
.position(|count| *count > 0)
.map(|series| ChartPoint::new(series, 0));
}
drop(focused);
focus.rebuild();
})
.on_blur(move || blur.rebuild())
.on_key_down(move |event: KeyboardEvent| {
if !reference.focused() || event.alt || event.ctrl || event.meta {
return;
}
let from = (*keyed.focused.lock()).unwrap_or_default();
match event.key.as_str() {
"Enter" | " " => {
event.prevent_default();
for handler in &selected_keys {
handler(from);
}
}
key => {
if let Some(to) = step(&plot_keys.counts(), from, key) {
event.prevent_default();
*keyed.focused.lock() = Some(to);
*keyed.hovered.lock() = None;
keyed.rebuild();
}
}
}
})
.describe(
"a11y_roledescription",
crate::ui::current_locale().data.chart_role.clone(),
)
}
fn series_name(&self, series: usize) -> String {
self
.series
.get(series)
.map_or_else(String::new, |series| series.name().to_owned())
}
fn series_color(&self, series: usize) -> crate::node::BackgroundColor {
self
.series
.get(series)
.and_then(|series| series.given_color().cloned())
.unwrap_or_else(|| series_color(series).into())
}
fn grid(&self) -> bool {
self.props.grid.unwrap_or(false)
}
fn value_axis(&self) -> bool {
self.props.value_axis.unwrap_or(false)
}
fn axis_element(&self) -> Option<Element> {
if self.props.loading || self.plot.is_empty() {
return None;
}
let label = self.part(ChartPart::AxisLabel);
let mut row = Row::new()
.part(&self.part(ChartPart::Axis))
.width(Dimension::Pct(100.0))
.describe("a11y_hidden", "true");
let gutter = self.gutter(ChartArea {
width: 0.0,
height: self.plot_height(),
});
if gutter > 0.0 {
row = row.padding_left(gutter);
}
let text = |name: &str| {
label
.text(name)
.part(&label)
.nowrap()
.text_overflow(TextOverflow::Elipsis)
.min_width(Dimension::Px(0.0))
};
if self.plot.across() {
if !self.value_axis() {
return None;
}
let value = self.part(ChartPart::ValueLabel);
let area = ChartArea {
width: 1.0,
height: self.plot_height(),
};
let mut numbers = Row::new().width(Dimension::Pct(100.0)).overflow_visible();
let mut before = 0.0;
for tick in self.plot.ticks(area, &self.look) {
let share = tick.position.clamp(0.0, 1.0);
let across = if share < 0.001 {
0.0
} else if share > 0.999 {
-1.0
} else {
-0.5
};
numbers = numbers
.child(Row::new().flex_full(share - before, 0.0, Some(0.0)))
.child(
Row::new()
.width(1.0)
.overflow_visible()
.child(value.text(&tick.text).part(&value).nowrap().offset_by_size(across, 0.0)),
);
before = share;
}
numbers = numbers.child(Row::new().flex_full(1.0 - before, 0.0, Some(0.0)));
return Some(row.child(numbers).into());
}
match self.plot.axis() {
ChartAxis::None => None,
ChartAxis::Bands { labels, gap } => Some(
row
.spacing(gap)
.with_children(labels.iter().map(|name| {
Row::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_width(Dimension::Px(0.0))
.justify(Justify::Center)
.child(text(name))
}))
.into(),
),
ChartAxis::Spread(labels) => Some(
row
.justify(Justify::SpaceBetween)
.with_children(labels.iter().map(|name| text(name)))
.into(),
),
}
}
fn legend_element(&mut self) -> Option<Element> {
if let Some(own) = self.own_legend.take() {
return (self.props.legend != Some(false) && !self.props.loading).then_some(own);
}
if !self.props.legend.unwrap_or(self.series.len() > 1) || self.props.loading {
return None;
}
let values = self
.beside
.as_ref()
.map(|beside| beside.values.as_slice())
.unwrap_or(&[]);
let items = self.series.iter().enumerate().map(|(index, series)| {
let item = ChartLegendItem::new(series.name(), self.series_color(index));
match values.get(index).filter(|value| !value.is_empty()) {
Some(value) => item.value(value),
None => item,
}
});
let mut legend = ChartLegend::new(items).shape(ChartLegendShape::Dot);
if let Some(beside) = &self.beside {
legend = legend.orientation(Orientation::Vertical).size(beside.size);
}
if let Some(write) = &self.props.write_hidden {
let write = write.clone();
legend = legend.hidden_controlled(self.props.hidden.clone(), move |next| write(next));
}
for handler in &self.props.on_hidden_change {
let handler = handler.clone();
legend = legend.on_hidden_change(move |next| handler(next));
}
if let Some(id) = &self.props.id {
legend = legend.id(format!("{id}-legend"));
}
Some(legend.build(self.recipe.theme()))
}
pub fn mount(
ctx: &mut Ctx,
key: Option<Arc<str>>,
make: impl Fn(&Theme) -> ChartFrame + Send + Sync + 'static,
) -> Element {
let props = ChartHostProps { make: Arc::new(make) };
match key {
Some(key) => ctx.mount_keyed::<ChartHost>(&key, props),
None => ctx.mount::<ChartHost>(props),
}
}
}
const GUTTER_GAP: f32 = 8.0;
const TIP_WIDTH: f32 = 140.0;
const TIP_BESIDE: f32 = 10.0;
const TIP_TOP: f32 = 4.0;
fn at(x: f32, y: f32, child: Element) -> Row {
Row::new()
.absolute(x, y, Dimension::Pct(100.0), Dimension::Pct(100.0))
.align_items(Alignment::Start)
.overflow_visible()
.inert(true)
.child(child)
}
pub fn chart_motion(theme: &Theme) -> CanvasMotion {
CanvasMotion::new(theme.duration_value(MotionDuration::Slow)).easing(theme.easing_value(MotionEasing::Standard))
}
fn draw(
canvas: &CanvasHandle,
plot: &dyn ChartPlot,
look: &ChartLook,
active: Option<ChartPoint>,
grid: bool,
motion: ChartMotion<'_>,
) {
let size = canvas.size();
let area = ChartArea {
width: size.width,
height: size.height,
};
let scale = canvas.scale_factor().max(1.0);
let context = canvas.context_2d();
context.reset();
context.clear();
let line = (scale.round().max(1.0)) / scale;
for tick in plot.ticks(area, look) {
if !tick.baseline && !grid {
continue;
}
let color = look.color(if tick.baseline {
ChartPart::Baseline
} else {
ChartPart::Grid
});
context.set_fill_style(color);
if plot.across() {
let x = snap(tick.position.max(0.0).min(area.width - line), scale);
context.fill_rect(x, 0.0, line, area.height);
} else {
let y = snap((tick.position - line).max(0.0).min(area.height - line), scale);
context.fill_rect(0.0, y, area.width, line);
}
}
plot.paint_moving(&context, area, look, active, motion);
canvas.set_items(plot.items(area, look));
}
pub fn snap(value: f32, scale: f32) -> f32 {
(value * scale).round() / scale
}
pub struct ChartView {
pub beside: bool,
pub plot_width: Option<f32>,
pub title: Option<Arc<str>>,
pub description: Option<Arc<str>>,
pub name: Arc<str>,
pub plot: Element,
pub axis: Option<Element>,
pub legend: Option<Element>,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl ChartView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn root(&self) -> Column {
let mut root = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(ChartPart::Root))
.describe("a11y_role", "figure")
.describe("a11y_name", self.name.clone());
if let Some(description) = &self.description {
root = root.describe("a11y_description", description.clone());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
pub fn header(&self) -> Option<Column> {
if self.title.is_none() && self.description.is_none() {
return None;
}
let mut header = Column::new()
.part(&self.part(ChartPart::Header))
.align_items(Alignment::Stretch);
if let Some(title) = &self.title {
let part = self.part(ChartPart::Title);
header = header.child(part.text(title).part(&part));
}
if let Some(description) = &self.description {
let part = self.part(ChartPart::Description);
header = header.child(part.text(description).part(&part));
}
Some(header)
}
pub fn render(mut self) -> Element {
let mut root = self.root();
if let Some(header) = self.header() {
root = root.child(header);
}
let plot = std::mem::replace(&mut self.plot, Row::new().into());
if self.beside {
let gap = self
.part(ChartPart::Body)
.rest()
.gap
.map(|gap| gap.resolve(&self.theme().spacing(), 0.0))
.unwrap_or(20.0);
let mut body = Stack::with(StackAlignment::CenterStart, Vec::<Element>::new())
.width(Dimension::Pct(100.0))
.overflow_visible();
if let Some(legend) = self.legend.take() {
body = body.child(
Row::new()
.width(Dimension::Pct(100.0))
.padding_left(self.plot_width.unwrap_or(0.0) + gap)
.child(
Column::new()
.flex_full(1.0, 1.0, Some(0.0))
.min_width(Dimension::Px(0.0))
.child(legend),
),
);
}
return root.child(body.child(plot)).into();
}
root = root.child(plot);
if let Some(axis) = self.axis.take() {
root = root.child(axis);
}
if let Some(legend) = self.legend.take() {
root = root.child(legend);
}
root.into()
}
}
pub fn chart_recipe() -> Recipe {
use ChartPart::{
Axis, AxisLabel, Baseline, Body, Cursor, Description, Empty, Grid, Header, Plot, Root, Title, ValueLabel,
};
use ChartSize::Sm;
use PaletteColor::{Card, CardForeground, Input, MutedForeground};
Recipe::new()
.base(Root, |s| {
s.width(Length::Fill)
.background(Card)
.foreground(CardForeground)
.radius(RadiusSize::Xl)
.border(Edge::inside(BorderSize::Sm, PaletteColor::Border))
.shadow(ShadowStyle::Sm)
.padding_x(24.0)
.padding_y(24.0)
.gap(20.0)
})
.size(Sm, Root, |s| s.padding_x(20.0).padding_y(20.0).gap(16.0))
.base(Header, |s| s.gap(4.0))
.size(Sm, Header, |s| s.gap(3.0))
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(16.0)
.weight(FontWeight::SemiBold)
.foreground(CardForeground)
})
.size(Sm, Title, |s| s.font_size(15.0))
.base(Description, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
.size(Sm, Description, |s| s.font_size(12.0))
.base(Plot, |s| s.height(160.0))
.size(Sm, Plot, |s| s.height(140.0))
.focus_visible(Plot, |s| {
s.outline(Outline::new(BorderSize::Md, PaletteColor::Ring).offset(2.0))
})
.base(Grid, |s| s.background(PaletteColor::Border).opacity(0.6))
.base(Baseline, |s| s.background(PaletteColor::Border))
.base(Cursor, |s| s.background(Input))
.base(Axis, |s| s.gap(12.0))
.base(AxisLabel, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(ValueLabel, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Empty, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
.base(Body, |s| s.gap(20.0))
.size(Sm, Body, |s| s.gap(18.0))
}
struct ChartHostProps {
make: Arc<dyn Fn(&Theme) -> ChartFrame + Send + Sync>,
}
impl PartialEq for ChartHostProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for ChartHostProps {}
struct ChartHost {
state: Arc<ChartHostState>,
_marker: PhantomData<()>,
}
impl Component for ChartHost {
type Props = ChartHostProps;
fn create(ctx: &mut Ctx) -> Self {
Self {
state: Arc::new(ChartHostState {
hovered: Mutex::new(None),
focused: Mutex::new(None),
canvas: ctx.element_ref(),
revision: ctx.signal(0_u64),
}),
_marker: PhantomData,
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let _ = self.state.revision.get();
let make = ctx.props::<ChartHostProps>().make.clone();
let frame = make(¤t_theme());
let counts = frame.plot.counts();
let fits = |point: &Option<ChartPoint>| {
point.is_some_and(|point| counts.get(point.series).is_some_and(|count| point.index < *count))
};
for held in [&self.state.hovered, &self.state.focused] {
let mut held = held.lock();
if held.is_some() && !fits(&held) {
*held = None;
}
}
frame.render_with(Some(self.state.clone()))
}
}