use std::fmt::Write as _;
use dioxus::prelude::*;
use super::activation::{ChartDatumActivation, DatumAction, motion_key};
use super::format::js_number;
use super::frame::{
ChartFrame, ChartPresentation, activate_on_click, chart_data_table, chart_legend,
datum_actions, detail_label, plot_label, render_frame, serialized,
};
use super::geometry::{
BarChartLayout, BarChartOrientation, BarGeometryOptions, COMPACT_AXIS_LABEL_SIZE, bar_geometry,
chart_size,
};
use super::model::{ChartDatum, ChartLabels, ChartSeries, ChartX, format_with, summarize};
use super::native_paints::paint_attributes;
use super::scale::{
CategoryTick, CategoryTickOptions, align_series, category_ticks, chart_categories,
fitted_label, has_chart_data, scale_value,
};
use crate::class::{Glass, compose};
#[derive(Props, Clone, PartialEq)]
pub struct BarChartProps {
pub width: Option<f64>,
pub height: Option<f64>,
#[props(default)]
pub series: Vec<ChartSeries>,
#[props(default)]
pub layout: BarChartLayout,
#[props(default)]
pub orientation: BarChartOrientation,
pub category_width: Option<f64>,
pub format_value: Option<Callback<f64, String>>,
pub format_category: Option<Callback<ChartX, String>>,
#[props(into)]
pub empty_label: Option<String>,
pub labels: Option<ChartLabels>,
pub show_legend: Option<bool>,
#[props(default = true)]
pub show_table: bool,
pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
#[props(into)]
pub heading: Option<String>,
#[props(into)]
pub description: Option<String>,
#[props(into)]
pub value: Option<String>,
#[props(into)]
pub summary: Option<String>,
#[props(into)]
pub caption: Option<String>,
#[props(default)]
pub presentation: ChartPresentation,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = figure)]
pub attributes: Vec<Attribute>,
}
struct TickText {
key: String,
anchor: &'static str,
x: String,
label: String,
}
struct BarRect {
paints: Vec<Attribute>,
key: String,
class: &'static str,
motion_key: String,
datum: Option<String>,
x: String,
y: String,
width: String,
height: String,
title: String,
hit: [String; 4],
action: Option<DatumAction>,
}
#[component]
#[allow(clippy::too_many_lines)]
pub fn BarChart(props: BarChartProps) -> Element {
let native_paints =
super::native_paints::use_native_chart_paints(super::model::ChartTone::Series1);
let labels = props.labels.clone().unwrap_or_default();
let format_value = props.format_value.as_ref();
let format_category = props.format_category.as_ref();
let horizontal = props.orientation == BarChartOrientation::Horizontal;
let categories = chart_categories(&props.series);
let aligned: Vec<ChartSeries> = props
.series
.iter()
.map(|item| align_series(item, &categories))
.collect();
let geometry = bar_geometry(
&aligned,
&BarGeometryOptions {
axis_font_size: Some(COMPACT_AXIS_LABEL_SIZE),
category_width: Some(props.category_width.unwrap_or(160.0)),
domain: None,
format_category,
format_value,
height: chart_size(props.height, 240.0),
layout: props.layout,
orientation: props.orientation,
width: chart_size(props.width, 640.0),
},
);
let has_data = has_chart_data(&aligned);
let show_legend = props.show_legend.unwrap_or(props.series.len() > 1);
let ticks = &geometry.ticks;
let margin = geometry.margin;
let plot_end = geometry.width - margin.right;
let category_labels: Vec<String> = geometry
.categories
.iter()
.map(|category| category.label.clone())
.collect();
let category_positions: Vec<f64> = geometry
.categories
.iter()
.map(|category| category.x)
.collect();
let tick_texts = |font_size: Option<f64>| -> Vec<TickText> {
let mut options = CategoryTickOptions::new(margin.left, plot_end)
.bounds(0.0, geometry.width)
.positions(&category_positions);
if let Some(size) = font_size {
options = options.font_size(size);
}
category_ticks(&category_labels, options)
.into_iter()
.map(|tick| TickText {
key: tick.index.to_string(),
anchor: CategoryTick::ANCHOR,
x: js_number(tick.position),
label: tick.label,
})
.collect()
};
let regular_ticks = tick_texts(None);
let compact_ticks = tick_texts(Some(COMPACT_AXIS_LABEL_SIZE));
let value_positions: Vec<f64> = ticks
.iter()
.map(|tick| scale_value(*tick, geometry.domain, margin.left, plot_end))
.collect();
let value_ticks: Vec<TickText> = category_ticks(
&geometry.tick_labels,
CategoryTickOptions::new(margin.left, plot_end)
.bounds(0.0, geometry.width)
.font_size(COMPACT_AXIS_LABEL_SIZE)
.positions(&value_positions),
)
.into_iter()
.map(|tick| TickText {
key: tick.index.to_string(),
anchor: CategoryTick::ANCHOR,
x: js_number(tick.position),
label: tick.label,
})
.collect();
let grid: Vec<(String, String, String)> = ticks
.iter()
.zip(&geometry.tick_labels)
.map(|(tick, label)| {
let coordinate = if horizontal {
scale_value(*tick, geometry.domain, margin.left, plot_end)
} else {
scale_value(
*tick,
geometry.domain,
geometry.height - margin.bottom,
margin.top,
)
};
(js_number(*tick), js_number(coordinate), label.clone())
})
.collect();
let category_rows: Vec<(String, String, String, String)> = geometry
.categories
.iter()
.map(|category| {
(
category.category.key(),
js_number(category.x),
js_number(category.y),
fitted_label(&category.label, margin.left - 16.0),
)
})
.collect();
let on_activate = props.on_datum_activate;
let bars: Vec<BarRect> = geometry
.marks
.iter()
.map(|mark| {
let context = format!(
"{} · {}: {}",
detail_label(&aligned, &mark.category, format_category),
mark.series_label,
format_with(format_value, mark.value)
);
let action = on_activate.and_then(|_| {
let mut datum = ChartDatum::new(mark.category.clone(), mark.value);
datum.id.clone_from(&mark.datum_id);
DatumAction::new(
ChartDatumActivation::series(&mark.series_id, &datum),
&context,
&labels,
)
});
let hit_width = mark.width.max(12.0);
let hit_height = mark.height.max(12.0);
BarRect {
paints: paint_attributes(native_paints, "bar", Some(mark.tone)),
key: format!("{}:{}", mark.series_id, mark.category.key()),
class: mark.tone.class_name(),
motion_key: motion_key(&mark.series_id, mark.datum_id.as_ref(), &mark.category),
datum: serialized(action.as_ref()),
x: js_number(mark.x),
y: js_number(mark.y),
width: js_number(mark.width),
height: js_number(mark.height),
title: context,
hit: [
js_number(hit_width),
js_number(hit_height),
js_number(mark.x - (12.0 - mark.width).max(0.0) / 2.0),
js_number(mark.y - (12.0 - mark.height).max(0.0) / 2.0),
],
action,
}
})
.collect();
let actions: Vec<Option<DatumAction>> = bars.iter().map(|bar| bar.action.clone()).collect();
let summary = props
.summary
.clone()
.or_else(|| Some(labels.summary(summarize(&aligned, format_value))));
let plot_name = plot_label(
&props.attributes,
props.heading.as_ref(),
&labels.chart_data,
);
let frame = ChartFrame {
chart_class: Some(compose([Some("ui-bar-chart"), props.class.as_deref()])),
heading: props.heading.clone(),
description: props.description.clone(),
value: props.value.clone(),
summary,
caption: props.caption.clone(),
presentation: props.presentation,
glass: props.glass,
activation: on_activate.is_some(),
attributes: props.attributes.clone(),
on_mounted: None,
};
let view_box = format!(
"0 0 {} {}",
js_number(geometry.width),
js_number(geometry.height)
);
let viewbox_width = js_number(geometry.width);
let viewbox_height = js_number(geometry.height);
let mut svg_style = format!("--ui-chart-viewbox-width: {viewbox_width}");
if native_paints.is_some() {
let _ = write!(
svg_style,
";width:{viewbox_width}px;height:auto;max-width:100%;min-width:0;aspect-ratio:{viewbox_width}/{viewbox_height}"
);
}
let left = js_number(margin.left);
let right = js_number(plot_end);
let top = js_number(margin.top);
let bottom = js_number(geometry.height - margin.bottom);
let label_x = js_number(margin.left - 8.0);
let category_y = js_number(geometry.height - 20.0);
let value_y = js_number(geometry.height - 6.0);
let body = rsx! {
if show_legend && has_data {
{chart_legend(&labels.chart_legend, &props.series)}
}
if !has_data {
p { class: "ui-chart__empty", role: "status",
"{props.empty_label.clone().unwrap_or_else(|| labels.empty.clone())}"
}
}
div {
aria_label: "{plot_name}",
class: "ui-chart__plot",
role: "region",
tabindex: "0",
hidden: (!has_data).then_some(true),
svg {
"aria-hidden": "true",
"preserveAspectRatio": "xMidYMid meet",
"style": "{svg_style}",
"viewBox": "{view_box}",
width: native_paints.map(|_| viewbox_width.clone()),
height: native_paints.map(|_| viewbox_height.clone()),
g { class: "ui-chart__grid",
for (key, coordinate, text) in grid {
if horizontal {
line {
key: "{key}", x1: "{coordinate}", x2: "{coordinate}", y1: "{top}", y2: "{bottom}",
..paint_attributes(native_paints, "grid-line", None),
}
} else {
line {
key: "{key}-line", x1: "{left}", x2: "{right}", y1: "{coordinate}", y2: "{coordinate}",
..paint_attributes(native_paints, "grid-line", None),
}
text {
x: "{label_x}", y: "{coordinate}",
..paint_attributes(native_paints, "grid-label", None),
"{text}"
}
}
}
}
g { class: "ui-chart__axis-labels",
..paint_attributes(native_paints, "axis-label", None),
if horizontal {
for (key, x, y, label) in category_rows {
text {
key: "{key}",
"dominant-baseline": "middle",
"text-anchor": "end",
x: "{x}",
y: "{y}",
"{label}"
}
}
} else {
g { class: "ui-chart__category-labels--regular",
for tick in regular_ticks {
text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{category_y}", "{tick.label}" }
}
}
g { class: "ui-chart__category-labels--compact",
..paint_attributes(native_paints, "compact-labels", None),
for tick in compact_ticks {
text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{category_y}", "{tick.label}" }
}
}
}
}
if horizontal {
g { class: "ui-chart__axis-labels",
..paint_attributes(native_paints, "axis-label", None),
for tick in value_ticks {
text { key: "{tick.key}", "text-anchor": tick.anchor, x: "{tick.x}", y: "{value_y}", "{tick.label}" }
}
}
}
g { class: "ui-bar-chart__marks",
for bar in bars.iter() {
rect {
key: "{bar.key}",
class: bar.class,
"data-ui-chart-motion-key": "{bar.motion_key}",
"data-ui-chart-datum": bar.datum.clone(),
height: "{bar.height}",
rx: native_paints.is_none().then_some("4"),
width: "{bar.width}",
x: "{bar.x}",
y: "{bar.y}",
onclick: activate_on_click(bar.action.as_ref(), on_activate),
..bar.paints.clone(),
title { "{bar.title}" }
}
}
if on_activate.is_some() {
for bar in bars.iter() {
rect {
key: "hit-{bar.key}",
class: "ui-chart__datum-hit",
width: "{bar.hit[0]}",
height: "{bar.hit[1]}",
x: "{bar.hit[2]}",
y: "{bar.hit[3]}",
"data-ui-chart-datum": bar.datum.clone(),
onclick: activate_on_click(bar.action.as_ref(), on_activate),
..paint_attributes(native_paints, "datum-hit", None),
}
}
}
}
}
}
if props.show_table && has_data {
{chart_data_table(&categories, format_category, format_value, &labels, &props.series)}
}
if on_activate.is_some() {
{datum_actions(&actions, &labels.explore_data, on_activate)}
}
};
render_frame(frame, body)
}