1use topcoat::{
5 context::Cx,
6 view::{BoxView, ViewExt, view},
7};
8
9use crate::{
10 Color, Text,
11 display::{Number, NumberFormat},
12};
13
14mod scale;
15
16use scale::Axis;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20enum ChartKind {
21 Line,
23 Bar,
25}
26
27impl ChartKind {
28 const fn name(self) -> &'static str {
30 match self {
31 Self::Line => "line",
32 Self::Bar => "bar",
33 }
34 }
35}
36
37#[derive(Clone, Debug)]
52pub struct Chart {
53 kind: ChartKind,
54 heading: Option<Text>,
55 description: Option<Text>,
56 labels: Vec<Text>,
57 series: Vec<Series>,
58}
59
60impl Chart {
61 pub fn line(labels: impl IntoIterator<Item = impl Into<Text>>) -> Self {
63 Self::new(ChartKind::Line, labels)
64 }
65
66 pub fn bar(labels: impl IntoIterator<Item = impl Into<Text>>) -> Self {
68 Self::new(ChartKind::Bar, labels)
69 }
70
71 fn new(kind: ChartKind, labels: impl IntoIterator<Item = impl Into<Text>>) -> Self {
72 Self {
73 kind,
74 heading: None,
75 description: None,
76 labels: labels.into_iter().map(Into::into).collect(),
77 series: Vec::new(),
78 }
79 }
80
81 #[must_use]
83 pub fn heading(mut self, heading: impl Into<Text>) -> Self {
84 self.heading = Some(heading.into());
85 self
86 }
87
88 #[must_use]
90 pub fn description(mut self, description: impl Into<Text>) -> Self {
91 self.description = Some(description.into());
92 self
93 }
94
95 #[must_use]
97 pub fn series(mut self, series: Series) -> Self {
98 self.series.push(series);
99 self
100 }
101}
102
103#[derive(Clone, Debug)]
105pub struct Series {
106 label: Text,
107 values: Vec<f64>,
108 color: Option<Color>,
109}
110
111impl Series {
112 pub fn new(label: impl Into<Text>, values: impl IntoIterator<Item = f64>) -> Self {
115 Self {
116 label: label.into(),
117 values: values.into_iter().collect(),
118 color: None,
119 }
120 }
121
122 #[must_use]
125 pub const fn color(mut self, color: Color) -> Self {
126 self.color = Some(color);
127 self
128 }
129}
130
131const PALETTE: [Color; 5] = [
133 Color::Primary,
134 Color::Info,
135 Color::Success,
136 Color::Warning,
137 Color::Danger,
138];
139
140const PLOT: f64 = 100.0;
142const BAR_GROUP: f64 = 0.7;
144const MAX_AXIS_LABELS: usize = 12;
146
147pub fn chart(cx: &Cx, chart: Chart) -> BoxView<'_> {
163 let Chart {
164 kind,
165 heading,
166 description,
167 labels,
168 series,
169 } = chart;
170 let heading = heading.map(|heading| heading.localize(cx));
171 let description = description.map(|description| description.localize(cx));
172 let labels: Vec<String> = labels.iter().map(|label| label.localize(cx)).collect();
173 let series: Vec<Drawn> = series
174 .into_iter()
175 .enumerate()
176 .map(|(index, series)| Drawn::new(cx, series, index, labels.len()))
177 .collect();
178 let axis = Axis::over(
179 series
180 .iter()
181 .flat_map(|drawn| drawn.values.iter().flatten()),
182 );
183 let plot = axis.map(|axis| plot(cx, kind, &axis, &labels, &series));
184 let empty = crate::t!(cx, "tablo-chart-empty");
185 let legend: Vec<(String, &'static str)> = if series.len() > 1 {
186 series
187 .iter()
188 .map(|drawn| (drawn.label.clone(), drawn.color.dot_class()))
189 .collect()
190 } else {
191 Vec::new()
192 };
193 let table = data_table(cx, heading.clone(), &labels, &series);
194 view! {
197 <section
198 data-chart=(kind.name())
199 data-slot="card"
200 class="relative flex flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-card"
201 >
202 if heading.is_some() || description.is_some() {
203 <div
204 class="flex flex-col gap-1 border-b border-rule bg-head px-5 py-3.5"
205 data-slot="card-header"
206 >
207 if let Some(heading) = heading {
208 <h2 class="tablo-heading text-[0.9375rem] leading-snug">
209 (heading)
210 </h2>
211 }
212 if let Some(description) = description {
213 <p class="text-sm text-muted-foreground">(description)</p>
214 }
215 </div>
216 }
217 <div class="flex flex-col gap-4 p-5">
218 if let Some(plot) = plot {
219 (plot)
220 } else {
221 <p class="py-12 text-center text-sm text-muted-foreground">
222 (empty)
223 </p>
224 }
225 if !legend.is_empty() {
226 <ul
227 class="flex flex-wrap gap-x-4 gap-y-1 text-sm text-muted-foreground"
228 aria-hidden="true"
229 >
230 for (label, dot) in legend {
231 <li class="flex items-center gap-1.5">
232 <span class=(dot)></span>
233 (label)
234 </li>
235 }
236 </ul>
237 }
238 </div>
239 (table)
240 </section>
241 }
242 .boxed()
243}
244
245struct Drawn {
248 label: String,
249 values: Vec<Option<f64>>,
250 color: Color,
251}
252
253impl Drawn {
254 fn new(cx: &Cx, series: Series, index: usize, labels: usize) -> Self {
255 let mut values: Vec<Option<f64>> = series
256 .values
257 .into_iter()
258 .take(labels)
259 .map(|value| value.is_finite().then_some(value))
260 .collect();
261 values.resize(labels, None);
262 Self {
263 label: series.label.localize(cx),
264 values,
265 color: series.color.unwrap_or(PALETTE[index % PALETTE.len()]),
266 }
267 }
268}
269
270fn plot<'a>(
273 cx: &'a Cx,
274 kind: ChartKind,
275 axis: &Axis,
276 labels: &[String],
277 series: &[Drawn],
278) -> BoxView<'a> {
279 let numbers = NumberFormat::of(cx);
280 let ticks: Vec<(String, String)> = axis
281 .ticks()
282 .map(|tick| {
283 (
284 axis.format(tick, &numbers),
285 coordinate(PLOT * axis.share(tick)),
286 )
287 })
288 .collect();
289 let width = PLOT / labels.len() as f64;
290 let marks: Vec<BoxView<'a>> = series
291 .iter()
292 .enumerate()
293 .map(|(index, drawn)| match kind {
294 ChartKind::Line => line(cx, axis, width, drawn),
295 ChartKind::Bar => bars(cx, axis, width, index, series.len(), drawn),
296 })
297 .collect();
298 let columns: Vec<(String, String)> = labels
300 .iter()
301 .enumerate()
302 .map(|(index, label)| {
303 let values: Vec<String> = series
304 .iter()
305 .map(|drawn| {
306 let value = drawn.values[index]
307 .map_or_else(|| "–".to_string(), |value| format_value(value, &numbers));
308 format!("{}: {value}", drawn.label)
309 })
310 .collect();
311 (
312 coordinate(index as f64 * width),
313 format!("{label} — {}", values.join(", ")),
314 )
315 })
316 .collect();
317 let step = labels.len().div_ceil(MAX_AXIS_LABELS);
318 let bottom: Vec<String> = labels
319 .iter()
320 .enumerate()
321 .map(|(index, label)| {
322 if index % step == 0 {
323 label.clone()
324 } else {
325 String::new()
326 }
327 })
328 .collect();
329 let bottom_columns = format!(
330 "grid-template-columns: repeat({}, minmax(0, 1fr))",
331 labels.len()
332 );
333 let column_width = coordinate(width);
334 let plot = PLOT.to_string();
335 let view_box = format!("0 0 {PLOT} {PLOT}");
336 view! {
337 <div
338 class="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-2"
339 aria-hidden="true"
340 >
341 <div
342 class="flex h-48 flex-col justify-between text-xs text-muted-foreground tabular-nums"
343 >
344 for (tick, _) in ticks.iter().rev() {
345 <div class="flex h-0 items-center justify-end">(tick.clone())</div>
346 }
347 </div>
348 <svg
349 class="h-48 w-full overflow-visible"
350 viewBox=(view_box)
351 preserveAspectRatio="none"
352 >
353 <g class="text-border">
354 for (_, y) in ticks.iter() {
355 <line
356 x1="0"
357 x2=(plot.clone())
358 y1=(y.clone())
359 y2=(y.clone())
360 stroke="currentColor"
361 vector-effect="non-scaling-stroke"
362 />
363 }
364 </g>
365 for mark in marks {
366 (mark)
367 }
368 for (x, title) in columns {
369 <rect
370 x=(x)
371 y="0"
372 width=(column_width.clone())
373 height=(plot.clone())
374 fill="transparent"
375 >
376 <title>(title)</title>
377 </rect>
378 }
379 </svg>
380 <div></div>
381 <div class="grid text-xs text-muted-foreground" style=(bottom_columns)>
382 for label in bottom {
383 <span class="truncate text-center">(label)</span>
384 }
385 </div>
386 </div>
387 }
388 .boxed()
389}
390
391fn line<'a>(cx: &'a Cx, axis: &Axis, width: f64, drawn: &Drawn) -> BoxView<'a> {
394 let runs = runs(&drawn.values, |index, value| {
395 format!(
396 "{},{}",
397 coordinate((index as f64 + 0.5) * width),
398 coordinate(PLOT * axis.share(value))
399 )
400 });
401 let class = drawn.color.text_class();
402 view! {
403 <g class=(class)>
404 for points in runs {
405 <polyline
406 points=(points)
407 fill="none"
408 stroke="currentColor"
409 stroke-width="2"
410 stroke-linejoin="round"
411 stroke-linecap="round"
412 vector-effect="non-scaling-stroke"
413 />
414 }
415 </g>
416 }
417 .boxed()
418}
419
420fn runs(values: &[Option<f64>], point: impl Fn(usize, f64) -> String) -> Vec<String> {
422 let mut runs: Vec<Vec<String>> = vec![Vec::new()];
423 for (index, value) in values.iter().enumerate() {
424 match value {
425 Some(value) => runs
426 .last_mut()
427 .expect("one run at least")
428 .push(point(index, *value)),
429 None => runs.push(Vec::new()),
430 }
431 }
432 runs.into_iter()
433 .filter_map(|run| match run.as_slice() {
434 [] => None,
435 [point] => Some(format!("{point} {point}")),
436 _ => Some(run.join(" ")),
437 })
438 .collect()
439}
440
441fn bars<'a>(
444 cx: &'a Cx,
445 axis: &Axis,
446 width: f64,
447 index: usize,
448 count: usize,
449 drawn: &Drawn,
450) -> BoxView<'a> {
451 let bar = width * BAR_GROUP / count as f64;
452 let zero = PLOT * axis.share(0.0);
453 let rects: Vec<[String; 4]> = drawn
454 .values
455 .iter()
456 .enumerate()
457 .filter_map(|(label, value)| {
458 let y = PLOT * axis.share((*value)?);
459 let x = label as f64 * width + width * (1.0 - BAR_GROUP) / 2.0 + index as f64 * bar;
460 Some([
462 coordinate(x + bar * 0.05),
463 coordinate(y.min(zero)),
464 coordinate(bar * 0.9),
465 coordinate((y - zero).abs()),
466 ])
467 })
468 .collect();
469 let class = drawn.color.text_class();
470 view! {
471 <g class=(class)>
472 for [x, y, w, h] in rects {
473 <rect x=(x) y=(y) width=(w) height=(h) fill="currentColor" />
474 }
475 </g>
476 }
477 .boxed()
478}
479
480fn data_table<'a>(
482 cx: &'a Cx,
483 heading: Option<String>,
484 labels: &[String],
485 series: &[Drawn],
486) -> BoxView<'a> {
487 let numbers = NumberFormat::of(cx);
488 let labels = labels.to_vec();
489 let rows: Vec<(String, Vec<String>)> = series
490 .iter()
491 .map(|drawn| {
492 let values = drawn
493 .values
494 .iter()
495 .map(|value| {
496 value
497 .map(|value| format_value(value, &numbers))
498 .unwrap_or_default()
499 })
500 .collect();
501 (drawn.label.clone(), values)
502 })
503 .collect();
504 view! {
505 <table class="sr-only" data-chart-data="">
506 if let Some(heading) = heading {
507 <caption>(heading)</caption>
508 }
509 <thead>
510 <tr>
511 <td></td>
512 for label in labels {
513 <th scope="col">(label)</th>
514 }
515 </tr>
516 </thead>
517 <tbody>
518 for (label, values) in rows {
519 <tr>
520 <th scope="row">(label)</th>
521 for value in values {
522 <td>(value)</td>
523 }
524 </tr>
525 }
526 </tbody>
527 </table>
528 }
529 .boxed()
530}
531
532fn coordinate(value: f64) -> String {
534 format!("{value:.3}")
535}
536
537fn format_value(value: f64, numbers: &NumberFormat) -> String {
540 if value.fract() == 0.0 && value.abs() < 1e38 {
542 #[allow(clippy::cast_possible_truncation)]
543 numbers.spell(Number::Int(value as i128), 0)
544 } else {
545 numbers.spell(Number::Float(value), 2)
546 }
547}
548
549#[cfg(test)]
550mod tests;