tablo-core 0.9.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! [`Page`] — a panel page that is not a resource: a dashboard, a report, a
//! settings screen, a media library — and the [`PageDef`] it declares.

use std::{any::TypeId, future::Future, sync::Arc};

use topcoat::{
    Result,
    context::Cx,
    icon::IconData,
    view::{BoxView, View, ViewExt},
};

pub use self::filters::{PageFilter, PageFilters};
use crate::{
    HeaderAction, HeaderActions, Widget,
    naming::{kebab_case, sentence_case, type_stem},
    navigation::NavigationItem,
    widget::WidgetGrid,
};

/// A panel page that is not a resource, mounted at `{prefix}/{slug}` with a
/// sidebar entry; the panel owns the route and entry while the page owns its
/// markup.
///
/// ```rust
/// # use tablo_core::{Page, Panel};
/// struct ReportsPage;
///
/// impl Page for ReportsPage {}
///
/// Panel::new("admin").page::<ReportsPage>(); // GET /admin/reports
/// ```
///
/// A page serves one `GET` with a sidebar entry, which [`PageDef::access`] limits
/// to the users it admits. A form it renders posts to an app-declared route the
/// auth gate covers; that route asks [`can_open`](crate::can_open) itself.
pub trait Page: Sized + Send + Sync + 'static {
    /// The page's slug, sidebar entry, access and header actions. Defaults to
    /// [`PageDef::new`]: every default.
    ///
    /// [`Panel::page_with`](crate::Panel::page_with) adjusts it for one panel.
    fn declare() -> PageDef {
        PageDef::new()
    }

    /// Render the page body. The panel checks for a resolved user and
    /// [`PageDef::access`] before calling it.
    ///
    /// Defaults to the page its [`PageDef`] declares: the [`title`](PageDef::title) and
    /// [`description`](PageDef::description), the buttons of its
    /// [`header_action`](PageDef::header_action)s, and the grid of its
    /// [`widget`](PageDef::widget)s. A page that renders more places those parts itself, through
    /// [`header_action_buttons`](crate::header_action_buttons) and [`widgets`](crate::widgets):
    ///
    /// ```rust
    /// # use tablo_core::Page;
    /// # use topcoat::{Result, context::Cx, view::{View, view}};
    /// struct ReportsPage;
    ///
    /// impl Page for ReportsPage {
    ///     async fn render(cx: &Cx) -> Result<impl View> {
    ///         Ok(view! {
    ///             tablo_ui::page(
    ///                 tablo_ui::page_header(tablo_ui::page_title("Reports"))
    ///                 tablo_ui::page_content((tablo_core::widgets::<Self>(cx)) "…")
    ///             )
    ///         })
    ///     }
    /// }
    /// ```
    fn render(cx: &Cx) -> impl Future<Output = Result<impl View>> + Send {
        async move { Ok(declared_body(cx, TypeId::of::<Self>())) }
    }
}

/// Renders the page of type `page` as its [`PageDef`] declares it. The panel installs it: a page's
/// header and grid are the serving layer's markup.
pub(crate) struct PageBody(pub(crate) for<'a> fn(&'a Cx, TypeId) -> BoxView<'a>);

/// The body [`Page::render`] defaults to; nothing on a router that mounts no panel.
fn declared_body(cx: &Cx, page: TypeId) -> BoxView<'_> {
    match topcoat::context::try_context::<PageBody>(cx) {
        Some(PageBody(render)) => render(cx, page),
        None => ().boxed(),
    }
}

/// Whether the request's user may open a page.
type AccessFn = dyn Fn(&Cx) -> bool + Send + Sync;

/// What a [`Page`] declares: its slug, sidebar entry, title, access, header actions and widgets.
///
/// [`Page::declare`] returns one, and [`Panel::page_with`](crate::Panel::page_with) adjusts it for
/// one panel. Every setting has a default, so a page sets only what differs:
///
/// ```rust
/// # use tablo_core::{Page, PageDef};
/// # use topcoat::{Result, context::Cx, view::View};
/// struct MediaLibraryPage;
///
/// impl Page for MediaLibraryPage {
///     fn declare() -> PageDef {
///         PageDef::new().slug("media").icon(tablo_ui::icons::IMAGE)
///     }
///
///     async fn render(_cx: &Cx) -> Result<impl View> {
///         Ok(())
///     }
/// }
/// ```
///
/// The panel builds the def once when it mounts and serves the result to every request.
pub struct PageDef {
    slug: Option<String>,
    label: Option<crate::Text>,
    icon: Option<IconData>,
    navigation_order: Option<i32>,
    navigation_group: Option<crate::Text>,
    navigation: Option<NavigationItem>,
    navigation_hidden: bool,
    title: Option<crate::Text>,
    description: Option<crate::Text>,
    access: Arc<AccessFn>,
    access_declared: bool,
    header_actions: HeaderActions,
    widgets: WidgetGrid,
    filters: Vec<PageFilter>,
}

impl PageDef {
    /// A def with every default: the slug and label from the page's type name, and access for
    /// every signed-in user.
    pub fn new() -> Self {
        Self::default()
    }

    /// The URL segment under the panel prefix: `"media"` mounts the page at
    /// `{panel prefix}/media`.
    ///
    /// Defaults to the page type's name without a trailing `Page`, kebab-cased:
    /// `MediaLibraryPage` → `media-library`. [`Panel::home`](crate::Panel::home) mounts the page
    /// at the prefix and does not read it.
    #[must_use]
    pub fn slug(mut self, slug: impl Into<String>) -> Self {
        self.slug = Some(slug.into());
        self
    }

    /// The sidebar label.
    ///
    /// Defaults to the message `page-{name}` of the panel's catalogs, else the page type's name
    /// without a trailing `Page`, in sentence case: `MediaLibraryPage` reads `page-media-library`,
    /// else `Media library`.
    #[must_use]
    pub fn label(mut self, label: impl Into<crate::Text>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// The icon of the page's sidebar entry, replacing the icon of a
    /// [`navigation`](Self::navigation) item.
    #[must_use]
    pub fn icon(mut self, icon: IconData) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Where the sidebar entry sorts among the panel's entries, lowest first; defaults to `0`, and
    /// entries of equal order keep their registration order. It replaces the order of a
    /// [`navigation`](Self::navigation) item.
    #[must_use]
    pub fn navigation_order(mut self, order: i32) -> Self {
        self.navigation_order = Some(order);
        self
    }

    /// The labelled sidebar group the entry renders in, such as `"Reports"`; defaults to none,
    /// above every group. It replaces the group of a [`navigation`](Self::navigation) item.
    #[must_use]
    pub fn navigation_group(mut self, group: impl Into<crate::Text>) -> Self {
        self.navigation_group = Some(group.into());
        self
    }

    /// Replaces the sidebar entry, for one that links somewhere other than the page:
    /// `NavigationItem::at("Exports", "/admin/reports?tab=exports")`. [`icon`](Self::icon),
    /// [`navigation_order`](Self::navigation_order) and
    /// [`navigation_group`](Self::navigation_group) still apply to it.
    #[must_use]
    pub fn navigation(mut self, item: NavigationItem) -> Self {
        self.navigation = Some(item);
        self
    }

    /// Keeps the page out of the sidebar. It stays mounted at its URL, and
    /// [`access`](Self::access) still decides who may open it: link it from a
    /// [user menu item](crate::Panel::user_menu_item), another page or a notification.
    #[must_use]
    pub fn without_navigation(mut self) -> Self {
        self.navigation_hidden = true;
        self
    }

    /// The heading the default [`render`](Page::render) shows. Defaults to the
    /// [`label`](Self::label) when one is given, else the label of the
    /// [`navigation`](Self::navigation) item, else the label's default.
    #[must_use]
    pub fn title(mut self, title: impl Into<crate::Text>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// The line the default [`render`](Page::render) shows under the title; defaults to none.
    #[must_use]
    pub fn description(mut self, description: impl Into<crate::Text>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Whether the request's user may open the page. The panel answers 403 and leaves the page
    /// out of the sidebar when it answers `false`. Defaults to every signed-in user.
    ///
    /// ```rust
    /// # use tablo_core::{Page, PageDef, auth};
    /// # use topcoat::{Result, context::Cx, view::{View, view}};
    /// # #[derive(Clone)]
    /// # struct Staff { admin: bool }
    /// # impl tablo_core::PanelUser for Staff {
    /// #     fn user_id(&self) -> String { String::new() }
    /// #     fn display_name(&self) -> &str { "" }
    /// #     fn can_access_panel(&self, _panel: &str) -> bool { true }
    /// # }
    /// struct BillingPage;
    ///
    /// impl Page for BillingPage {
    ///     fn declare() -> PageDef {
    ///         PageDef::new().access(|cx| auth::user::<Staff>(cx).is_some_and(|staff| staff.admin))
    ///     }
    ///
    ///     async fn render(cx: &Cx) -> Result<impl View> {
    ///         Ok(view! { tablo_ui::page(tablo_ui::page_title("Billing")) })
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn access(mut self, access: impl Fn(&Cx) -> bool + Send + Sync + 'static) -> Self {
        self.access = Arc::new(access);
        self.access_declared = true;
        self
    }

    /// Adds the [`HeaderAction`] `A` after the ones already declared, served at
    /// `{url}/-/actions/{NAME}`. The default [`render`](Page::render) shows their buttons in the
    /// page's header; a page that renders itself places
    /// [`header_action_buttons`](crate::header_action_buttons). An `A::NAME` that is not a
    /// single URL path segment does not compile.
    ///
    /// The actions run for whoever may open the page: a page has no policy. An action that writes
    /// a resource's records asks that resource's policy in its own
    /// [`can_run`](crate::HeaderAction::can_run).
    #[must_use]
    pub fn header_action<A: HeaderAction>(mut self) -> Self {
        self.header_actions = self.header_actions.add::<A>();
        self
    }

    /// Adds the [`Widget`] `W` after the ones already declared, to the grid the default
    /// [`render`](Page::render) shows under the header; a page that renders itself places
    /// [`widgets`](crate::widgets).
    #[must_use]
    pub fn widget<W: Widget>(mut self) -> Self {
        self.widgets.push::<W>();
        self
    }

    /// Offers `filter` above the widgets, after the filters already declared: a value the page
    /// keeps in its query string, which its widgets read through
    /// [`page_filters`](crate::page_filters). The default [`render`](Page::render) shows the
    /// filters' bar under the header; a page that renders itself places
    /// [`page_filter_bar`](crate::page_filter_bar). Mounting refuses two filters sharing a key,
    /// and a key that is not ASCII letters, digits, `-` and `_`.
    #[must_use]
    pub fn filter(mut self, filter: PageFilter) -> Self {
        self.filters.push(filter);
        self
    }

    /// How many columns the widget grid has on a wide screen, from 1 to 4; defaults to 2. A
    /// medium screen shows at most two, a narrow one one.
    #[must_use]
    pub fn widget_columns(mut self, columns: u8) -> Self {
        self.widgets.set_columns(columns);
        self
    }
}

impl Default for PageDef {
    fn default() -> Self {
        Self {
            slug: None,
            label: None,
            icon: None,
            navigation_order: None,
            navigation_group: None,
            navigation: None,
            navigation_hidden: false,
            title: None,
            description: None,
            access: Arc::new(|_| true),
            access_declared: false,
            header_actions: HeaderActions::new(),
            widgets: WidgetGrid::default(),
            filters: Vec::new(),
        }
    }
}

impl std::fmt::Debug for PageDef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PageDef")
            .field("slug", &self.slug)
            .field("label", &self.label)
            .field("navigation_order", &self.navigation_order)
            .field("navigation_group", &self.navigation_group)
            .field("navigation", &self.navigation)
            .field("navigation_hidden", &self.navigation_hidden)
            .field("title", &self.title)
            .field("description", &self.description)
            .field("header_actions", &self.header_actions)
            .field("widgets", &self.widgets)
            .finish_non_exhaustive()
    }
}

/// A [`PageDef`] with its defaults filled in for the page `P`, as a panel mounted it.
pub(crate) struct MountedPage {
    pub(crate) slug: String,
    /// The sidebar entry, its target not yet resolved to the page's URL.
    pub(crate) navigation: NavigationItem,
    /// Whether the sidebar leaves the page out: [`PageDef::without_navigation`].
    pub(crate) navigation_hidden: bool,
    /// The heading the default [`Page::render`] shows.
    pub(crate) title: crate::Text,
    pub(crate) description: Option<crate::Text>,
    access: Arc<AccessFn>,
    /// Whether the def declared [`PageDef::access`] rather than keep the default.
    pub(crate) access_declared: bool,
    pub(crate) header_actions: HeaderActions,
    pub(crate) widgets: WidgetGrid,
    /// The [`PageDef::filter`]s, in declaration order.
    pub(crate) filters: Vec<PageFilter>,
}

impl MountedPage {
    pub(crate) fn new<P: Page>(def: PageDef) -> Self {
        let stem = type_stem::<P>("Page");
        let noun = sentence_case(stem);
        let label = crate::Text::derived(
            crate::naming::derived_id("page", &crate::naming::slug_case(&noun)),
            noun,
        );
        Self::declared(def, kebab_case(stem), label)
    }

    /// `def` with its defaults filled in: `slug` and `label` where it names none.
    pub(crate) fn declared(def: PageDef, slug: String, label: crate::Text) -> Self {
        let title = def
            .title
            .or_else(|| def.label.clone())
            .or_else(|| def.navigation.as_ref().map(|item| item.label.clone()));
        let label = def.label.unwrap_or(label);
        let title = title.unwrap_or_else(|| label.clone());
        let mut navigation = def.navigation.unwrap_or_else(|| NavigationItem {
            label,
            ..NavigationItem::default()
        });
        if let Some(order) = def.navigation_order {
            navigation.order = order;
        }
        if let Some(icon) = def.icon {
            navigation.icon = Some(icon);
        }
        if let Some(group) = def.navigation_group {
            navigation.group = Some(group);
        }
        Self {
            slug: def.slug.unwrap_or(slug),
            navigation,
            navigation_hidden: def.navigation_hidden,
            title,
            description: def.description,
            access: def.access,
            access_declared: def.access_declared,
            header_actions: def.header_actions,
            widgets: def.widgets,
            filters: def.filters,
        }
    }

    /// Whether the request's user may open the page.
    pub(crate) fn admits(&self, cx: &Cx) -> bool {
        (self.access)(cx)
    }

    /// The page behind `access` in place of its def's: an auth page placed in an area, which
    /// declares none, opens to whom auth offers it.
    pub(crate) fn with_access(
        mut self,
        access: impl Fn(&Cx) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.access = Arc::new(access);
        self
    }

    /// The page's access check, shared with its sidebar entry.
    pub(crate) fn access(&self) -> Arc<AccessFn> {
        Arc::clone(&self.access)
    }
}

/// A page's declaration check, run by
/// [`RouterBuilderPanelExt::panel`](crate::RouterBuilderPanelExt::panel) as a resource's is.
pub(crate) type PageCheck = Box<dyn Fn(&Cx, &mut Vec<crate::DeclarationError>) + Send>;

/// Checks the header actions of `page`, the page `P` as the panel mounted it, as a resource's are,
/// that no two of its widgets share a name, and that its filters' keys are distinct query words.
pub(crate) fn check_page<P: Page>(page: Arc<MountedPage>) -> PageCheck {
    Box::new(move |cx, errors| {
        page.widgets.check::<P>(errors);
        let mut keys = std::collections::HashSet::new();
        for filter in &page.filters {
            if !filter.has_valid_key() || !keys.insert(filter.key()) {
                errors.push(crate::DeclarationError::of::<P>(
                    crate::declaration::Site::Registration,
                    crate::DeclarationErrorKind::MisdeclaredPageFilter {
                        key: filter.key().to_string(),
                    },
                ));
            }
        }
        crate::resource::check_inputs::<P>(
            cx,
            page.header_actions
                .entries()
                .iter()
                .map(|action| (action.name, action.input)),
            errors,
        );
    })
}

pub(crate) mod filters;
#[cfg(test)]
mod tests;