Skip to main content

laravel_rust_admin/
widget.rs

1//! What the dashboard shows: stats, charts, and short tables.
2
3use std::collections::BTreeMap;
4use std::future::Future;
5use std::marker::PhantomData;
6
7use futures_util::future::BoxFuture;
8use laravel::http::Request;
9
10use crate::protocol::{
11    BadgeColor, ChartPointDto, ChartStyle, ColumnAlign, DashboardWidgetDto, TableWidgetColumnDto, TableWidgetRowDto,
12    TrendDirection,
13};
14
15/// A widget on the panel's dashboard, built again each time the dashboard loads.
16///
17/// Most widgets are a function given to [`AdminPanel::widget_fn`](crate::AdminPanel::widget_fn).
18/// Implement the trait for a widget that carries settings of its own:
19///
20/// ```ignore
21/// struct SignupsThisWeek { plan: Plan }
22///
23/// impl DashboardWidget for SignupsThisWeek {
24///     async fn resolve(&self, _request: &Request) -> laravel::Result<DashboardWidgetDto> {
25///         let count = User::query().filter(User::plan.eq(self.plan)).count().await?;
26///         Ok(StatWidget::new("signups", "Signups", count.to_string()).build())
27///     }
28/// }
29/// ```
30pub trait DashboardWidget: Send + Sync + 'static {
31    /// Builds the widget for this request.
32    fn resolve(&self, request: &Request) -> impl Future<Output = laravel::Result<DashboardWidgetDto>> + Send;
33}
34
35/// A [`DashboardWidget`] behind a pointer, which the panel keeps a list of.
36pub(crate) trait ErasedWidget: Send + Sync {
37    fn resolve<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<DashboardWidgetDto>>;
38}
39
40impl<W: DashboardWidget> ErasedWidget for W {
41    fn resolve<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<DashboardWidgetDto>> {
42        Box::pin(DashboardWidget::resolve(self, request))
43    }
44}
45
46/// A widget that is a function of nothing, for [`AdminPanel::widget_fn`](crate::AdminPanel::widget_fn).
47pub(crate) struct FnWidget<F>(pub(crate) F);
48
49impl<F, Fut, W> DashboardWidget for FnWidget<F>
50where
51    F: Fn() -> Fut + Send + Sync + 'static,
52    Fut: Future<Output = laravel::Result<W>> + Send,
53    W: Into<DashboardWidgetDto>,
54{
55    async fn resolve(&self, _request: &Request) -> laravel::Result<DashboardWidgetDto> {
56        Ok((self.0)().await?.into())
57    }
58}
59
60/// A widget that is a function of the request, for
61/// [`AdminPanel::widget_for_request`](crate::AdminPanel::widget_for_request).
62pub(crate) struct RequestWidget<F, W>(pub(crate) F, pub(crate) PhantomData<fn() -> W>);
63
64impl<F, W> DashboardWidget for RequestWidget<F, W>
65where
66    F: for<'a> crate::panel::RequestFn<'a, W>,
67    W: Into<DashboardWidgetDto> + 'static,
68{
69    async fn resolve(&self, request: &Request) -> laravel::Result<DashboardWidgetDto> {
70        Ok(self.0.call(request).await?.into())
71    }
72}
73
74/// A number on the dashboard, such as this month's revenue, with what you choose to show around
75/// it: how it changed, its recent history, and a link to where it comes from.
76#[derive(Debug, Clone)]
77pub struct StatWidget {
78    id: String,
79    label: String,
80    value: String,
81    description: Option<String>,
82    trend: Option<String>,
83    trend_direction: Option<TrendDirection>,
84    icon: Option<String>,
85    color: BadgeColor,
86    sparkline: Vec<f64>,
87    href: Option<String>,
88    col_span: u8,
89}
90
91impl StatWidget {
92    /// A stat with an `id` that is unique on the dashboard, a label, and the value to show,
93    /// already formatted.
94    #[must_use]
95    pub fn new(id: impl Into<String>, label: impl Into<String>, value: impl Into<String>) -> Self {
96        Self {
97            id: id.into(),
98            label: label.into(),
99            value: value.into(),
100            description: None,
101            trend: None,
102            trend_direction: None,
103            icon: None,
104            color: BadgeColor::Zinc,
105            sparkline: Vec::new(),
106            href: None,
107            col_span: 1,
108        }
109    }
110
111    /// Adds a line of context under the value, such as `vs. last month`.
112    #[must_use]
113    pub fn description(mut self, description: impl Into<String>) -> Self {
114        self.description = Some(description.into());
115        self
116    }
117
118    /// Shows how the value changed, such as `+12%`, colored by its direction.
119    #[must_use]
120    pub fn trend(mut self, trend: impl Into<String>, direction: TrendDirection) -> Self {
121        self.trend = Some(trend.into());
122        self.trend_direction = Some(direction);
123        self
124    }
125
126    /// Sets the icon in the card's corner, by name.
127    #[must_use]
128    pub fn icon(mut self, icon: impl Into<String>) -> Self {
129        self.icon = Some(icon.into());
130        self
131    }
132
133    /// Sets the color of the sparkline.
134    #[must_use]
135    pub fn color(mut self, color: BadgeColor) -> Self {
136        self.color = color;
137        self
138    }
139
140    /// Draws the stat's recent history as a line across the card, oldest point first.
141    #[must_use]
142    pub fn sparkline(mut self, points: impl IntoIterator<Item = f64>) -> Self {
143        self.sparkline = points.into_iter().collect();
144        self
145    }
146
147    /// Makes the card a link to a path inside the panel, such as `/resources/orders`.
148    #[must_use]
149    pub fn href(mut self, href: impl Into<String>) -> Self {
150        self.href = Some(href.into());
151        self
152    }
153
154    /// Sets how many of the dashboard's four columns the card spans. A stat spans one.
155    #[must_use]
156    pub fn col_span(mut self, span: u8) -> Self {
157        self.col_span = span.clamp(1, 4);
158        self
159    }
160
161    /// Finishes the widget.
162    #[must_use]
163    pub fn build(self) -> DashboardWidgetDto {
164        DashboardWidgetDto::Stat {
165            id: self.id,
166            label: self.label,
167            value: self.value,
168            description: self.description,
169            trend: self.trend,
170            trend_direction: self.trend_direction,
171            icon: self.icon,
172            color: self.color,
173            sparkline: self.sparkline,
174            href: self.href,
175            col_span: self.col_span,
176        }
177    }
178}
179
180impl From<StatWidget> for DashboardWidgetDto {
181    fn from(widget: StatWidget) -> Self {
182        widget.build()
183    }
184}
185
186/// Fluent builder for a dashboard chart widget (bar, area, or horizontal breakdown).
187#[derive(Debug, Clone)]
188pub struct ChartWidget {
189    id: String,
190    title: String,
191    subtitle: Option<String>,
192    style: ChartStyle,
193    points: Vec<ChartPointDto>,
194    value_prefix: Option<String>,
195    value_suffix: Option<String>,
196    col_span: u8,
197}
198
199impl ChartWidget {
200    /// A chart with an `id` that is unique on the dashboard, a title, and a style. It spans two
201    /// of the dashboard's four columns unless you set [`col_span`](Self::col_span).
202    #[must_use]
203    pub fn new(id: impl Into<String>, title: impl Into<String>, style: ChartStyle) -> Self {
204        Self {
205            id: id.into(),
206            title: title.into(),
207            subtitle: None,
208            style,
209            points: Vec::new(),
210            value_prefix: None,
211            value_suffix: None,
212            col_span: 2,
213        }
214    }
215
216    /// Adds a line under the chart's title.
217    #[must_use]
218    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
219        self.subtitle = Some(subtitle.into());
220        self
221    }
222
223    /// Adds a point, drawn in the chart's main color. Points are drawn in the order you add them.
224    #[must_use]
225    pub fn point(mut self, label: impl Into<String>, value: f64) -> Self {
226        self.points.push(ChartPointDto {
227            label: label.into(),
228            value,
229            color: None,
230        });
231        self
232    }
233
234    /// Adds a point with a color of its own, for a breakdown such as orders by status.
235    #[must_use]
236    pub fn colored_point(mut self, label: impl Into<String>, value: f64, color: BadgeColor) -> Self {
237        self.points.push(ChartPointDto {
238            label: label.into(),
239            value,
240            color: Some(color),
241        });
242        self
243    }
244
245    /// Sets text shown before each value, such as `$`.
246    #[must_use]
247    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
248        self.value_prefix = Some(prefix.into());
249        self
250    }
251
252    /// Sets text shown after each value, such as `%`.
253    #[must_use]
254    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
255        self.value_suffix = Some(suffix.into());
256        self
257    }
258
259    /// Sets how many of the dashboard's four columns the chart spans.
260    #[must_use]
261    pub fn col_span(mut self, span: u8) -> Self {
262        self.col_span = span.clamp(1, 4);
263        self
264    }
265
266    /// Finishes the widget.
267    #[must_use]
268    pub fn build(self) -> DashboardWidgetDto {
269        DashboardWidgetDto::Chart {
270            id: self.id,
271            title: self.title,
272            subtitle: self.subtitle,
273            style: self.style,
274            points: self.points,
275            value_prefix: self.value_prefix,
276            value_suffix: self.value_suffix,
277            col_span: self.col_span,
278        }
279    }
280}
281
282impl From<ChartWidget> for DashboardWidgetDto {
283    fn from(widget: ChartWidget) -> Self {
284        widget.build()
285    }
286}
287
288/// Fluent builder for a compact dashboard table widget (e.g. "Recent Orders").
289#[derive(Debug, Clone)]
290pub struct TableWidget {
291    id: String,
292    title: String,
293    subtitle: Option<String>,
294    action_label: Option<String>,
295    action_href: Option<String>,
296    columns: Vec<TableWidgetColumnDto>,
297    rows: Vec<TableWidgetRowDto>,
298    col_span: u8,
299}
300
301impl TableWidget {
302    /// A table with an `id` that is unique on the dashboard, and a title. It spans the dashboard's
303    /// full width unless you set [`col_span`](Self::col_span).
304    #[must_use]
305    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
306        Self {
307            id: id.into(),
308            title: title.into(),
309            subtitle: None,
310            action_label: None,
311            action_href: None,
312            columns: Vec::new(),
313            rows: Vec::new(),
314            col_span: 4,
315        }
316    }
317
318    /// Adds a line under the table's title.
319    #[must_use]
320    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
321        self.subtitle = Some(subtitle.into());
322        self
323    }
324
325    /// Adds a link beside the title, such as `View all`, to a path inside the panel.
326    #[must_use]
327    pub fn action(mut self, label: impl Into<String>, href: impl Into<String>) -> Self {
328        self.action_label = Some(label.into());
329        self.action_href = Some(href.into());
330        self
331    }
332
333    /// Adds a column. `key` names the cell of each row that the column shows.
334    #[must_use]
335    pub fn column(mut self, key: impl Into<String>, label: impl Into<String>, align: ColumnAlign) -> Self {
336        self.columns.push(TableWidgetColumnDto {
337            key: key.into(),
338            label: label.into(),
339            align,
340            badge_colors: BTreeMap::new(),
341        });
342        self
343    }
344
345    /// Adds a column that shows its cells as badges, colored by their value.
346    #[must_use]
347    pub fn badge_column(
348        mut self,
349        key: impl Into<String>,
350        label: impl Into<String>,
351        colors: impl IntoIterator<Item = (String, BadgeColor)>,
352    ) -> Self {
353        self.columns.push(TableWidgetColumnDto {
354            key: key.into(),
355            label: label.into(),
356            align: ColumnAlign::Left,
357            badge_colors: colors.into_iter().collect(),
358        });
359        self
360    }
361
362    /// Adds a row: a key that is unique in the table, an optional path inside the panel to open
363    /// when the row is clicked, and the row's cells by column key.
364    #[must_use]
365    pub fn row(
366        mut self,
367        key: impl Into<String>,
368        href: Option<String>,
369        cells: BTreeMap<String, serde_json::Value>,
370    ) -> Self {
371        self.rows.push(TableWidgetRowDto {
372            key: key.into(),
373            href,
374            cells,
375        });
376        self
377    }
378
379    /// Sets how many of the dashboard's four columns the table spans.
380    #[must_use]
381    pub fn col_span(mut self, span: u8) -> Self {
382        self.col_span = span.clamp(1, 4);
383        self
384    }
385
386    /// Finishes the widget.
387    #[must_use]
388    pub fn build(self) -> DashboardWidgetDto {
389        DashboardWidgetDto::Table {
390            id: self.id,
391            title: self.title,
392            subtitle: self.subtitle,
393            action_label: self.action_label,
394            action_href: self.action_href,
395            columns: self.columns,
396            rows: self.rows,
397            col_span: self.col_span,
398        }
399    }
400}
401
402impl From<TableWidget> for DashboardWidgetDto {
403    fn from(widget: TableWidget) -> Self {
404        widget.build()
405    }
406}