use dioxus::prelude::*;
use super::activation::{ChartDatumActivation, DatumAction};
use super::model::{
ChartLabels, ChartSeries, ChartTone, ChartX, format_category_with, format_with,
};
use super::scale::{LabelContext, align_series, category_label};
use crate::class::{Glass, compose};
use crate::{Button, ButtonVariant};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChartPresentation {
#[default]
Default,
Bare,
}
#[derive(Props, Clone, PartialEq)]
pub struct ChartProps {
#[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>,
pub children: Element,
}
#[component]
pub fn Chart(props: ChartProps) -> Element {
let frame = ChartFrame {
chart_class: props.class.clone(),
heading: props.heading,
description: props.description,
value: props.value,
summary: props.summary,
caption: props.caption,
presentation: props.presentation,
glass: props.glass,
activation: false,
attributes: props.attributes,
on_mounted: None,
};
render_frame(frame, props.children)
}
#[derive(Default)]
pub(crate) struct ChartFrame {
pub(crate) chart_class: Option<String>,
pub(crate) heading: Option<String>,
pub(crate) description: Option<String>,
pub(crate) value: Option<String>,
pub(crate) summary: Option<String>,
pub(crate) caption: Option<String>,
pub(crate) presentation: ChartPresentation,
pub(crate) glass: Glass,
pub(crate) activation: bool,
pub(crate) attributes: Vec<Attribute>,
pub(crate) on_mounted: Option<EventHandler<std::rc::Rc<MountedData>>>,
}
macro_rules! chart_frame {
($props:expr, $class:expr, $summary:expr) => {
$crate::charts::frame::ChartFrame {
chart_class: Some($class),
heading: $props.heading.clone(),
description: $props.description.clone(),
value: $props.value.clone(),
summary: $summary,
caption: $props.caption.clone(),
presentation: $props.presentation,
glass: $props.glass,
activation: false,
attributes: $props.attributes.clone(),
on_mounted: None,
}
};
}
pub(crate) use chart_frame;
pub(crate) fn render_frame(frame: ChartFrame, children: Element) -> Element {
let glass = frame.glass.class("ui-chart");
let class = compose([
Some("ui-chart"),
(frame.presentation == ChartPresentation::Bare).then_some("ui-chart--bare"),
glass.as_deref(),
frame.chart_class.as_deref(),
]);
let on_mounted = frame.on_mounted;
let has_header = non_empty(frame.heading.as_ref()).is_some()
|| non_empty(frame.description.as_ref()).is_some()
|| non_empty(frame.value.as_ref()).is_some();
rsx! {
figure {
class,
"data-ui-chart-activation": frame.activation.then_some("true"),
"data-ui-chart-adapter": frame.activation.then_some("dioxus"),
onmounted: move |event| {
if let Some(handler) = on_mounted {
handler.call(event.data());
}
},
..frame.attributes,
if has_header {
header {
div { class: "ui-chart__heading",
if let Some(heading) = non_empty(frame.heading.as_ref()) {
h3 { "{heading}" }
}
if let Some(description) = non_empty(frame.description.as_ref()) {
p { "{description}" }
}
}
if let Some(value) = non_empty(frame.value.as_ref()) {
strong { "data-ui-chart-value": "true", "{value}" }
}
}
}
if let Some(summary) = non_empty(frame.summary.as_ref()) {
p { class: "ui-sr-only", "data-ui-chart-summary": "true", "{summary}" }
}
{children}
if let Some(caption) = non_empty(frame.caption.as_ref()) {
figcaption { "{caption}" }
}
}
}
}
fn non_empty(value: Option<&String>) -> Option<&String> {
value.filter(|text| !text.is_empty())
}
pub(crate) fn attribute_text(attributes: &[Attribute], name: &str) -> Option<String> {
attributes
.iter()
.find(|attribute| attribute.name == name)
.and_then(|attribute| match &attribute.value {
dioxus::dioxus_core::AttributeValue::Text(text) => Some(text.clone()),
_ => None,
})
}
pub(crate) fn plot_label(
attributes: &[Attribute],
heading: Option<&String>,
fallback: &str,
) -> String {
attribute_text(attributes, "aria-label")
.or_else(|| heading.cloned())
.unwrap_or_else(|| fallback.to_string())
}
pub(crate) fn chart_legend(label: &str, series: &[ChartSeries]) -> Element {
rsx! {
ul { aria_label: "{label}", class: "ui-chart__legend",
for (index, item) in series.iter().enumerate() {
li { key: "{item.id}", class: ChartTone::resolve(item.tone, index).class_name(),
span { aria_hidden: "true" }
"{item.label}"
}
}
}
}
}
pub(crate) fn table_value(
value: Option<f64>,
format_value: Option<&Callback<f64, String>>,
not_available: &str,
) -> String {
match value.filter(|value| value.is_finite()) {
Some(value) => format_with(format_value, value),
None => not_available.to_string(),
}
}
type TableRow = (String, String, Vec<(String, String)>);
pub(crate) fn chart_data_table(
categories: &[ChartX],
format_category: Option<&Callback<ChartX, String>>,
format_value: Option<&Callback<f64, String>>,
labels: &ChartLabels,
series: &[ChartSeries],
) -> Element {
let aligned: Vec<ChartSeries> = series
.iter()
.map(|item| align_series(item, categories))
.collect();
let rows: Vec<TableRow> = categories
.iter()
.map(|category| {
let cells = aligned
.iter()
.map(|item| {
let datum = item.data.iter().find(|candidate| candidate.x == *category);
let text = datum
.and_then(|datum| datum.label.clone())
.unwrap_or_else(|| {
table_value(
datum.and_then(|datum| datum.y),
format_value,
&labels.not_available,
)
});
(item.id.clone(), text)
})
.collect();
(
category.key(),
category_label(&aligned, category, format_category, LabelContext::Detail),
cells,
)
})
.collect();
rsx! {
details { class: "ui-chart__data",
summary { "{labels.view_data}" }
div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
table {
thead {
tr {
th { scope: "col", "{labels.category}" }
for item in series.iter() {
th { key: "{item.id}", scope: "col", "{item.label}" }
}
}
}
tbody {
for (key, label, cells) in rows {
tr { key: "{key}",
th { scope: "row", "{label}" }
for (id, text) in cells {
td { key: "{id}", "{text}" }
}
}
}
}
}
}
}
}
}
pub(crate) fn datum_actions(
actions: &[Option<DatumAction>],
label: &str,
on_activate: Option<EventHandler<ChartDatumActivation>>,
) -> Element {
let available: Vec<DatumAction> = actions.iter().flatten().cloned().collect();
if available.is_empty() {
return rsx! {};
}
rsx! {
details { class: "ui-chart__actions", "data-ui-chart-actions": "true",
summary { "{label}" }
ul {
for action in available {
li { key: "{action.serialized}",
Button {
variant: ButtonVariant::Ghost,
"data-ui-chart-datum": action.serialized.clone(),
onclick: move |_| {
if let Some(handler) = on_activate {
handler.call(action.detail.clone());
}
},
"{action.label}"
}
}
}
}
}
}
}
pub(crate) fn activate_on_click(
action: Option<&DatumAction>,
on_activate: Option<EventHandler<ChartDatumActivation>>,
) -> impl FnMut(MouseEvent) + 'static {
let detail = action.map(|action| action.detail.clone());
move |event: MouseEvent| {
let primary = event
.trigger_button()
.is_none_or(|button| button == dioxus::html::input_data::MouseButton::Primary);
if !primary {
return;
}
if let (Some(handler), Some(detail)) = (on_activate, detail.clone()) {
handler.call(detail);
}
}
}
pub(crate) fn serialized(action: Option<&DatumAction>) -> Option<String> {
action.map(|action| action.serialized.clone())
}
pub(crate) fn detail_label(
series: &[ChartSeries],
category: &ChartX,
format_category: Option<&Callback<ChartX, String>>,
) -> String {
category_label(series, category, format_category, LabelContext::Detail)
}
pub(crate) fn plain_category(
category: &ChartX,
format: Option<&Callback<ChartX, String>>,
) -> String {
format_category_with(format, category)
}