laravel-rust-admin 0.1.1

Admin panel framework for Laravel for Rust: auto-generated CRUD tables, forms, actions, and dashboard widgets from your models.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! What the dashboard shows: stats, charts, and short tables.

use std::collections::BTreeMap;
use std::future::Future;
use std::marker::PhantomData;

use futures_util::future::BoxFuture;
use laravel::http::Request;

use crate::protocol::{
    BadgeColor, ChartPointDto, ChartStyle, ColumnAlign, DashboardWidgetDto, TableWidgetColumnDto, TableWidgetRowDto,
    TrendDirection,
};

/// A widget on the panel's dashboard, built again each time the dashboard loads.
///
/// Most widgets are a function given to [`AdminPanel::widget_fn`](crate::AdminPanel::widget_fn).
/// Implement the trait for a widget that carries settings of its own:
///
/// ```ignore
/// struct SignupsThisWeek { plan: Plan }
///
/// impl DashboardWidget for SignupsThisWeek {
///     async fn resolve(&self, _request: &Request) -> laravel::Result<DashboardWidgetDto> {
///         let count = User::query().filter(User::plan.eq(self.plan)).count().await?;
///         Ok(StatWidget::new("signups", "Signups", count.to_string()).build())
///     }
/// }
/// ```
pub trait DashboardWidget: Send + Sync + 'static {
    /// Builds the widget for this request.
    fn resolve(&self, request: &Request) -> impl Future<Output = laravel::Result<DashboardWidgetDto>> + Send;
}

/// A [`DashboardWidget`] behind a pointer, which the panel keeps a list of.
pub(crate) trait ErasedWidget: Send + Sync {
    fn resolve<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<DashboardWidgetDto>>;
}

impl<W: DashboardWidget> ErasedWidget for W {
    fn resolve<'a>(&'a self, request: &'a Request) -> BoxFuture<'a, laravel::Result<DashboardWidgetDto>> {
        Box::pin(DashboardWidget::resolve(self, request))
    }
}

/// A widget that is a function of nothing, for [`AdminPanel::widget_fn`](crate::AdminPanel::widget_fn).
pub(crate) struct FnWidget<F>(pub(crate) F);

impl<F, Fut, W> DashboardWidget for FnWidget<F>
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = laravel::Result<W>> + Send,
    W: Into<DashboardWidgetDto>,
{
    async fn resolve(&self, _request: &Request) -> laravel::Result<DashboardWidgetDto> {
        Ok((self.0)().await?.into())
    }
}

/// A widget that is a function of the request, for
/// [`AdminPanel::widget_for_request`](crate::AdminPanel::widget_for_request).
pub(crate) struct RequestWidget<F, W>(pub(crate) F, pub(crate) PhantomData<fn() -> W>);

impl<F, W> DashboardWidget for RequestWidget<F, W>
where
    F: for<'a> crate::panel::RequestFn<'a, W>,
    W: Into<DashboardWidgetDto> + 'static,
{
    async fn resolve(&self, request: &Request) -> laravel::Result<DashboardWidgetDto> {
        Ok(self.0.call(request).await?.into())
    }
}

/// A number on the dashboard, such as this month's revenue, with what you choose to show around
/// it: how it changed, its recent history, and a link to where it comes from.
#[derive(Debug, Clone)]
pub struct StatWidget {
    id: String,
    label: String,
    value: String,
    description: Option<String>,
    trend: Option<String>,
    trend_direction: Option<TrendDirection>,
    icon: Option<String>,
    color: BadgeColor,
    sparkline: Vec<f64>,
    href: Option<String>,
    col_span: u8,
}

impl StatWidget {
    /// A stat with an `id` that is unique on the dashboard, a label, and the value to show,
    /// already formatted.
    #[must_use]
    pub fn new(id: impl Into<String>, label: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value: value.into(),
            description: None,
            trend: None,
            trend_direction: None,
            icon: None,
            color: BadgeColor::Zinc,
            sparkline: Vec::new(),
            href: None,
            col_span: 1,
        }
    }

    /// Adds a line of context under the value, such as `vs. last month`.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Shows how the value changed, such as `+12%`, colored by its direction.
    #[must_use]
    pub fn trend(mut self, trend: impl Into<String>, direction: TrendDirection) -> Self {
        self.trend = Some(trend.into());
        self.trend_direction = Some(direction);
        self
    }

    /// Sets the icon in the card's corner, by name.
    #[must_use]
    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// Sets the color of the sparkline.
    #[must_use]
    pub fn color(mut self, color: BadgeColor) -> Self {
        self.color = color;
        self
    }

    /// Draws the stat's recent history as a line across the card, oldest point first.
    #[must_use]
    pub fn sparkline(mut self, points: impl IntoIterator<Item = f64>) -> Self {
        self.sparkline = points.into_iter().collect();
        self
    }

    /// Makes the card a link to a path inside the panel, such as `/resources/orders`.
    #[must_use]
    pub fn href(mut self, href: impl Into<String>) -> Self {
        self.href = Some(href.into());
        self
    }

    /// Sets how many of the dashboard's four columns the card spans. A stat spans one.
    #[must_use]
    pub fn col_span(mut self, span: u8) -> Self {
        self.col_span = span.clamp(1, 4);
        self
    }

    /// Finishes the widget.
    #[must_use]
    pub fn build(self) -> DashboardWidgetDto {
        DashboardWidgetDto::Stat {
            id: self.id,
            label: self.label,
            value: self.value,
            description: self.description,
            trend: self.trend,
            trend_direction: self.trend_direction,
            icon: self.icon,
            color: self.color,
            sparkline: self.sparkline,
            href: self.href,
            col_span: self.col_span,
        }
    }
}

impl From<StatWidget> for DashboardWidgetDto {
    fn from(widget: StatWidget) -> Self {
        widget.build()
    }
}

/// Fluent builder for a dashboard chart widget (bar, area, or horizontal breakdown).
#[derive(Debug, Clone)]
pub struct ChartWidget {
    id: String,
    title: String,
    subtitle: Option<String>,
    style: ChartStyle,
    points: Vec<ChartPointDto>,
    value_prefix: Option<String>,
    value_suffix: Option<String>,
    col_span: u8,
}

impl ChartWidget {
    /// A chart with an `id` that is unique on the dashboard, a title, and a style. It spans two
    /// of the dashboard's four columns unless you set [`col_span`](Self::col_span).
    #[must_use]
    pub fn new(id: impl Into<String>, title: impl Into<String>, style: ChartStyle) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            subtitle: None,
            style,
            points: Vec::new(),
            value_prefix: None,
            value_suffix: None,
            col_span: 2,
        }
    }

    /// Adds a line under the chart's title.
    #[must_use]
    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }

    /// Adds a point, drawn in the chart's main color. Points are drawn in the order you add them.
    #[must_use]
    pub fn point(mut self, label: impl Into<String>, value: f64) -> Self {
        self.points.push(ChartPointDto {
            label: label.into(),
            value,
            color: None,
        });
        self
    }

    /// Adds a point with a color of its own, for a breakdown such as orders by status.
    #[must_use]
    pub fn colored_point(mut self, label: impl Into<String>, value: f64, color: BadgeColor) -> Self {
        self.points.push(ChartPointDto {
            label: label.into(),
            value,
            color: Some(color),
        });
        self
    }

    /// Sets text shown before each value, such as `$`.
    #[must_use]
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.value_prefix = Some(prefix.into());
        self
    }

    /// Sets text shown after each value, such as `%`.
    #[must_use]
    pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
        self.value_suffix = Some(suffix.into());
        self
    }

    /// Sets how many of the dashboard's four columns the chart spans.
    #[must_use]
    pub fn col_span(mut self, span: u8) -> Self {
        self.col_span = span.clamp(1, 4);
        self
    }

    /// Finishes the widget.
    #[must_use]
    pub fn build(self) -> DashboardWidgetDto {
        DashboardWidgetDto::Chart {
            id: self.id,
            title: self.title,
            subtitle: self.subtitle,
            style: self.style,
            points: self.points,
            value_prefix: self.value_prefix,
            value_suffix: self.value_suffix,
            col_span: self.col_span,
        }
    }
}

impl From<ChartWidget> for DashboardWidgetDto {
    fn from(widget: ChartWidget) -> Self {
        widget.build()
    }
}

/// Fluent builder for a compact dashboard table widget (e.g. "Recent Orders").
#[derive(Debug, Clone)]
pub struct TableWidget {
    id: String,
    title: String,
    subtitle: Option<String>,
    action_label: Option<String>,
    action_href: Option<String>,
    columns: Vec<TableWidgetColumnDto>,
    rows: Vec<TableWidgetRowDto>,
    col_span: u8,
}

impl TableWidget {
    /// A table with an `id` that is unique on the dashboard, and a title. It spans the dashboard's
    /// full width unless you set [`col_span`](Self::col_span).
    #[must_use]
    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            subtitle: None,
            action_label: None,
            action_href: None,
            columns: Vec::new(),
            rows: Vec::new(),
            col_span: 4,
        }
    }

    /// Adds a line under the table's title.
    #[must_use]
    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }

    /// Adds a link beside the title, such as `View all`, to a path inside the panel.
    #[must_use]
    pub fn action(mut self, label: impl Into<String>, href: impl Into<String>) -> Self {
        self.action_label = Some(label.into());
        self.action_href = Some(href.into());
        self
    }

    /// Adds a column. `key` names the cell of each row that the column shows.
    #[must_use]
    pub fn column(mut self, key: impl Into<String>, label: impl Into<String>, align: ColumnAlign) -> Self {
        self.columns.push(TableWidgetColumnDto {
            key: key.into(),
            label: label.into(),
            align,
            badge_colors: BTreeMap::new(),
        });
        self
    }

    /// Adds a column that shows its cells as badges, colored by their value.
    #[must_use]
    pub fn badge_column(
        mut self,
        key: impl Into<String>,
        label: impl Into<String>,
        colors: impl IntoIterator<Item = (String, BadgeColor)>,
    ) -> Self {
        self.columns.push(TableWidgetColumnDto {
            key: key.into(),
            label: label.into(),
            align: ColumnAlign::Left,
            badge_colors: colors.into_iter().collect(),
        });
        self
    }

    /// Adds a row: a key that is unique in the table, an optional path inside the panel to open
    /// when the row is clicked, and the row's cells by column key.
    #[must_use]
    pub fn row(
        mut self,
        key: impl Into<String>,
        href: Option<String>,
        cells: BTreeMap<String, serde_json::Value>,
    ) -> Self {
        self.rows.push(TableWidgetRowDto {
            key: key.into(),
            href,
            cells,
        });
        self
    }

    /// Sets how many of the dashboard's four columns the table spans.
    #[must_use]
    pub fn col_span(mut self, span: u8) -> Self {
        self.col_span = span.clamp(1, 4);
        self
    }

    /// Finishes the widget.
    #[must_use]
    pub fn build(self) -> DashboardWidgetDto {
        DashboardWidgetDto::Table {
            id: self.id,
            title: self.title,
            subtitle: self.subtitle,
            action_label: self.action_label,
            action_href: self.action_href,
            columns: self.columns,
            rows: self.rows,
            col_span: self.col_span,
        }
    }
}

impl From<TableWidget> for DashboardWidgetDto {
    fn from(widget: TableWidget) -> Self {
        widget.build()
    }
}