Skip to main content

ignite_core/
widget.rs

1//! Dashboard widgets: the stat cards and the latest-records tables a resource
2//! can show on the dashboard, and the panel's own widgets.
3//!
4//! A [`Stat`] is one card, as Filament's `Stat::make($label, $value)` in a stats overview
5//! widget: its label is the card's title, its value the number shown, and an optional
6//! description the line under it. A resource gives its cards with
7//! [`IgniteResource::stats`](crate::IgniteResource::stats) (or a runtime resource's
8//! [`RuntimeData::stats`](crate::RuntimeData::stats)); the panel gives cards of its own with a
9//! [`StatsOverviewWidget`] passed to `Ignite::widget`, as Filament's panel `widgets()`. The
10//! dashboard shows every card in a grid: the panel's widgets first, in the order they were
11//! added, then each resource's, in the order of the navigation's resources.
12
13use std::fmt;
14use std::sync::Arc;
15
16use orbit_orm::{Database, Error};
17
18use crate::policy::ActingUser;
19use crate::query::ListQuery;
20use crate::runtime_resource::{Row, RuntimeData, RuntimeFuture};
21
22/// One stat card on the dashboard: a label and a whole-number value.
23#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
24pub struct StatWidget {
25    /// The card's heading, such as "Users".
26    pub label: &'static str,
27    /// The number the card shows.
28    pub value: i64,
29}
30
31/// A dashboard table of the newest records of a resource (added in v1).
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct LatestRecords {
34    /// The table's heading, such as "Latest users".
35    pub title: &'static str,
36    /// The keys of the resource's columns to show, in order. Each key must be a column key.
37    pub columns: &'static [&'static str],
38    /// The most records the table shows, newest first.
39    pub limit: i64,
40}
41
42/// One card of the dashboard, as Filament's `Stat::make($label, $value)`: a title (the label),
43/// the number shown and an optional description under it, such as "3 drafts".
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Stat {
46    label: String,
47    value: String,
48    description: Option<String>,
49}
50
51impl Stat {
52    /// A card titled `label` showing `value`, such as `Stat::make("Posts", 12)`. The value is
53    /// shown as its text, so it may be formatted already, such as `"1.2k"`.
54    pub fn make(label: impl Into<String>, value: impl ToString) -> Self {
55        Stat {
56            label: label.into(),
57            value: value.to_string(),
58            description: None,
59        }
60    }
61
62    /// The line under the value, as Filament's `description()`.
63    pub fn description(mut self, description: impl Into<String>) -> Self {
64        self.description = Some(description.into());
65        self
66    }
67
68    /// The card's title.
69    pub fn get_label(&self) -> &str {
70        &self.label
71    }
72
73    /// The value, as shown.
74    pub fn get_value(&self) -> &str {
75        &self.value
76    }
77
78    /// The description, if set.
79    pub fn get_description(&self) -> Option<&str> {
80        self.description.as_deref()
81    }
82}
83
84impl From<StatWidget> for Stat {
85    fn from(widget: StatWidget) -> Self {
86        Stat::make(widget.label, widget.value)
87    }
88}
89
90/// A widget of the panel's own on the dashboard, as Filament's `StatsOverviewWidget` with its
91/// `getStats()`: the cards it computes for the signed-in user. Pass it to `Ignite::widget`.
92///
93/// ```ignore
94/// struct SiteStats;
95///
96/// impl StatsOverviewWidget for SiteStats {
97///     fn stats<'a>(&'a self, db: &'a Database, _: &'a ActingUser) -> RuntimeFuture<'a, Vec<Stat>> {
98///         Box::pin(async move {
99///             let comments = count_pending_comments(db).await?;
100///             Ok(vec![Stat::make("Comments", comments).description("awaiting moderation")])
101///         })
102///     }
103/// }
104/// ```
105pub trait StatsOverviewWidget: Send + Sync + 'static {
106    /// The cards, in display order, for `user`.
107    fn stats<'a>(&'a self, db: &'a Database, user: &'a ActingUser) -> RuntimeFuture<'a, Vec<Stat>>;
108
109    /// Whether `user` sees the widget, as Filament's `canView()`. The default is every user.
110    fn can_view(&self, user: &ActingUser) -> bool {
111        let _ = user;
112        true
113    }
114}
115
116/// One row of a [`ListWidget`]: a label, an optional value beside it and an optional link,
117/// such as a post's title linking to its edit form and its date as the value, as the rows of
118/// WordPress's "Activity" and "Recently Published" boxes.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct ListWidgetRow {
121    label: String,
122    value: Option<String>,
123    url: Option<String>,
124}
125
126impl ListWidgetRow {
127    /// A row showing `label`.
128    pub fn make(label: impl Into<String>) -> Self {
129        ListWidgetRow {
130            label: label.into(),
131            value: None,
132            url: None,
133        }
134    }
135
136    /// The text beside the label, such as a date or a count.
137    pub fn value(mut self, value: impl ToString) -> Self {
138        self.value = Some(value.to_string());
139        self
140    }
141
142    /// The address the label links to, such as `/admin/posts/7/edit`. Only a path (starting
143    /// with `/`, not `//`) or an `http://` or `https://` URL is linked; anything else, such as
144    /// a `javascript:` URL, shows the label without a link.
145    pub fn url(mut self, url: impl Into<String>) -> Self {
146        self.url = Some(url.into());
147        self
148    }
149
150    /// The label.
151    pub fn get_label(&self) -> &str {
152        &self.label
153    }
154
155    /// The value, if set.
156    pub fn get_value(&self) -> Option<&str> {
157        self.value.as_deref()
158    }
159
160    /// The link, if set and safe to link (see [`url`](Self::url)).
161    pub fn get_url(&self) -> Option<&str> {
162        self.url.as_deref().filter(|url| safe_url(url))
163    }
164}
165
166/// Whether `url` is a path of this site or an `http(s)` URL, so a link cannot run script.
167pub fn safe_url(url: &str) -> bool {
168    let lower = url.trim_start().to_ascii_lowercase();
169    !url.chars().any(char::is_control)
170        && ((lower.starts_with('/') && !lower.starts_with("//") && !lower.starts_with("/\\"))
171            || lower.starts_with("https://")
172            || lower.starts_with("http://"))
173}
174
175type RowsFn = Arc<
176    dyn for<'a> Fn(&'a Database, &'a ActingUser) -> RuntimeFuture<'a, Vec<ListWidgetRow>>
177        + Send
178        + Sync,
179>;
180type ViewRule = Arc<dyn Fn(&ActingUser) -> bool + Send + Sync>;
181
182/// A dashboard widget that lists rows under a title, as a Filament custom widget with its own
183/// view: the rows of WordPress's "Activity" or "Recently Published" box. Pass it to
184/// `Ignite::list_widget`. The panel renders it with its `partials.widgets.list` view (a theme
185/// can replace it), escaping every label, value and link.
186///
187/// ```ignore
188/// ListWidget::make("Recently Published")
189///     .rows_from(posts.data.clone(), ListQuery { page: 1, per_page: 5, search: None,
190///         sort: Some(("published_at".into(), Direction::Desc)),
191///         filter: ListFilter::new().where_eq("status", "publish") },
192///         |row| ListWidgetRow::make(row["title"].as_str().unwrap_or_default())
193///             .value(row["published_at"].as_str().unwrap_or_default())
194///             .url(format!("/admin/posts/{}/edit", row["id"])))
195///     .empty_state("No posts published yet.")
196/// ```
197#[derive(Clone)]
198pub struct ListWidget {
199    title: String,
200    rows: Option<RowsFn>,
201    empty_state: String,
202    can_view: Option<ViewRule>,
203}
204
205impl fmt::Debug for ListWidget {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        f.debug_struct("ListWidget")
208            .field("title", &self.title)
209            .field("rows", &self.rows.is_some())
210            .field("empty_state", &self.empty_state)
211            .field("can_view", &self.can_view.is_some())
212            .finish()
213    }
214}
215
216/// What a [`ListWidget`] shows when it has no rows, unless it sets its own.
217pub const DEFAULT_EMPTY_STATE: &str = "Nothing to show yet.";
218
219impl ListWidget {
220    /// A widget titled `title`, with no rows yet.
221    pub fn make(title: impl Into<String>) -> Self {
222        ListWidget {
223            title: title.into(),
224            rows: None,
225            empty_state: DEFAULT_EMPTY_STATE.to_string(),
226            can_view: None,
227        }
228    }
229
230    /// The rows, computed for the signed-in user on each dashboard request. Write it as
231    /// `|db, user| Box::pin(async move { ... })`.
232    pub fn rows<F>(mut self, rows: F) -> Self
233    where
234        F: for<'a> Fn(&'a Database, &'a ActingUser) -> RuntimeFuture<'a, Vec<ListWidgetRow>>
235            + Send
236            + Sync
237            + 'static,
238    {
239        self.rows = Some(Arc::new(rows));
240        self
241    }
242
243    /// The rows from a [`RuntimeData`]: its [`list_for`](RuntimeData::list_for) for the
244    /// signed-in user with `query` (its page, sort and filter), each row turned into a
245    /// [`ListWidgetRow`] by `map`. A runtime resource's data is its `data` field.
246    pub fn rows_from<M>(self, data: Arc<dyn RuntimeData>, query: ListQuery, map: M) -> Self
247    where
248        M: Fn(&Row) -> ListWidgetRow + Send + Sync + 'static,
249    {
250        let map = Arc::new(map);
251        self.rows(move |db, user| {
252            let data = Arc::clone(&data);
253            let query = query.clone();
254            let map = Arc::clone(&map);
255            Box::pin(async move {
256                let page = data.list_for(db, user, &query).await?;
257                Ok(page.rows.iter().map(|row| map(row)).collect())
258            })
259        })
260    }
261
262    /// The text shown when there are no rows. The default is [`DEFAULT_EMPTY_STATE`].
263    pub fn empty_state(mut self, text: impl Into<String>) -> Self {
264        self.empty_state = text.into();
265        self
266    }
267
268    /// Who sees the widget, as Filament's `canView()`. The default is every user.
269    pub fn can_view(mut self, rule: impl Fn(&ActingUser) -> bool + Send + Sync + 'static) -> Self {
270        self.can_view = Some(Arc::new(rule));
271        self
272    }
273
274    /// The title.
275    pub fn get_title(&self) -> &str {
276        &self.title
277    }
278
279    /// The text shown without rows.
280    pub fn get_empty_state(&self) -> &str {
281        &self.empty_state
282    }
283
284    /// Whether `user` sees the widget.
285    pub fn is_visible_to(&self, user: &ActingUser) -> bool {
286        self.can_view.as_ref().is_none_or(|rule| rule(user))
287    }
288
289    /// The rows for `user`. None when the widget sets none.
290    pub async fn load(
291        &self,
292        db: &Database,
293        user: &ActingUser,
294    ) -> Result<Vec<ListWidgetRow>, Error> {
295        match &self.rows {
296            Some(rows) => rows(db, user).await,
297            None => Ok(Vec::new()),
298        }
299    }
300}
301
302/// A dashboard widget with a short form that creates a record of a resource, as a Filament
303/// custom widget with a form: WordPress's "Quick Draft" (a title, the content and "Save
304/// Draft"). Pass it to `Ignite::form_widget`. The form shows the resource's fields (all of
305/// them, or the ones [`fields`](Self::fields) names, in that order) and posts to the
306/// resource's create route with the CSRF token, so the resource's validation, policy and
307/// `create_for` run as for its own form; the panel then comes back to the dashboard with the
308/// flash message. A form that does not validate shows the resource's create form with its
309/// errors. The widget shows only to a user who may create a record of the resource.
310///
311/// ```ignore
312/// FormWidget::make("Quick Draft", "posts")
313///     .fields(["title", "content"])
314///     .hidden("status", "draft")
315///     .submit_label("Save Draft")
316/// ```
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct FormWidget {
319    title: String,
320    resource: String,
321    fields: Vec<String>,
322    hidden: Vec<(String, String)>,
323    submit_label: String,
324}
325
326impl FormWidget {
327    /// A widget titled `title` whose form creates a record of the resource at `slug`.
328    pub fn make(title: impl Into<String>, slug: impl Into<String>) -> Self {
329        FormWidget {
330            title: title.into(),
331            resource: slug.into(),
332            fields: Vec::new(),
333            hidden: Vec::new(),
334            submit_label: "Save".to_string(),
335        }
336    }
337
338    /// The resource's fields the form shows, in order. The default is every field.
339    pub fn fields<I, S>(mut self, names: I) -> Self
340    where
341        I: IntoIterator<Item = S>,
342        S: Into<String>,
343    {
344        self.fields = names.into_iter().map(Into::into).collect();
345        self
346    }
347
348    /// A value the form sends without showing it, such as `status` = `draft`. The resource's
349    /// validation reads it as any other field's value.
350    pub fn hidden(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
351        self.hidden.push((name.into(), value.into()));
352        self
353    }
354
355    /// The button's text. The default is "Save".
356    pub fn submit_label(mut self, label: impl Into<String>) -> Self {
357        self.submit_label = label.into();
358        self
359    }
360
361    /// The title.
362    pub fn get_title(&self) -> &str {
363        &self.title
364    }
365
366    /// The slug of the resource the form creates a record of.
367    pub fn get_resource(&self) -> &str {
368        &self.resource
369    }
370
371    /// The names of the fields the form shows; empty for every field.
372    pub fn get_fields(&self) -> &[String] {
373        &self.fields
374    }
375
376    /// The values the form sends without showing them.
377    pub fn get_hidden(&self) -> &[(String, String)] {
378        &self.hidden
379    }
380
381    /// The button's text.
382    pub fn get_submit_label(&self) -> &str {
383        &self.submit_label
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    #[test]
392    fn only_paths_and_web_urls_are_linked() {
393        assert!(safe_url("/admin/posts/1/edit"));
394        assert!(safe_url("https://example.test/a"));
395        assert!(safe_url("HTTP://example.test"));
396        assert!(!safe_url("javascript:alert(1)"));
397        assert!(!safe_url(" JavaScript:alert(1)"));
398        assert!(!safe_url("//evil.test"));
399        assert!(!safe_url("/\\evil.test"));
400        assert!(!safe_url("data:text/html,x"));
401        assert!(!safe_url("/a\nb"));
402        assert_eq!(ListWidgetRow::make("x").url("javascript:x").get_url(), None);
403    }
404}