ailloli_ui_widgets/controls/
charts.rs

1//! Non-interactive bar, line, and radial-gauge data visualizations.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use ailloli_ui_core::event::Event;
5use ailloli_ui_core::geometry::{Constraints, Rect, Size};
6use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
7use ailloli_ui_core::{
8    auto_x_range, auto_y_range, ChartRange, ChartSeries, Color, FontId, LineCap, LineJoin, Point,
9    StrokeStyle, TextStyle, Theme,
10};
11use ailloli_ui_runtime::component::{Binding, IntoView, View, Widget};
12use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
13use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
14use ailloli_ui_runtime::scene::PaintCtx;
15use ailloli_ui_runtime::{
16    DrawBorder, DrawCmd, DrawPolyline, DrawRRect, DrawRect, DrawRingProgress, DrawText,
17};
18use ailloli_ui_text::{TextLayoutParams, WrapMode};
19
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21/// Built-in chart canvas and stroke sizes.
22///
23/// # Examples
24///
25/// ```
26/// use ailloli_ui_widgets::controls::ChartSize;
27/// let sizes = [ChartSize::Compact, ChartSize::Default, ChartSize::Large];
28/// assert_eq!(sizes.len(), 3);
29/// assert_eq!(ChartSize::default(), ChartSize::Default);
30/// ```
31pub enum ChartSize {
32    /// 180 by 124 logical-pixel canvas.
33    Compact,
34    /// 240 by 164 logical-pixel canvas; the default.
35    #[default]
36    Default,
37    /// 320 by 220 logical-pixel canvas.
38    Large,
39}
40
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
42/// Semantic series color for line charts and radial gauges.
43///
44/// Bar charts instead cycle through all six colors in [`ChartStyle::colors`].
45///
46/// # Examples
47///
48/// ```
49/// use ailloli_ui_widgets::controls::ChartTone;
50/// let tones = [
51///     ChartTone::Accent,
52///     ChartTone::Success,
53///     ChartTone::Warning,
54///     ChartTone::Danger,
55///     ChartTone::Info,
56///     ChartTone::Neutral,
57/// ];
58/// assert_eq!(tones.len(), 6);
59/// assert_eq!(ChartTone::default(), ChartTone::Accent);
60/// ```
61pub enum ChartTone {
62    /// Accent-brand color; the default.
63    #[default]
64    Accent,
65    /// Successful-state color.
66    Success,
67    /// Warning-state color.
68    Warning,
69    /// Destructive or error color.
70    Danger,
71    /// Informational color.
72    Info,
73    /// Muted neutral color.
74    Neutral,
75}
76
77#[derive(Clone, Debug, PartialEq)]
78/// Resolved chart colors, typography, and logical-pixel geometry.
79///
80/// Custom geometry is not validated. Padding larger than the canvas collapses
81/// the content area to zero; non-finite values can propagate to draw commands.
82///
83/// # Examples
84///
85/// ```
86/// use ailloli_ui_core::Theme;
87/// use ailloli_ui_widgets::controls::{ChartSize, ChartStyle};
88/// let style = ChartStyle::from_theme(Theme::dark(), ChartSize::Compact);
89/// assert_eq!((style.width, style.height, style.padding), (180.0, 124.0, 10.0));
90/// assert_eq!(style.colors.len(), 6);
91/// ```
92pub struct ChartStyle {
93    /// Rounded outer canvas fill.
94    pub background: Color,
95    /// Plot area and radial-gauge track fill.
96    pub plot_background: Color,
97    /// Horizontal grid-line color.
98    pub grid: Color,
99    /// Left and bottom axis color.
100    pub axis: Color,
101    /// Outer canvas border.
102    pub border: Border,
103    /// Title and gauge percentage typography.
104    pub text: TextStyle,
105    /// Empty-state, x-label, and gauge-label typography.
106    pub muted_text: TextStyle,
107    /// Accent, success, info, warning, danger, and neutral colors in that order.
108    pub colors: [Color; 6],
109    /// Intrinsic canvas width in logical pixels.
110    pub width: f32,
111    /// Intrinsic canvas height in logical pixels.
112    pub height: f32,
113    /// Inner inset on every side in logical pixels.
114    pub padding: f32,
115    /// Outer canvas corner radius in logical pixels.
116    pub radius: f32,
117    /// Horizontal space reserved within each bar group in logical pixels.
118    pub bar_gap: f32,
119    /// Line-chart stroke width in logical pixels.
120    pub line_thickness: f32,
121    /// Line-chart point diameter in logical pixels.
122    pub point_size: f32,
123    /// Preferred radial-gauge ring thickness in logical pixels.
124    pub gauge_thickness: f32,
125}
126
127impl Default for ChartStyle {
128    fn default() -> Self {
129        Self::from_theme(Theme::default(), ChartSize::Default)
130    }
131}
132
133impl ChartStyle {
134    /// Resolves all chart styling from a theme and built-in size.
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// use ailloli_ui_core::Theme;
140    /// use ailloli_ui_widgets::controls::{ChartSize, ChartStyle};
141    /// let style = ChartStyle::from_theme(Theme::default(), ChartSize::Large);
142    /// assert_eq!((style.width, style.height), (320.0, 220.0));
143    /// assert_eq!((style.line_thickness, style.point_size), (3.0, 6.0));
144    /// ```
145    pub fn from_theme(theme: Theme, size: ChartSize) -> Self {
146        let palette = theme.palette();
147        let (width, height, text_px, padding, line_thickness, point_size, gauge_thickness) =
148            match size {
149                ChartSize::Compact => (180.0, 124.0, 10, 10.0, 2.0, 4.0, 6.0),
150                ChartSize::Default => (240.0, 164.0, 11, 12.0, 2.5, 5.0, 8.0),
151                ChartSize::Large => (320.0, 220.0, 13, 16.0, 3.0, 6.0, 10.0),
152            };
153        Self {
154            background: palette.surface,
155            plot_background: palette.surface_elevated.with_alpha(0.42),
156            grid: palette.border.with_alpha(0.40),
157            axis: palette.border.with_alpha(0.72),
158            border: Border::new(1.0, palette.border.with_alpha(0.72)),
159            text: TextStyle::new(FontId::Ui, text_px, palette.text),
160            muted_text: TextStyle::new(FontId::Ui, text_px, palette.text_muted),
161            colors: [
162                palette.accent,
163                palette.success,
164                palette.info,
165                palette.warning,
166                palette.danger,
167                palette.text_muted,
168            ],
169            width,
170            height,
171            padding,
172            radius: theme.radius().md,
173            bar_gap: 4.0,
174            line_thickness,
175            point_size,
176            gauge_thickness,
177        }
178    }
179
180    /// Returns the configured intrinsic canvas size.
181    fn intrinsic_size(&self) -> Size {
182        Size::new(self.width, self.height)
183    }
184
185    /// Resolves a semantic tone through the fixed six-color palette.
186    fn tone_color(&self, tone: ChartTone) -> Color {
187        match tone {
188            ChartTone::Accent => self.colors[0],
189            ChartTone::Success => self.colors[1],
190            ChartTone::Info => self.colors[2],
191            ChartTone::Warning => self.colors[3],
192            ChartTone::Danger => self.colors[4],
193            ChartTone::Neutral => self.colors[5],
194        }
195    }
196}
197
198/// A grouped vertical bar chart with optional x-axis labels.
199///
200/// Each added series forms one bar per point index. Point `x` coordinates are
201/// ignored; non-finite `y` values are skipped. The longest series determines
202/// group count, and labels are independently distributed across the plot, so a
203/// mismatched label count does not automatically align with groups. The first
204/// series name is used as the title; no legend is drawn.
205///
206/// # Examples
207///
208/// ```
209/// use ailloli_ui_widgets::controls::BarChart;
210/// let chart = BarChart::new()
211///     .series("Requests", [12.0, 18.0, 9.0])
212///     .labels(["Mon", "Tue", "Wed"]);
213/// let _ = chart;
214/// ```
215pub struct BarChart {
216    /// Layout configuration applied to the intrinsic canvas.
217    pub(crate) layout: LayoutStyle,
218    /// Flex behavior used by the parent layout.
219    pub(crate) flex_item: FlexItemStyle,
220    /// Series in insertion/color-cycle order.
221    series: Vec<ChartSeries>,
222    /// Independently spaced x-axis labels.
223    labels: Vec<String>,
224    /// Optional explicit sanitized y-domain.
225    y_range: Option<ChartRange>,
226    /// Resolved paint and geometry.
227    style: ChartStyle,
228    /// Empty-state text.
229    empty_text: String,
230}
231
232/// A multi-series polyline chart using one semantic color.
233///
234/// All series share the selected tone; the first series name is the title and
235/// no legend is drawn. Empty series display the empty text. A non-empty series
236/// containing only non-finite coordinates is not considered empty, but yields
237/// no valid polyline. When points are enabled, callers should provide finite
238/// coordinates because point markers are emitted without an additional filter.
239///
240/// # Examples
241///
242/// ```
243/// use ailloli_ui_widgets::controls::{ChartTone, LineChart};
244/// let chart = LineChart::new()
245///     .series("Latency", [(0.0, 12.0), (1.0, 8.0)])
246///     .show_points(true)
247///     .tone(ChartTone::Info);
248/// let _ = chart;
249/// ```
250pub struct LineChart {
251    /// Layout configuration applied to the intrinsic canvas.
252    pub(crate) layout: LayoutStyle,
253    /// Flex behavior used by the parent layout.
254    pub(crate) flex_item: FlexItemStyle,
255    /// Series in insertion order.
256    series: Vec<ChartSeries>,
257    /// Optional explicit sanitized x-domain.
258    x_range: Option<ChartRange>,
259    /// Optional explicit sanitized y-domain.
260    y_range: Option<ChartRange>,
261    /// Whether to paint a circular marker for every source point.
262    show_points: bool,
263    /// Resolved paint and geometry.
264    style: ChartStyle,
265    /// Shared semantic series color.
266    tone: ChartTone,
267    /// Empty-state text.
268    empty_text: String,
269}
270
271/// A radial normalized value indicator with optional percentage and label.
272///
273/// Values are mapped through [`ChartRange`], clamped to `0.0..=1.0`, and
274/// non-finite values map to zero. The optional percentage is rounded to a whole
275/// number. The default range is `0.0..=1.0`, value is zero, and text is hidden.
276///
277/// # Examples
278///
279/// ```
280/// use ailloli_ui_widgets::controls::RadialGauge;
281/// let gauge = RadialGauge::new()
282///     .value(75.0)
283///     .range(0.0, 100.0)
284///     .show_value(true)
285///     .label("Complete");
286/// let _ = gauge;
287/// ```
288pub struct RadialGauge {
289    /// Layout configuration applied to the intrinsic canvas.
290    pub(crate) layout: LayoutStyle,
291    /// Flex behavior used by the parent layout.
292    pub(crate) flex_item: FlexItemStyle,
293    /// Live data value in the range's caller-defined unit.
294    value: Binding<f32>,
295    /// Sanitized inclusive data domain.
296    range: ChartRange,
297    /// Optional live label below the ring.
298    label: Option<Binding<String>>,
299    /// Whether to paint the rounded percentage inside the ring.
300    show_value: bool,
301    /// Resolved paint and geometry.
302    style: ChartStyle,
303    /// Semantic ring fill color.
304    tone: ChartTone,
305}
306
307crate::impl_layout_builders_unit!(BarChart);
308crate::impl_layout_builders_unit!(LineChart);
309crate::impl_layout_builders_unit!(RadialGauge);
310
311impl Default for BarChart {
312    fn default() -> Self {
313        Self::new()
314    }
315}
316
317impl BarChart {
318    /// Creates an empty chart with automatic y-range and `"No data"` text.
319    ///
320    /// # Examples
321    ///
322    /// ```
323    /// use ailloli_ui_widgets::controls::BarChart;
324    /// let chart = BarChart::new();
325    /// let _ = chart;
326    /// ```
327    pub fn new() -> Self {
328        Self {
329            layout: LayoutStyle::default(),
330            flex_item: FlexItemStyle::default(),
331            series: Vec::new(),
332            labels: Vec::new(),
333            y_range: None,
334            style: ChartStyle::default(),
335            empty_text: "No data".to_string(),
336        }
337    }
338
339    /// Appends a named series whose x coordinates are zero-based indices.
340    ///
341    /// Values, including non-finite values, are retained; the painter skips
342    /// non-finite y values. Empty series are allowed.
343    ///
344    /// # Examples
345    ///
346    /// ```
347    /// use ailloli_ui_widgets::controls::BarChart;
348    /// let chart = BarChart::new().series("CPU", [20.0, 35.0]);
349    /// let _ = chart;
350    /// ```
351    pub fn series(
352        mut self,
353        name: impl Into<String>,
354        values: impl IntoIterator<Item = f32>,
355    ) -> Self {
356        self.series.push(ChartSeries::from_values(name, values));
357        self
358    }
359
360    /// Appends an existing series without normalization.
361    ///
362    /// Its x coordinates are ignored by bar placement.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use ailloli_ui_core::ChartSeries;
368    /// use ailloli_ui_widgets::controls::BarChart;
369    /// let chart = BarChart::new().chart_series(ChartSeries::from_values("CPU", [1.0, 2.0]));
370    /// let _ = chart;
371    /// ```
372    pub fn chart_series(mut self, series: ChartSeries) -> Self {
373        self.series.push(series);
374        self
375    }
376
377    /// Replaces all x-axis labels with values collected in iterator order.
378    ///
379    /// Labels are spread according to their own count, independently of bar
380    /// groups. Empty text remains a label; an empty iterator hides the label row.
381    ///
382    /// # Examples
383    ///
384    /// ```
385    /// use ailloli_ui_widgets::controls::BarChart;
386    /// let chart = BarChart::new().labels(["Q1", "Q2"]);
387    /// let _ = chart;
388    /// ```
389    pub fn labels<I, S>(mut self, labels: I) -> Self
390    where
391        I: IntoIterator<Item = S>,
392        S: Into<String>,
393    {
394        self.labels = labels.into_iter().map(Into::into).collect();
395        self
396    }
397
398    /// Sets an explicit y-domain after finite/order/degeneracy sanitization.
399    ///
400    /// Reversed bounds are swapped, non-finite bounds fall back to `0`/`1`, and
401    /// nearly equal bounds are widened when representable. Values outside the
402    /// domain are clamped to the plot edges.
403    ///
404    /// # Examples
405    ///
406    /// ```
407    /// use ailloli_ui_widgets::controls::BarChart;
408    /// let chart = BarChart::new().range(-100.0, 100.0);
409    /// let _ = chart;
410    /// ```
411    pub fn range(mut self, min: f32, max: f32) -> Self {
412        self.y_range = Some(ChartRange::new(min, max));
413        self
414    }
415
416    /// Replaces complete chart style and intrinsic geometry.
417    ///
418    /// # Examples
419    ///
420    /// ```
421    /// use ailloli_ui_widgets::controls::{BarChart, ChartStyle};
422    /// let chart = BarChart::new().chart_style(ChartStyle::default());
423    /// let _ = chart;
424    /// ```
425    pub fn chart_style(mut self, style: ChartStyle) -> Self {
426        self.style = style;
427        self
428    }
429
430    /// Replaces style with a default-theme built-in size.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use ailloli_ui_widgets::controls::{BarChart, ChartSize};
436    /// let chart = BarChart::new().chart_size(ChartSize::Large);
437    /// let _ = chart;
438    /// ```
439    pub fn chart_size(mut self, size: ChartSize) -> Self {
440        self.style = ChartStyle::from_theme(Theme::default(), size);
441        self
442    }
443
444    /// Replaces text painted when there are no points or no plot area.
445    ///
446    /// Empty text is valid and paints no glyphs.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// use ailloli_ui_widgets::controls::BarChart;
452    /// let chart = BarChart::new().empty_text("Awaiting samples");
453    /// let _ = chart;
454    /// ```
455    pub fn empty_text(mut self, text: impl Into<String>) -> Self {
456        self.empty_text = text.into();
457        self
458    }
459}
460
461impl Default for LineChart {
462    fn default() -> Self {
463        Self::new()
464    }
465}
466
467impl LineChart {
468    /// Creates an empty accent chart with automatic axes and hidden points.
469    ///
470    /// # Examples
471    ///
472    /// ```
473    /// use ailloli_ui_widgets::controls::LineChart;
474    /// let chart = LineChart::new();
475    /// let _ = chart;
476    /// ```
477    pub fn new() -> Self {
478        Self {
479            layout: LayoutStyle::default(),
480            flex_item: FlexItemStyle::default(),
481            series: Vec::new(),
482            x_range: None,
483            y_range: None,
484            show_points: false,
485            style: ChartStyle::default(),
486            tone: ChartTone::Accent,
487            empty_text: "No data".to_string(),
488        }
489    }
490
491    /// Appends a named series of `(x, y)` points without normalization.
492    ///
493    /// # Examples
494    ///
495    /// ```
496    /// use ailloli_ui_widgets::controls::LineChart;
497    /// let chart = LineChart::new().series("CPU", [(10.0, 0.4), (20.0, 0.8)]);
498    /// let _ = chart;
499    /// ```
500    pub fn series(
501        mut self,
502        name: impl Into<String>,
503        points: impl IntoIterator<Item = (f32, f32)>,
504    ) -> Self {
505        self.series.push(ChartSeries::from_xy(name, points));
506        self
507    }
508
509    /// Appends an existing series without normalization.
510    ///
511    /// # Examples
512    ///
513    /// ```
514    /// use ailloli_ui_core::ChartSeries;
515    /// use ailloli_ui_widgets::controls::LineChart;
516    /// let chart = LineChart::new().chart_series(ChartSeries::from_xy("CPU", [(0.0, 1.0)]));
517    /// let _ = chart;
518    /// ```
519    pub fn chart_series(mut self, series: ChartSeries) -> Self {
520        self.series.push(series);
521        self
522    }
523
524    /// Sets an explicit sanitized y-domain.
525    ///
526    /// Reversed bounds are swapped, non-finite bounds fall back to `0`/`1`, and
527    /// values outside the result are clamped to the plot edges.
528    ///
529    /// # Examples
530    ///
531    /// ```
532    /// use ailloli_ui_widgets::controls::LineChart;
533    /// let chart = LineChart::new().range(0.0, 100.0);
534    /// let _ = chart;
535    /// ```
536    pub fn range(mut self, min: f32, max: f32) -> Self {
537        self.y_range = Some(ChartRange::new(min, max));
538        self
539    }
540
541    /// Sets an explicit sanitized x-domain.
542    ///
543    /// # Examples
544    ///
545    /// ```
546    /// use ailloli_ui_widgets::controls::LineChart;
547    /// let chart = LineChart::new().x_range(1_000.0, 2_000.0);
548    /// let _ = chart;
549    /// ```
550    pub fn x_range(mut self, min: f32, max: f32) -> Self {
551        self.x_range = Some(ChartRange::new(min, max));
552        self
553    }
554
555    /// Shows or hides a marker for every source point.
556    ///
557    /// The default is `false`. Point markers do not filter non-finite source
558    /// coordinates, so finite coordinates are required when enabled.
559    ///
560    /// # Examples
561    ///
562    /// ```
563    /// use ailloli_ui_widgets::controls::LineChart;
564    /// let chart = LineChart::new().show_points(true);
565    /// let _ = chart;
566    /// ```
567    pub fn show_points(mut self, show: bool) -> Self {
568        self.show_points = show;
569        self
570    }
571
572    /// Sets the single semantic color shared by all series.
573    ///
574    /// # Examples
575    ///
576    /// ```
577    /// use ailloli_ui_widgets::controls::{ChartTone, LineChart};
578    /// let chart = LineChart::new().tone(ChartTone::Success);
579    /// let _ = chart;
580    /// ```
581    pub fn tone(mut self, tone: ChartTone) -> Self {
582        self.tone = tone;
583        self
584    }
585
586    /// Replaces complete chart style and intrinsic geometry.
587    ///
588    /// # Examples
589    ///
590    /// ```
591    /// use ailloli_ui_widgets::controls::{ChartStyle, LineChart};
592    /// let chart = LineChart::new().chart_style(ChartStyle::default());
593    /// let _ = chart;
594    /// ```
595    pub fn chart_style(mut self, style: ChartStyle) -> Self {
596        self.style = style;
597        self
598    }
599
600    /// Replaces style with a default-theme built-in size.
601    ///
602    /// # Examples
603    ///
604    /// ```
605    /// use ailloli_ui_widgets::controls::{ChartSize, LineChart};
606    /// let chart = LineChart::new().chart_size(ChartSize::Compact);
607    /// let _ = chart;
608    /// ```
609    pub fn chart_size(mut self, size: ChartSize) -> Self {
610        self.style = ChartStyle::from_theme(Theme::default(), size);
611        self
612    }
613
614    /// Replaces text painted only when every series has no points.
615    ///
616    /// # Examples
617    ///
618    /// ```
619    /// use ailloli_ui_widgets::controls::LineChart;
620    /// let chart = LineChart::new().empty_text("No samples");
621    /// let _ = chart;
622    /// ```
623    pub fn empty_text(mut self, text: impl Into<String>) -> Self {
624        self.empty_text = text.into();
625        self
626    }
627}
628
629impl Default for RadialGauge {
630    fn default() -> Self {
631        Self::new()
632    }
633}
634
635impl RadialGauge {
636    /// Creates a zero-valued accent gauge over `0.0..=1.0` with no text.
637    ///
638    /// # Examples
639    ///
640    /// ```
641    /// use ailloli_ui_widgets::controls::RadialGauge;
642    /// let gauge = RadialGauge::new();
643    /// let _ = gauge;
644    /// ```
645    pub fn new() -> Self {
646        Self {
647            layout: LayoutStyle::default(),
648            flex_item: FlexItemStyle::default(),
649            value: Binding::Static(0.0),
650            range: ChartRange::default(),
651            label: None,
652            show_value: false,
653            style: ChartStyle::default(),
654            tone: ChartTone::Accent,
655        }
656    }
657
658    /// Sets the static or reactive data value.
659    ///
660    /// Painting maps it through the configured range, clamps out-of-range
661    /// values, and treats NaN or infinity as the range minimum.
662    ///
663    /// # Examples
664    ///
665    /// ```
666    /// use ailloli_ui_widgets::controls::RadialGauge;
667    /// let gauge = RadialGauge::new().value(0.75);
668    /// let _ = gauge;
669    /// ```
670    pub fn value(mut self, value: impl Into<Binding<f32>>) -> Self {
671        self.value = value.into();
672        self
673    }
674
675    /// Sets the inclusive sanitized data domain.
676    ///
677    /// Reversed bounds are swapped and non-finite bounds become `0`/`1`.
678    ///
679    /// # Examples
680    ///
681    /// ```
682    /// use ailloli_ui_widgets::controls::RadialGauge;
683    /// let gauge = RadialGauge::new().range(0.0, 100.0).value(25.0);
684    /// let _ = gauge;
685    /// ```
686    pub fn range(mut self, min: f32, max: f32) -> Self {
687        self.range = ChartRange::new(min, max);
688        self
689    }
690
691    /// Sets static or reactive text painted below the ring.
692    ///
693    /// Empty text remains present but paints no glyphs.
694    ///
695    /// # Examples
696    ///
697    /// ```
698    /// use ailloli_ui_widgets::controls::RadialGauge;
699    /// let gauge = RadialGauge::new().label("Storage");
700    /// let _ = gauge;
701    /// ```
702    pub fn label(mut self, label: impl Into<Binding<String>>) -> Self {
703        self.label = Some(label.into());
704        self
705    }
706
707    /// Shows or hides a whole-number percentage inside the ring.
708    ///
709    /// The default is `false`.
710    ///
711    /// # Examples
712    ///
713    /// ```
714    /// use ailloli_ui_widgets::controls::RadialGauge;
715    /// let gauge = RadialGauge::new().show_value(true);
716    /// let _ = gauge;
717    /// ```
718    pub fn show_value(mut self, show: bool) -> Self {
719        self.show_value = show;
720        self
721    }
722
723    /// Sets the semantic ring fill color.
724    ///
725    /// # Examples
726    ///
727    /// ```
728    /// use ailloli_ui_widgets::controls::{ChartTone, RadialGauge};
729    /// let gauge = RadialGauge::new().tone(ChartTone::Warning);
730    /// let _ = gauge;
731    /// ```
732    pub fn tone(mut self, tone: ChartTone) -> Self {
733        self.tone = tone;
734        self
735    }
736
737    /// Replaces complete gauge style and intrinsic geometry.
738    ///
739    /// # Examples
740    ///
741    /// ```
742    /// use ailloli_ui_widgets::controls::{ChartStyle, RadialGauge};
743    /// let gauge = RadialGauge::new().chart_style(ChartStyle::default());
744    /// let _ = gauge;
745    /// ```
746    pub fn chart_style(mut self, style: ChartStyle) -> Self {
747        self.style = style;
748        self
749    }
750
751    /// Replaces style with a default-theme built-in size.
752    ///
753    /// # Examples
754    ///
755    /// ```
756    /// use ailloli_ui_widgets::controls::{ChartSize, RadialGauge};
757    /// let gauge = RadialGauge::new().chart_size(ChartSize::Large);
758    /// let _ = gauge;
759    /// ```
760    pub fn chart_size(mut self, size: ChartSize) -> Self {
761        self.style = ChartStyle::from_theme(Theme::default(), size);
762        self
763    }
764}
765
766/// Retained leaf widget that paints grouped bar series.
767struct BarChartWidget {
768    /// Outer logical sizing policy.
769    layout: LayoutStyle,
770    /// Ordered bar series; each series is aligned with `labels` by index.
771    series: Vec<ChartSeries>,
772    /// Ordered category labels along the horizontal axis.
773    labels: Vec<String>,
774    /// Optional explicit vertical domain; otherwise finite data determines it.
775    y_range: Option<ChartRange>,
776    /// Shared colors and logical-pixel chart geometry.
777    style: ChartStyle,
778    /// Message painted when no finite samples are available.
779    empty_text: String,
780}
781
782/// Retained leaf widget that paints one-color polyline series.
783struct LineChartWidget {
784    /// Outer logical sizing policy.
785    layout: LayoutStyle,
786    /// Ordered polyline series.
787    series: Vec<ChartSeries>,
788    /// Optional explicit horizontal domain.
789    x_range: Option<ChartRange>,
790    /// Optional explicit vertical domain.
791    y_range: Option<ChartRange>,
792    /// Whether finite samples receive point markers.
793    show_points: bool,
794    /// Shared colors and logical-pixel chart geometry.
795    style: ChartStyle,
796    /// Semantic palette tone applied to fallback series colors.
797    tone: ChartTone,
798    /// Message painted when no finite samples are available.
799    empty_text: String,
800}
801
802/// Retained leaf widget that reads and paints a reactive gauge value/label.
803struct RadialGaugeWidget {
804    /// Outer logical sizing policy.
805    layout: LayoutStyle,
806    /// Reactive gauge value; non-finite values use the range minimum.
807    value: Binding<f32>,
808    /// Inclusive value domain mapped onto the arc sweep.
809    range: ChartRange,
810    /// Optional reactive center label.
811    label: Option<Binding<String>>,
812    /// Whether a formatted numeric value is painted below the label.
813    show_value: bool,
814    /// Shared colors and logical-pixel gauge geometry.
815    style: ChartStyle,
816    /// Semantic palette tone used for the filled arc.
817    tone: ChartTone,
818}
819
820impl<A: 'static> Widget<A> for BarChartWidget {
821    fn debug_name(&self) -> &'static str {
822        "BarChart"
823    }
824
825    fn layout(
826        &self,
827        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
828        _ctx: &mut LayoutCtx<'_>,
829        _children: &mut [LayoutChild],
830        constraints: Constraints,
831    ) -> LayoutResult {
832        chart_layout_result(self.style.intrinsic_size(), self.layout, constraints)
833    }
834
835    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
836        paint_bar_chart(
837            ctx,
838            bounds,
839            &self.series,
840            &self.labels,
841            self.y_range,
842            &self.style,
843            &self.empty_text,
844        );
845    }
846
847    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
848    }
849
850    fn focus_policy(&self) -> FocusPolicy {
851        FocusPolicy::NotFocusable
852    }
853}
854
855impl<A: 'static> Widget<A> for LineChartWidget {
856    fn debug_name(&self) -> &'static str {
857        "LineChart"
858    }
859
860    fn layout(
861        &self,
862        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
863        _ctx: &mut LayoutCtx<'_>,
864        _children: &mut [LayoutChild],
865        constraints: Constraints,
866    ) -> LayoutResult {
867        chart_layout_result(self.style.intrinsic_size(), self.layout, constraints)
868    }
869
870    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
871        paint_line_chart(
872            ctx,
873            bounds,
874            &self.series,
875            self.x_range,
876            self.y_range,
877            self.show_points,
878            self.tone,
879            &self.style,
880            &self.empty_text,
881        );
882    }
883
884    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
885    }
886
887    fn focus_policy(&self) -> FocusPolicy {
888        FocusPolicy::NotFocusable
889    }
890}
891
892impl<A: 'static> Widget<A> for RadialGaugeWidget {
893    fn debug_name(&self) -> &'static str {
894        "RadialGauge"
895    }
896
897    fn layout(
898        &self,
899        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
900        _ctx: &mut LayoutCtx<'_>,
901        _children: &mut [LayoutChild],
902        constraints: Constraints,
903    ) -> LayoutResult {
904        chart_layout_result(self.style.intrinsic_size(), self.layout, constraints)
905    }
906
907    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
908        paint_radial_gauge(
909            ctx,
910            bounds,
911            self.range.fraction_for_value(self.value.read()),
912            self.label.as_ref(),
913            self.show_value,
914            self.tone,
915            &self.style,
916        );
917    }
918
919    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
920    }
921
922    fn focus_policy(&self) -> FocusPolicy {
923        FocusPolicy::NotFocusable
924    }
925}
926
927impl<A: 'static> IntoView<A> for BarChart {
928    fn into_view(self) -> View<A> {
929        finish_view_sized(
930            View::leaf(BarChartWidget {
931                layout: self.layout,
932                series: self.series,
933                labels: self.labels,
934                y_range: self.y_range,
935                style: self.style,
936                empty_text: self.empty_text,
937            }),
938            self.flex_item,
939            LayoutSizeHint::from_layout(self.layout),
940        )
941    }
942}
943
944impl<A: 'static> IntoView<A> for LineChart {
945    fn into_view(self) -> View<A> {
946        finish_view_sized(
947            View::leaf(LineChartWidget {
948                layout: self.layout,
949                series: self.series,
950                x_range: self.x_range,
951                y_range: self.y_range,
952                show_points: self.show_points,
953                style: self.style,
954                tone: self.tone,
955                empty_text: self.empty_text,
956            }),
957            self.flex_item,
958            LayoutSizeHint::from_layout(self.layout),
959        )
960    }
961}
962
963impl<A: 'static> IntoView<A> for RadialGauge {
964    fn into_view(self) -> View<A> {
965        finish_view_sized(
966            View::leaf(RadialGaugeWidget {
967                layout: self.layout,
968                value: self.value,
969                range: self.range,
970                label: self.label,
971                show_value: self.show_value,
972                style: self.style,
973                tone: self.tone,
974            }),
975            self.flex_item,
976            LayoutSizeHint::from_layout(self.layout),
977        )
978    }
979}
980
981/// Builds childless layout from intrinsic style size and layout overrides.
982fn chart_layout_result(
983    intrinsic: Size,
984    layout: LayoutStyle,
985    constraints: Constraints,
986) -> LayoutResult {
987    let size = apply_layout_size(intrinsic, layout, constraints);
988    let rect = Rect::new(0.0, 0.0, size.w, size.h);
989    LayoutResult {
990        size,
991        children: Vec::new(),
992        paint_bounds: rect,
993        visual_bounds: rect,
994        overlay_hit_bounds: Vec::new(),
995        clip: None,
996        is_window_root_clip: false,
997        artifact: None,
998    }
999}
1000
1001/// Paints the rounded canvas/border and returns its non-negative content inset.
1002fn paint_chart_frame(ctx: &mut PaintCtx<'_>, bounds: Rect, style: &ChartStyle) -> Rect {
1003    if bounds.w <= 0.0 || bounds.h <= 0.0 {
1004        return bounds;
1005    }
1006    ctx.push(DrawCmd::RRect(DrawRRect {
1007        rect: bounds,
1008        radius: style.radius,
1009        color: style.background,
1010    }));
1011    if style.border.is_visible() {
1012        ctx.push(DrawCmd::Border(DrawBorder {
1013            rect: bounds,
1014            radius: Radius::uniform(style.radius),
1015            border: style.border,
1016        }));
1017    }
1018    Rect::new(
1019        bounds.x + style.padding,
1020        bounds.y + style.padding,
1021        (bounds.w - style.padding * 2.0).max(0.0),
1022        (bounds.h - style.padding * 2.0).max(0.0),
1023    )
1024}
1025
1026/// Paints grouped indexed bars, axes, title, labels, or the empty state.
1027fn paint_bar_chart(
1028    ctx: &mut PaintCtx<'_>,
1029    bounds: Rect,
1030    series: &[ChartSeries],
1031    labels: &[String],
1032    y_range: Option<ChartRange>,
1033    style: &ChartStyle,
1034    empty_text: &str,
1035) {
1036    let content = paint_chart_frame(ctx, bounds, style);
1037    let title_h = 16.0;
1038    let label_h = if labels.is_empty() { 4.0 } else { 18.0 };
1039    let plot = Rect::new(
1040        content.x,
1041        content.y + title_h,
1042        content.w,
1043        (content.h - title_h - label_h).max(0.0),
1044    );
1045    paint_chart_title(ctx, content, series.first().map(|s| s.name.as_str()), style);
1046    paint_plot_background(ctx, plot, style);
1047
1048    let max_points = series.iter().map(|s| s.points.len()).max().unwrap_or(0);
1049    if series.is_empty() || max_points == 0 || plot.w <= 0.0 || plot.h <= 0.0 {
1050        paint_centered_text(ctx, plot, empty_text, style.muted_text);
1051        return;
1052    }
1053
1054    let range = y_range.unwrap_or_else(|| auto_y_range(series.iter()));
1055    paint_grid(ctx, plot, style);
1056
1057    let group_w = plot.w / max_points as f32;
1058    let series_count = series.len().max(1);
1059    let bar_w = ((group_w - style.bar_gap) / series_count as f32).max(1.0);
1060    let zero_y = value_y(plot, range, 0.0);
1061    for (series_idx, chart_series) in series.iter().enumerate() {
1062        let color = style.colors[series_idx % style.colors.len()];
1063        for (idx, point) in chart_series.points.iter().enumerate() {
1064            if !point.y.is_finite() {
1065                continue;
1066            }
1067            let x = plot.x + idx as f32 * group_w + style.bar_gap * 0.5 + series_idx as f32 * bar_w;
1068            let y = value_y(plot, range, point.y);
1069            let rect_y = y.min(zero_y);
1070            let h = (zero_y - y).abs().max(1.0);
1071            ctx.push(DrawCmd::RRect(DrawRRect {
1072                rect: Rect::new(x, rect_y, (bar_w - 1.0).max(1.0), h),
1073                radius: 3.0,
1074                color,
1075            }));
1076        }
1077    }
1078    paint_axis(ctx, plot, style);
1079    paint_x_labels(ctx, plot, labels, style);
1080}
1081
1082#[allow(clippy::too_many_arguments)]
1083/// Paints clipped polyline series, optional markers, axes, or the empty state.
1084fn paint_line_chart(
1085    ctx: &mut PaintCtx<'_>,
1086    bounds: Rect,
1087    series: &[ChartSeries],
1088    x_range: Option<ChartRange>,
1089    y_range: Option<ChartRange>,
1090    show_points: bool,
1091    tone: ChartTone,
1092    style: &ChartStyle,
1093    empty_text: &str,
1094) {
1095    let content = paint_chart_frame(ctx, bounds, style);
1096    let title_h = 16.0;
1097    let plot = Rect::new(
1098        content.x,
1099        content.y + title_h,
1100        content.w,
1101        (content.h - title_h - 4.0).max(0.0),
1102    );
1103    paint_chart_title(ctx, content, series.first().map(|s| s.name.as_str()), style);
1104    paint_plot_background(ctx, plot, style);
1105
1106    if series.iter().all(ChartSeries::is_empty) || plot.w <= 0.0 || plot.h <= 0.0 {
1107        paint_centered_text(ctx, plot, empty_text, style.muted_text);
1108        return;
1109    }
1110
1111    let x_range = x_range.unwrap_or_else(|| auto_x_range(series.iter()));
1112    let y_range = y_range.unwrap_or_else(|| auto_y_range(series.iter()));
1113    let color = style.tone_color(tone);
1114    paint_grid(ctx, plot, style);
1115    ctx.with_clip(plot, |ctx| {
1116        for chart_series in series {
1117            let points: Vec<Point> = chart_series
1118                .points
1119                .iter()
1120                .filter_map(|point| {
1121                    let [x, y] = point_to_screen(plot, x_range, y_range, *point);
1122                    if x.is_finite() && y.is_finite() {
1123                        Some(Point::new(x, y))
1124                    } else {
1125                        None
1126                    }
1127                })
1128                .collect();
1129            if points.len() >= 2 {
1130                ctx.push(DrawCmd::Polyline(DrawPolyline {
1131                    points,
1132                    stroke: StrokeStyle {
1133                        color,
1134                        width: style.line_thickness,
1135                        cap: LineCap::Butt,
1136                        join: LineJoin::Bevel,
1137                        miter_limit: 4.0,
1138                    },
1139                }));
1140            }
1141            if show_points {
1142                for point in &chart_series.points {
1143                    let [x, y] = point_to_screen(plot, x_range, y_range, *point);
1144                    let size = style.point_size;
1145                    ctx.push(DrawCmd::RRect(DrawRRect {
1146                        rect: Rect::new(x - size * 0.5, y - size * 0.5, size, size),
1147                        radius: size * 0.5,
1148                        color,
1149                    }));
1150                }
1151            }
1152        }
1153    });
1154    paint_axis(ctx, plot, style);
1155}
1156
1157/// Paints the clamped ring fraction and optional percentage/label text.
1158fn paint_radial_gauge(
1159    ctx: &mut PaintCtx<'_>,
1160    bounds: Rect,
1161    fraction: f32,
1162    label: Option<&Binding<String>>,
1163    show_value: bool,
1164    tone: ChartTone,
1165    style: &ChartStyle,
1166) {
1167    let content = paint_chart_frame(ctx, bounds, style);
1168    let side = content.w.min(content.h - 28.0).max(0.0);
1169    let ring = Rect::new(content.x + (content.w - side) * 0.5, content.y, side, side);
1170    let fill = style.tone_color(tone);
1171    ctx.push(DrawCmd::RingProgress(DrawRingProgress {
1172        rect: ring,
1173        thickness: style.gauge_thickness.min(side * 0.5).max(1.0),
1174        fraction: fraction.clamp(0.0, 1.0),
1175        track_color: style.plot_background,
1176        fill_color: fill,
1177        start_angle: -std::f32::consts::FRAC_PI_2,
1178    }));
1179
1180    if show_value {
1181        let value = format!("{:.0}%", fraction.clamp(0.0, 1.0) * 100.0);
1182        paint_centered_text(ctx, ring, &value, style.text);
1183    }
1184    if let Some(label) = label {
1185        let label_rect = Rect::new(content.x, ring.bottom() + 6.0, content.w, 18.0);
1186        paint_centered_text(ctx, label_rect, &label.read(), style.muted_text);
1187    }
1188}
1189
1190/// Paints the rounded plot fill when both dimensions are positive.
1191fn paint_plot_background(ctx: &mut PaintCtx<'_>, plot: Rect, style: &ChartStyle) {
1192    if plot.w > 0.0 && plot.h > 0.0 {
1193        ctx.push(DrawCmd::RRect(DrawRRect {
1194            rect: plot,
1195            radius: 5.0,
1196            color: style.plot_background,
1197        }));
1198    }
1199}
1200
1201/// Paints a non-empty first-series title in the reserved title row.
1202fn paint_chart_title(
1203    ctx: &mut PaintCtx<'_>,
1204    content: Rect,
1205    title: Option<&str>,
1206    style: &ChartStyle,
1207) {
1208    if let Some(title) = title.filter(|title| !title.is_empty()) {
1209        paint_text(
1210            ctx,
1211            [content.x, content.y + 11.0],
1212            title,
1213            style.text,
1214            Some(content.w),
1215        );
1216    }
1217}
1218
1219/// Paints three evenly spaced horizontal grid lines.
1220fn paint_grid(ctx: &mut PaintCtx<'_>, plot: Rect, style: &ChartStyle) {
1221    for idx in 1..=3 {
1222        let y = plot.y + plot.h * idx as f32 / 4.0;
1223        ctx.push(DrawCmd::Rect(DrawRect {
1224            rect: Rect::new(plot.x, y, plot.w, 1.0),
1225            color: style.grid,
1226        }));
1227    }
1228}
1229
1230/// Paints one-pixel bottom and left axes.
1231fn paint_axis(ctx: &mut PaintCtx<'_>, plot: Rect, style: &ChartStyle) {
1232    ctx.push(DrawCmd::Rect(DrawRect {
1233        rect: Rect::new(plot.x, plot.bottom() - 1.0, plot.w, 1.0),
1234        color: style.axis,
1235    }));
1236    ctx.push(DrawCmd::Rect(DrawRect {
1237        rect: Rect::new(plot.x, plot.y, 1.0, plot.h),
1238        color: style.axis,
1239    }));
1240}
1241
1242/// Distributes and centers labels across equal-width slots below the plot.
1243fn paint_x_labels(ctx: &mut PaintCtx<'_>, plot: Rect, labels: &[String], style: &ChartStyle) {
1244    if labels.is_empty() || plot.w <= 0.0 {
1245        return;
1246    }
1247    let group_w = plot.w / labels.len() as f32;
1248    for (idx, label) in labels.iter().enumerate() {
1249        let x = plot.x + idx as f32 * group_w;
1250        let rect = Rect::new(x, plot.bottom() + 4.0, group_w, 14.0);
1251        paint_centered_text(ctx, rect, label, style.muted_text);
1252    }
1253}
1254
1255/// Maps a data value to a bottom-origin clamped plot y coordinate.
1256fn value_y(plot: Rect, range: ChartRange, value: f32) -> f32 {
1257    plot.bottom() - range.fraction_for_value(value) * plot.h
1258}
1259
1260/// Maps a chart point through x/y domains into plot coordinates.
1261fn point_to_screen(
1262    plot: Rect,
1263    x_range: ChartRange,
1264    y_range: ChartRange,
1265    point: ailloli_ui_core::ChartPoint,
1266) -> [f32; 2] {
1267    [
1268        plot.x + x_range.fraction_for_value(point.x) * plot.w,
1269        value_y(plot, y_range, point.y),
1270    ]
1271}
1272
1273/// Shapes one unwrapped line and centers it within a rectangle.
1274fn paint_centered_text(ctx: &mut PaintCtx<'_>, rect: Rect, text: &str, style: TextStyle) {
1275    let Some(ts) = ctx.text_system.as_deref_mut() else {
1276        return;
1277    };
1278    let layout = ts.layout_cached(TextLayoutParams {
1279        text,
1280        style,
1281        max_width: Some(rect.w.max(0.0)),
1282        wrap_mode: WrapMode::NoWrap,
1283    });
1284    let baseline = layout
1285        .lines
1286        .first()
1287        .map(|line| line.baseline_y)
1288        .unwrap_or(0.0);
1289    let x = rect.x + (rect.w - layout.metrics.width).max(0.0) * 0.5;
1290    let y = rect.y + (rect.h - layout.metrics.height).max(0.0) * 0.5 + baseline;
1291    ctx.push(DrawCmd::Text(DrawText {
1292        pos: [x, y],
1293        color: style.color,
1294        decoration: ailloli_ui_core::TextDecoration::None,
1295        layout,
1296    }));
1297}
1298
1299/// Shapes and paints one unwrapped line at an explicit baseline position.
1300fn paint_text(
1301    ctx: &mut PaintCtx<'_>,
1302    pos: [f32; 2],
1303    text: &str,
1304    style: TextStyle,
1305    max_width: Option<f32>,
1306) {
1307    let Some(ts) = ctx.text_system.as_deref_mut() else {
1308        return;
1309    };
1310    let layout = ts.layout_cached(TextLayoutParams {
1311        text,
1312        style,
1313        max_width,
1314        wrap_mode: WrapMode::NoWrap,
1315    });
1316    ctx.push(DrawCmd::Text(DrawText {
1317        pos,
1318        color: style.color,
1319        decoration: ailloli_ui_core::TextDecoration::None,
1320        layout,
1321    }));
1322}