Skip to main content

tablo_core/panel/
widgets.rs

1//! The widget grid of a [`Page`], and the row of [`Stat`] tiles and the [`RecordTable`] a widget
2//! renders.
3
4use std::{any::TypeId, sync::Arc};
5
6use jiff::{SignedDuration, Timestamp};
7use toasty::{
8    Executor,
9    stmt::{List, Path, Query},
10};
11use topcoat::{
12    Result,
13    context::Cx,
14    view::{BoxView, ViewExt, view},
15};
16
17use crate::{
18    Page, RecordTable, Resource, Stat, Trend,
19    navigation::runtime_link,
20    page::MountedPage,
21    panel::list::{TableChrome, declared_chrome, wire_table_over},
22    resource::mounted,
23    table::include_relations,
24    topcoat_compat::async_page,
25    widget::{MountedWidget, Span, WidgetGrid},
26};
27
28/// The widget grid of the page `P`: each [`Widget`](crate::Widget) its
29/// [`PageDef::widget`](crate::PageDef::widget) calls added, in their order, that the request may
30/// see.
31///
32/// It renders nothing outside a request to `P`'s panel, for a request the panel's sign-in or
33/// [`PageDef::access`](crate::PageDef::access) refuses — the check
34/// [`can_open`](crate::can_open) makes — and leaves out each widget whose
35/// [`WidgetDef::access`](crate::WidgetDef::access) refuses the request. The default
36/// [`Page::render`] places it; the [`Page::render`] docs show a page placing it itself.
37pub fn widgets<P: Page>(cx: &Cx) -> BoxView<'_> {
38    match super::pages::mounted_admitted(cx, TypeId::of::<P>()) {
39        Some(page) => page_grid(cx, page),
40        None => ().boxed(),
41    }
42}
43
44/// The widget grid of `page`, which the request may open: each of its widgets the request may
45/// see.
46pub(super) fn page_grid<'a>(cx: &'a Cx, page: &MountedPage) -> BoxView<'a> {
47    let cells = page
48        .widgets
49        .admitted(cx)
50        .map(|widget| (widget, async_page((widget.render)(cx))))
51        .collect();
52    grid(cx, page.widgets.columns, cells)
53}
54
55/// The grid of `widgets` the request may see, each rendered before the grid returns: a list
56/// streams its rows behind a suspense, and a widget rendered lazily beside them would wait for
57/// the connection they hold on a pool of one.
58pub(crate) async fn rendered_grid<'a>(cx: &'a Cx, widgets: &WidgetGrid) -> Result<BoxView<'a>> {
59    let mut cells = Vec::new();
60    for widget in widgets.admitted(cx) {
61        cells.push((widget, (widget.render)(cx).await?));
62    }
63    Ok(grid(cx, widgets.columns, cells))
64}
65
66/// A grid `columns` wide of each widget with its body, each row filled: the last widget of a row
67/// the next one does not fit in grows over the columns left empty.
68fn grid<'a>(cx: &'a Cx, columns: u8, cells: Vec<(&MountedWidget, BoxView<'a>)>) -> BoxView<'a> {
69    let spans = filled(
70        columns,
71        &cells
72            .iter()
73            .map(|(widget, _)| widget.span)
74            .collect::<Vec<_>>(),
75    );
76    let cells: Vec<BoxView<'a>> = cells
77        .into_iter()
78        .zip(spans)
79        .map(|((widget, body), span)| {
80            let name = widget.name.clone();
81            let class = span_class(span, columns);
82            view! { <div data-widget=(name) class=(class)>(body)</div> }.boxed()
83        })
84        .collect();
85    if cells.is_empty() {
86        return ().boxed();
87    }
88    view! {
89        <div data-widgets="" class=(grid_class(columns))>
90            for cell in cells {
91                (cell)
92            }
93        </div>
94    }
95    .boxed()
96}
97
98/// `spans` laid out in rows `columns` wide, as the widest screen lays them, with the last span of
99/// each row that leaves columns empty grown over them: a half-width widget between two full-width
100/// ones takes the whole row rather than leave half of it blank.
101fn filled(columns: u8, spans: &[Span]) -> Vec<Span> {
102    let columns = columns.max(1);
103    let width = |span: Span| match span {
104        Span::Full => columns,
105        Span::Columns(span) => span.clamp(1, columns),
106    };
107    let mut filled = spans.to_vec();
108    let mut used = 0;
109    for index in 0..spans.len() {
110        used += width(spans[index]);
111        let next = spans.get(index + 1).copied().map(width);
112        if next.is_none_or(|next| used + next > columns) {
113            if used < columns {
114                let grown = width(spans[index]) + columns - used;
115                filled[index] = if grown == columns {
116                    Span::Full
117                } else {
118                    Span::Columns(grown)
119                };
120            }
121            used = 0;
122        }
123    }
124    filled
125}
126
127/// The grid's classes: one column on a narrow screen, at most two on a medium one, `columns` on a
128/// wide one.
129const fn grid_class(columns: u8) -> &'static str {
130    match columns {
131        0 | 1 => "grid gap-4",
132        2 => "grid gap-4 md:grid-cols-2",
133        3 => "grid gap-4 md:grid-cols-2 xl:grid-cols-3",
134        _ => "grid gap-4 md:grid-cols-2 xl:grid-cols-4",
135    }
136}
137
138/// A cell's classes for `span` in a grid `columns` wide; Tailwind needs each class spelled whole.
139const fn span_class(span: Span, columns: u8) -> &'static str {
140    let span = match span {
141        Span::Full => return "min-w-0 col-span-full",
142        Span::Columns(span) if span < columns => span,
143        Span::Columns(_) => columns,
144    };
145    match span {
146        0 | 1 => "min-w-0",
147        2 => "min-w-0 md:col-span-2",
148        3 => "min-w-0 md:col-span-2 xl:col-span-3",
149        _ => "min-w-0 md:col-span-2 xl:col-span-4",
150    }
151}
152
153/// A row of [`Stat`] tiles, for a [`Widget`](crate::Widget)'s body: as many to a row as the
154/// widget's width holds, up to three, or four when three would leave one tile alone on the last
155/// row; nothing when there is no tile.
156///
157/// ```rust
158/// # use tablo_core::Stat;
159/// # fn row(cx: &topcoat::context::Cx) -> topcoat::view::BoxView<'_> {
160/// tablo_core::stats(
161///     cx,
162///     [Stat::new("Orders", "1,204"), Stat::new("Refunds", "3")],
163/// )
164/// # }
165/// ```
166pub fn stats(cx: &Cx, stats: impl IntoIterator<Item = Stat>) -> BoxView<'_> {
167    let stats: Vec<Stat> = stats.into_iter().collect();
168    if stats.is_empty() {
169        return ().boxed();
170    }
171    // Two to a row from a phone's width, the odd one out spanning both, until the row fits them.
172    let class = if stats.len() > 3 && stats.len() % 3 == 1 {
173        "grid gap-3 sm:gap-4 @xs:grid-cols-2 @xs:[&>:last-child:nth-child(odd)]:col-span-2 \
174         @4xl:grid-cols-4 @4xl:[&>:last-child:nth-child(odd)]:col-span-1"
175    } else {
176        "grid gap-3 sm:gap-4 @xs:grid-cols-2 @xs:[&>:last-child:nth-child(odd)]:col-span-2 \
177         @3xl:grid-cols-3 @3xl:[&>:last-child:nth-child(odd)]:col-span-1"
178    };
179    let tiles: Vec<BoxView<'_>> = stats.into_iter().map(|stat| tile(cx, stat)).collect();
180    view! {
181        <div data-stats="" class="@container">
182            <div class=(class)>
183                for tile in tiles {
184                    (tile)
185                }
186            </div>
187        </div>
188    }
189    .boxed()
190}
191
192fn tile(cx: &Cx, stat: Stat) -> BoxView<'_> {
193    let Stat {
194        label,
195        value,
196        detail,
197        icon,
198        href,
199        trend,
200        color,
201        chart,
202    } = stat;
203    let detail = detail.map(|detail| detail.localize(cx)).unwrap_or_default();
204    let (detail_icon, detail_icon_label) = match trend {
205        Some(Trend::Up) => (
206            Some(tablo_ui::icons::ARROW_UP),
207            crate::t!(cx, "tablo-stat-trend-up"),
208        ),
209        Some(Trend::Down) => (
210            Some(tablo_ui::icons::ARROW_DOWN),
211            crate::t!(cx, "tablo-stat-trend-down"),
212        ),
213        Some(Trend::Flat) => (
214            Some(tablo_ui::icons::MINUS),
215            crate::t!(cx, "tablo-stat-trend-flat"),
216        ),
217        None => (None, String::new()),
218    };
219    let mut attrs = topcoat::view::attributes! { data-stat="" };
220    if let Some(href) = &href {
221        let mut link = runtime_link(cx, href);
222        link.remove("href");
223        attrs.extend(link);
224    }
225    view! {
226        tablo_ui::stat(
227            label: label.localize(cx),
228            value: value,
229            detail: detail,
230            detail_icon: detail_icon,
231            detail_icon_label: detail_icon_label,
232            accent: color.text_class(),
233            chart: chart,
234            icon: icon,
235            href: href,
236            attrs: attrs
237        )
238    }
239    .boxed()
240}
241
242impl Stat {
243    /// How many records of `R` the request may see, under `R`'s sidebar label and icon, linking to
244    /// its list; `None` when the request may not open that list, so no tile counts records it
245    /// cannot see or links to a list that would answer 403.
246    ///
247    /// The count reads [`scoped_query`](crate::scoped_query): the caller's tenant, `R`'s
248    /// [`query`](crate::ResourceDef::query), and no trashed record.
249    ///
250    /// # Errors
251    ///
252    /// The database's, when the count fails.
253    pub async fn records<R: Resource>(cx: &Cx) -> Result<Option<Self>> {
254        if !super::can_list::<R>(cx) {
255            return Ok(None);
256        }
257        let (Some(item), Some(url)) = (
258            super::navigation_item::<R>(cx),
259            super::url::resource::<R>(cx),
260        ) else {
261            return Ok(None);
262        };
263        let count = crate::db::count(cx, crate::scoped_query::<R>(cx)?).await?;
264        let count = crate::display::NumberFormat::of(cx)
265            .spell(crate::display::Number::Int(count.into()), 0);
266        let mut stat = Self::new(item.label, count).href(url);
267        stat.icon = item.icon;
268        Ok(Some(stat))
269    }
270
271    /// [`records`](Self::records), with a sparkline of how many of those records `created_at`
272    /// dates in each of the last `weeks` weeks, oldest first: the newest week ends now, and each
273    /// spans the seven days before the next.
274    ///
275    /// ```rust,no_run
276    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
277    /// # struct Order { #[key] #[auto] id: uuid::Uuid, created_at: jiff::Timestamp }
278    /// # use tablo_core::Resource;
279    /// # async fn tile<OrderResource: Resource<Model = Order>>(
280    /// #     cx: &topcoat::context::Cx,
281    /// # ) -> topcoat::Result<Option<tablo_core::Stat>> {
282    /// use tablo_core::Stat;
283    ///
284    /// Stat::records_by_week::<OrderResource>(cx, Order::fields().created_at(), 12).await
285    /// # }
286    /// ```
287    ///
288    /// Each week is one count query over the same scoped query, so the tile reads no record
289    /// however many `R` holds.
290    ///
291    /// # Errors
292    ///
293    /// As [`records`](Self::records), and a declaration failure when `weeks` reach past the
294    /// earliest timestamp.
295    pub async fn records_by_week<R: Resource>(
296        cx: &Cx,
297        created_at: Path<R::Model, Timestamp>,
298        weeks: usize,
299    ) -> Result<Option<Self>> {
300        let Some(stat) = Self::records::<R>(cx).await? else {
301            return Ok(None);
302        };
303        let counts = weekly_counts(
304            || crate::scoped_query::<R>(cx),
305            created_at,
306            weeks,
307            Timestamp::now(),
308            &mut crate::db::db(cx)?,
309        )
310        .await?;
311        Ok(Some(stat.chart(counts)))
312    }
313}
314
315/// How many of the records `query` returns `created_at` dates in each of the `weeks` weeks before
316/// `now`, oldest first: one count query a week.
317async fn weekly_counts<M: toasty::schema::Model>(
318    query: impl Fn() -> Result<Query<List<M>>>,
319    created_at: Path<M, Timestamp>,
320    weeks: usize,
321    now: Timestamp,
322    ex: &mut dyn Executor,
323) -> Result<Vec<f64>> {
324    let mut counts = Vec::with_capacity(weeks);
325    for week in (0..weeks).rev() {
326        let (start, end) = (weeks_before(now, week + 1)?, weeks_before(now, week)?);
327        let count = crate::toasty_compat::count(
328            query()?
329                .filter(created_at.clone().ge(start))
330                .filter(created_at.clone().lt(end)),
331            &mut *ex,
332        )
333        .await
334        .map_err(crate::error::unavailable)?;
335        // A week's count is far below 2^53, so the float holds it exactly.
336        counts.push(count as f64);
337    }
338    Ok(counts)
339}
340
341/// The instant `weeks` weeks before `now`.
342fn weeks_before(now: Timestamp, weeks: usize) -> Result<Timestamp> {
343    i64::try_from(weeks)
344        .ok()
345        .and_then(|weeks| weeks.checked_mul(7 * 24))
346        .and_then(|hours| now.checked_sub(SignedDuration::from_hours(hours)).ok())
347        .ok_or_else(|| {
348            crate::error::declaration(format!(
349                "a sparkline {weeks} weeks long reaches past the earliest timestamp"
350            ))
351        })
352}
353
354/// `table` over `R`'s records, for a [`Widget`](crate::Widget)'s body: the rows under `R`'s list
355/// columns, each linking its View and Edit pages as `R`'s policy allows, with a link to the full
356/// list. Two record tables of one resource on a page take distinct headings, which keep their
357/// rows' DOM ids apart. It renders nothing when the request may not open that list, the check
358/// [`can_list`](super::can_list) makes, or may see none of its columns' fields.
359///
360/// The rows are the ones the list would show: [`scoped_query`](crate::scoped_query)'s, the
361/// caller's tenant, `R`'s [`query`](crate::ResourceDef::query) and no trashed record, which
362/// `table`'s [`filter`](RecordTable::filter) narrows. Its columns hide what
363/// [`field_access`](crate::ResourceDef::field_access) hides from the request, on `R` and on the
364/// related records they show, as the list does. It never pages, sorts, searches or writes, so it
365/// adds no route: a record's own page and the list do.
366///
367/// ```rust,ignore
368/// impl Widget for LatestPosts {
369///     fn declare() -> WidgetDef {
370///         WidgetDef::new().access(can_list::<PostResource>)
371///     }
372///
373///     async fn render(cx: &Cx) -> Result<impl View> {
374///         let table = RecordTable::new()
375///             .heading("Latest posts")
376///             .order_by(Post::fields().created_at().desc());
377///         tablo::record_table::<PostResource>(cx, table).await
378///     }
379/// }
380/// ```
381///
382/// # Errors
383///
384/// A [column](RecordTable::column) `R`'s list declares no column for, and the database's,
385/// when the load fails.
386pub async fn record_table<R: Resource>(
387    cx: &Cx,
388    table: RecordTable<R::Model>,
389) -> Result<BoxView<'_>> {
390    let Some(resource) = mounted::<R>(cx).filter(|_| super::can_list::<R>(cx)) else {
391        return Ok(().boxed());
392    };
393    let RecordTable {
394        heading,
395        description,
396        columns,
397        filter,
398        order_by,
399        limit,
400        ..
401    } = table;
402    let shown = resource.table_for(cx);
403    let shown = match &columns {
404        Some(names) => {
405            let declared = resource.table.declared_columns();
406            if let Some(name) = names
407                .iter()
408                .find(|name| !declared.iter().any(|column| column.name() == name.as_str()))
409            {
410                return Err(crate::error::declaration(format!(
411                    "a record table of `{}` names `{name}`, a column its list does not declare",
412                    resource.slug
413                )));
414            }
415            Arc::new(shown.only(names))
416        }
417        None => shown,
418    };
419    if shown.declared_columns().is_empty() {
420        return Ok(().boxed());
421    }
422    let mut query = resource.scoped_query(cx)?;
423    if let Some(filter) = filter {
424        query = query.filter(filter);
425    }
426    for order in order_by {
427        query = query.order_by(order);
428    }
429    let query = include_relations(query.limit(limit), shown.declared_columns());
430    let mut db = crate::db::db(cx)?;
431    let rows = query
432        .exec(&mut db)
433        .await
434        .map_err(crate::error::unavailable)?;
435    shown.restrict_relations(cx, &rows, &mut db).await?;
436    let declared = declared_chrome(cx, &resource);
437    let chrome = TableChrome {
438        delete: false,
439        actions: false,
440        ..declared
441    };
442    let back = topcoat::router::request::uri(cx)
443        .path_and_query()
444        .map_or_else(String::new, ToString::to_string);
445    let heading = heading.map_or_else(
446        || resource.plural_label.localize(cx),
447        |heading| heading.localize(cx),
448    );
449    let mut wired =
450        wire_table_over(cx, &resource, shown, chrome).prefixed(dom_scope(&resource.slug, &heading));
451    // An edit begun here lands back here.
452    if !back.is_empty() {
453        wired = wired.returning_to(back);
454    }
455    let rows = wired.render_records(cx, rows).await?;
456    let description = description.map(|description| description.localize(cx));
457    let list = crate::navigation::runtime_link(cx, &resource.url);
458    let view_all = crate::t!(cx, "tablo-record-table-view-all");
459    let slug = resource.slug.clone();
460    Ok(view! {
461        <section
462            data-record-table=(slug)
463            data-slot="card"
464            class="relative overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-card"
465        >
466            <div
467                class="flex items-start justify-between gap-4 border-b border-rule bg-head px-5 py-3.5"
468                data-slot="card-header"
469            >
470                <div class="flex min-w-0 flex-col gap-1">
471                    <h2 class="tablo-heading text-[0.9375rem] leading-snug">
472                        (heading)
473                    </h2>
474                    if let Some(description) = description {
475                        <p class="text-sm text-muted-foreground">(description)</p>
476                    }
477                </div>
478                <a
479                    (list)
480                    data-record-table-list=""
481                    class="shrink-0 text-sm font-medium text-primary underline-offset-4 hover:underline"
482                >
483                    (view_all)
484                </a>
485            </div>
486            (rows)
487        </section>
488    }
489    .boxed())
490}
491
492/// The scope of a record table's DOM ids: its resource's slug and its heading, spelled in the
493/// characters an id takes.
494fn dom_scope(slug: &str, heading: &str) -> String {
495    let heading: String = heading
496        .chars()
497        .map(|c| {
498            if c.is_ascii_alphanumeric() {
499                c.to_ascii_lowercase()
500            } else {
501                '-'
502            }
503        })
504        .collect();
505    format!("{slug}-{heading}")
506}
507
508#[cfg(test)]
509mod tests;