Skip to main content

tablo_ui/components/composites/
stat.rs

1use topcoat::{
2    Result,
3    context::Cx,
4    // Renamed: the tile's `icon` prop takes the name.
5    icon::{IconData, icon as icon_view},
6    view::{Attributes, StaticClass, View, class, component, view},
7};
8
9const STAT: StaticClass = class!(
10    "relative flex min-w-0 flex-col gap-3 rounded-xl border border-border bg-card px-4 py-4",
11    "text-card-foreground shadow-card outline-none transition-colors sm:px-5",
12    "focus-visible:ring-2 focus-visible:ring-ring",
13);
14/// A linked tile answers the pointer, as the list rows it leads to do.
15const STAT_LINK: StaticClass = class!("hover:border-rule-strong hover:bg-mark/50");
16/// The label is a caption, its icon trimmed to the caption's size.
17const STAT_LABEL: StaticClass = class!(
18    "tablo-caption flex items-center gap-2 text-muted-foreground",
19    "[&>svg]:size-3.5 [&>svg]:shrink-0",
20);
21/// The figure, in the display face.
22const STAT_VALUE: StaticClass =
23    class!("tablo-figure text-[1.875rem] leading-none text-foreground sm:text-[2.125rem]");
24const STAT_DETAIL: StaticClass =
25    class!("flex items-center gap-1 text-sm [&>svg]:size-4 [&>svg]:shrink-0");
26const STAT_CHART: StaticClass = class!("-mx-1 h-8 w-[calc(100%+0.5rem)] overflow-visible");
27
28/// The sparkline's drawing box: as wide as 100 units, stretched to the tile's width.
29const CHART_WIDTH: f64 = 100.0;
30const CHART_HEIGHT: f64 = 24.0;
31/// Room above and below the line, so the stroke at the extremes stays inside the box.
32const CHART_PAD: f64 = 2.0;
33
34/// One figure for a dashboard: what it counts, the value, and an optional line under it. With an
35/// `href` the whole tile is a link, such as to the list the figure counts.
36///
37/// Lay several out in a grid of your own:
38///
39/// ```rust
40/// # use tablo_ui::{icons, stat};
41/// # use topcoat::{context::Cx, view::{BoxView, ViewExt, view}};
42/// # fn stats(cx: &Cx) -> BoxView<'_> {
43/// view! {
44///     <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
45///         stat(
46///             label: "Posts",
47///             value: "66",
48///             detail: "65 drafts",
49///             icon: icons::FILE_TEXT,
50///             href: "/admin/posts".to_string(),
51///         )
52///         stat(
53///             label: "Comments",
54///             value: "4",
55///             detail: "2 more than last week",
56///             detail_icon: icons::ARROW_UP,
57///             accent: "text-success",
58///             chart: vec![1.0, 3.0, 2.0, 4.0],
59///         )
60///     </div>
61/// }
62/// # .boxed()
63/// # }
64/// ```
65#[component]
66pub async fn stat(
67    cx: &Cx,
68    /// What the value counts, e.g. `"Posts"`.
69    #[into]
70    label: String,
71    /// The figure, formatted, e.g. `"1,204"` or `"98%"`.
72    #[into]
73    value: String,
74    /// Optional line under the value, e.g. `"12 this week"`.
75    #[into]
76    #[default]
77    detail: String,
78    /// Optional icon before the detail line, such as an arrow for its trend.
79    #[into]
80    #[default]
81    detail_icon: Option<IconData>,
82    /// What the detail icon says to a screen reader, e.g. `"Up"`; the icon alone is hidden from
83    /// it.
84    #[into]
85    #[default]
86    detail_icon_label: String,
87    /// The text-color class of the detail line and the chart, e.g. `"text-success"`; muted when
88    /// empty.
89    #[into]
90    #[default]
91    accent: String,
92    /// Optional values the tile draws as a sparkline under the value, oldest first. Fewer than two
93    /// finite values draw none.
94    #[default]
95    chart: Vec<f64>,
96    /// Optional icon before the label.
97    #[into]
98    #[default]
99    icon: Option<IconData>,
100    /// Optional URL the tile links to.
101    #[into]
102    #[default]
103    href: Option<String>,
104    /// Extra attributes for the tile.
105    #[default]
106    mut attrs: Attributes,
107) -> Result<impl View> {
108    let accent = if accent.is_empty() {
109        "text-muted-foreground".to_string()
110    } else {
111        accent
112    };
113    let line = sparkline_points(&chart);
114    let area = line
115        .as_ref()
116        .map(|line| format!("0,{CHART_HEIGHT} {line} {CHART_WIDTH},{CHART_HEIGHT}"));
117    let view_box = format!("0 0 {CHART_WIDTH} {CHART_HEIGHT}");
118    let body = view! {
119        <p class=(STAT_LABEL)>
120            if let Some(glyph) = icon {
121                icon_view(
122                    data: glyph,
123                    attrs: topcoat::view::attributes! { aria-hidden="true" }
124                )
125            }
126            (label)
127        </p>
128        <p class=(STAT_VALUE)>(value)</p>
129        if !detail.is_empty() {
130            <p class=(class!(STAT_DETAIL, accent.clone()))>
131                if let Some(glyph) = detail_icon {
132                    icon_view(
133                        data: glyph,
134                        attrs: topcoat::view::attributes! { aria-hidden="true" }
135                    )
136                }
137                if !detail_icon_label.is_empty() {
138                    <span class="sr-only">
139                        (detail_icon_label)
140                        " "
141                    </span>
142                }
143                (detail)
144            </p>
145        }
146        if let (Some(line), Some(area)) = (line, area) {
147            <svg
148                class=(class!(STAT_CHART, accent))
149                viewBox=(view_box)
150                preserveAspectRatio="none"
151                aria-hidden="true"
152            >
153                <polygon points=(area) fill="currentColor" fill-opacity="0.1" />
154                <polyline
155                    points=(line)
156                    fill="none"
157                    stroke="currentColor"
158                    stroke-width="2"
159                    stroke-linejoin="round"
160                    stroke-linecap="round"
161                    vector-effect="non-scaling-stroke"
162                />
163            </svg>
164        }
165    };
166    Ok(view! {
167        if let Some(href) = href {
168            <a
169                href=(href)
170                class=(class!(STAT, STAT_LINK, attrs.remove("class")))
171                (attrs)
172            >
173                (body)
174            </a>
175        } else {
176            <div class=(class!(STAT, attrs.remove("class"))) (attrs)>(body)</div>
177        }
178    })
179}
180
181/// The `points` of a sparkline over `values` in the chart's drawing box: evenly spaced from the
182/// left edge to the right, the largest value at the top and the smallest at the bottom, a flat
183/// series across the middle. Non-finite values are dropped; fewer than two left draw no line.
184fn sparkline_points(values: &[f64]) -> Option<String> {
185    let values: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
186    if values.len() < 2 {
187        return None;
188    }
189    let (min, max) = values
190        .iter()
191        .fold((f64::INFINITY, f64::NEG_INFINITY), |(min, max), &v| {
192            (min.min(v), max.max(v))
193        });
194    let span = max - min;
195    let last = (values.len() - 1) as f64;
196    let points: Vec<String> = values
197        .iter()
198        .enumerate()
199        .map(|(index, &value)| {
200            let x = index as f64 * CHART_WIDTH / last;
201            // A span that overflows to infinity or is zero has no usable scale.
202            let share = if span.is_finite() && span > 0.0 {
203                (max - value) / span
204            } else {
205                0.5
206            };
207            let y = CHART_PAD + share * (CHART_HEIGHT - 2.0 * CHART_PAD);
208            format!("{x:.2},{y:.2}")
209        })
210        .collect();
211    Some(points.join(" "))
212}
213
214#[cfg(test)]
215mod tests;