1use 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
28pub 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
44pub(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
55pub(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
66fn 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
98fn 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
127const 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
138const 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
153pub 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 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 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 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
315async 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 counts.push(count as f64);
337 }
338 Ok(counts)
339}
340
341fn 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
354pub 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 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
492fn 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;