zeyn 0.0.7

Rust web framework for data heavy applications, written by AI agents and reviewed by people
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
//! Catalog components for public pages: [`CardGrid`] (the card view of a DataGrid), [`Rail`] (a
//! horizontal list of cards) and [`SearchBox`] (a search field with suggestions).
//!
//! All three load rows through an action that takes a [`DataQuery`] and returns a [`Page`], the
//! same action a DataGrid uses. Paging, sorting, free text search and permissions run on the
//! server; the browser never chooses a page size, a field or a filter on its own.

use super::layout::Card;
use super::list::ListItem;
use super::widgets::{Badge, screen_href};
use super::{DataSource, dom_id};
use crate::action::{ActionMeta, Cursor, DataQuery, Error, Page, PageRequest, Result, Sort};
use crate::ctx::{BoxFuture, Ctx};
use crate::grid::{FetchFn, Paging, fetch_via};
use crate::i18n::Text;
use crate::model::Model;
use crate::render::{Render, attr, escape};
use crate::screen::{Component, GridSource, LoadedPage, Node, Params, ScreenDef};
use crate::value::Value;
use serde::{Deserialize, Serialize};
use serde_json::{Value as Json, json};

/// Params of a search results screen: the text the user searched for. A screen opened without
/// params (from a menu) gets empty text.
///
/// ```
/// use zeyn::prelude::*;
/// use zeyn::ui::SearchParams;
///
/// #[screen(route = "/search", public)]
/// pub fn results(p: SearchParams) -> Screen {
///     Screen::new("Results").body(zeyn::ui::Alert::info(p.q))
/// }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct SearchParams {
    pub q: String,
}

impl<'de> Deserialize<'de> for SearchParams {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct Raw {
            #[serde(default)]
            q: String,
        }
        Ok(Option::<Raw>::deserialize(d)?
            .map(|r| SearchParams { q: r.q })
            .unwrap_or_default())
    }
}

impl Params for SearchParams {}

/// One card of a [`CardGrid`] or [`Rail`]: an image, a title, an optional subtitle, text,
/// badges and progress bar, and the screen the card opens. Built from a row with
/// [`Card::image`].
///
/// ```
/// use zeyn::prelude::*;
/// let card = Card::image("/img/course-1.jpg", "Intro to baking")
///     .subtitle("Six lessons")
///     .text("12 min left")
///     .corner(Badge::new("New").tone(Tone::Success))
///     .badges([Badge::new("Beginner"), Badge::new("Video")])
///     .progress(0.4, "Watched")
///     .horizontal();
/// ```
pub struct ImageCard {
    image: String,
    title: Text,
    subtitle: Option<Text>,
    text: Option<Text>,
    alt: Text,
    badge: Option<Badge>,
    corner: Option<Badge>,
    badges: Vec<Badge>,
    progress: Option<(f32, Text)>,
    horizontal: bool,
    link: Option<(&'static str, Json)>,
    preview: super::preview::PreviewTarget,
}

impl Card {
    /// A card with an image and a title, for a [`CardGrid`] or [`Rail`]. The image is a path of
    /// the app (`/...`), an `https:` address or a `data:image/` URI; anything else is left out.
    /// Its alternative text is empty, because the title next to it names the card; give
    /// [`ImageCard::alt`] when the image says more than the title.
    pub fn image(image: impl Into<String>, title: impl Into<Text>) -> ImageCard {
        ImageCard {
            image: image.into(),
            title: title.into(),
            subtitle: None,
            text: None,
            alt: Text::from(""),
            badge: None,
            corner: None,
            badges: Vec::new(),
            progress: None,
            horizontal: false,
            link: None,
            preview: None,
        }
    }
}

impl ImageCard {
    /// A line under the title, such as a price.
    pub fn text(mut self, text: impl Into<Text>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Alternative text of the image, when it shows something the title does not say.
    pub fn alt(mut self, alt: impl Into<Text>) -> Self {
        self.alt = alt.into();
        self
    }

    /// A badge on the image, such as "New", at its starting corner.
    pub fn badge(mut self, badge: Badge) -> Self {
        self.badge = Some(badge);
        self
    }

    /// A second line next to the title, such as an author or a category, in a quieter color.
    pub fn subtitle(mut self, subtitle: impl Into<Text>) -> Self {
        self.subtitle = Some(subtitle.into());
        self
    }

    /// A badge over the image at its ending corner (top right, top left in right to left
    /// pages), such as a count or a status.
    pub fn corner(mut self, badge: Badge) -> Self {
        self.corner = Some(badge);
        self
    }

    /// Badges in a row under the text, such as tags. Several calls add to the row.
    pub fn badges(mut self, badges: impl IntoIterator<Item = Badge>) -> Self {
        self.badges.extend(badges);
        self
    }

    /// A thin progress bar along the bottom of the image, such as how much of a course is done.
    /// `fraction` runs from 0 to 1 (values outside are clamped, `NaN` is 0); `label` names it for
    /// screen readers, which also hear the percentage.
    pub fn progress(mut self, fraction: f32, label: impl Into<Text>) -> Self {
        let f = if fraction.is_nan() {
            0.0
        } else {
            fraction.clamp(0.0, 1.0)
        };
        self.progress = Some((f, label.into()));
        self
    }

    /// Lays the card out in a row: a small image at the start and the text beside it, for lists
    /// of compact cards. The card grid or rail gives such cards wider columns.
    pub fn horizontal(mut self) -> Self {
        self.horizontal = true;
        self
    }

    /// The screen the card opens. The whole card is one link, loaded without a page reload. The
    /// link is the screen's canonical address when it has a route (`/items/{slug}`), so search
    /// engines and visitors without JavaScript follow it directly. Params of the wrong type do
    /// not compile.
    pub fn link<S: ScreenDef>(mut self, _screen: S, params: S::Params) -> Self {
        self.link = Some((
            S::META.name,
            serde_json::to_value(params).unwrap_or(Json::Null),
        ));
        self
    }

    /// A preview of `screen` in a panel next to the card: after about half a second of hover
    /// with a mouse, or at once on keyboard focus. The screen loads only then, through the same
    /// access checks as a window, and is kept for the page's life. Escape closes the panel, the
    /// pointer can move onto it, frames and media inside are left out, and touch screens show no
    /// preview (a tap opens the link). Needs [`ImageCard::link`]. Params of the wrong type do not
    /// compile.
    pub fn preview<S: ScreenDef>(mut self, _screen: S, params: S::Params) -> Self {
        self.preview = Some((
            S::META.name,
            serde_json::to_value(params).unwrap_or(Json::Null),
        ));
        self
    }

    fn html(&self, out: &mut String, r: &Render, size: (u32, u32)) {
        let img = if safe_image(&self.image) {
            format!(
                r#"<img class="z-poster-img" src="{}" alt="{}" width="{}" height="{}" loading="lazy" decoding="async" draggable="false">"#,
                escape(&self.image),
                r.text(&self.alt),
                size.0,
                size.1
            )
        } else {
            format!(
                r#"<span class="z-poster-img" style="aspect-ratio:{} / {}"></span>"#,
                size.0, size.1
            )
        };
        let badge = self
            .badge
            .as_ref()
            .map(|b| b.html(r))
            .unwrap_or_default();
        let corner = self
            .corner
            .as_ref()
            .map(|b| format!(r#"<span class="z-poster-corner">{}</span>"#, b.html(r)))
            .unwrap_or_default();
        let progress = self
            .progress
            .as_ref()
            .map(|(f, label)| {
                let pct = (f * 100.0).round() as u32;
                format!(
                    r#"<span class="z-poster-progress" role="progressbar" aria-label="{}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{pct}" aria-valuetext="{pct}%"><span class="z-poster-progress-bar" style="--z-progress:{pct}%"></span></span>"#,
                    r.text(label)
                )
            })
            .unwrap_or_default();
        let line = |t: &Option<Text>, class: &str| {
            t.as_ref()
                .map(|t| format!(r#"<span class="{class}">{}</span>"#, r.text(t)))
                .unwrap_or_default()
        };
        let subtitle = line(&self.subtitle, "z-poster-subtitle");
        let text = line(&self.text, "z-poster-text");
        let badges = if self.badges.is_empty() {
            String::new()
        } else {
            let all: String = self
                .badges
                .iter()
                .map(|b| b.html(r))
                .collect();
            format!(r#"<span class="z-poster-badges">{all}</span>"#)
        };
        let body = format!(
            r#"<span class="z-poster-media">{img}{badge}{corner}{progress}</span><span class="z-poster-body"><span class="z-poster-title">{}</span>{subtitle}{text}{badges}</span>"#,
            r.text(&self.title)
        );
        let class = if self.horizontal {
            "z-poster z-poster-h"
        } else {
            "z-poster"
        };
        match &self.link {
            Some((screen, params)) => out.push_str(&format!(
                r#"<li class="{class}"><a class="z-poster-link" href="{}" data-zeyn-base-href{}>{body}</a></li>"#,
                screen_href(r, screen, params),
                super::preview::preview_attr(&self.preview)
            )),
            None => out.push_str(&format!(
                r#"<li class="{class}"><div class="z-poster-link">{body}</div></li>"#
            )),
        }
    }
}

/// Whether an image address may go in a card or list row: a path of the app, an `https:`
/// address or a `data:image/` URI.
pub(crate) fn safe_image(src: &str) -> bool {
    src.starts_with('/') && !src.starts_with("//")
        || src.starts_with("https://")
        || src.starts_with("data:image/")
}

type CardFn<E> = Box<dyn Fn(&E) -> ImageCard + Send + Sync>;
type ItemFn<E> = Box<dyn Fn(&E) -> ListItem + Send + Sync>;

/// Turns away rows of a model with `#[mask]` fields the user may not reveal. Cards and
/// suggestions are built by app closures that see the raw row, so they could not keep a masked
/// value masked.
pub(crate) fn check_masks<E: Model>(ctx: &Ctx) -> Result<()> {
    if E::fields()
        .iter()
        .any(|f| !crate::privacy::can_unmask(Some(ctx), f))
    {
        Err(Error::Forbidden)
    } else {
        Ok(())
    }
}

/// The card view of a DataGrid: rows of an action shown as cards in a responsive grid, with
/// numbered pages or "load more" paging and an optional sort picker. Paging, sorting and the
/// search text run on the server through the action and its [`DataQuery`]; the server keeps the
/// page size and accepts only the sort orders offered here. Reading needs the action's access,
/// as for a DataGrid.
///
/// Cards are built by a closure that sees the raw row, so a model with `#[mask]` fields is only
/// shown to users who may reveal them; everyone else gets `Forbidden`.
///
/// ```ignore
/// CardGrid::of(search_products)
///     .title(t!("shop.products"))
///     .card(|p: &Product| Card::image(p.image.clone(), p.name.clone()).text(p.price.to_string())
///         .badge(Badge::new(t!("shop.new")).tone(Tone::Success))
///         .link(product_page, ProductParams { id: p.id }))
///     .sort_option(t!("shop.by_name"), Product::name, false)
///     .paging(Paging::infinite(24))
/// ```
pub struct CardGrid<E: Model> {
    action: ActionMeta,
    fetch: FetchFn<E>,
    card: Option<CardFn<E>>,
    item: Option<ItemFn<E>>,
    title: Option<Text>,
    paging: Paging,
    sorts: Vec<(Text, Sort)>,
    search: String,
    image: (u32, u32),
    rail: bool,
    list: bool,
    scrollbar: bool,
}

/// A horizontal list of cards that scrolls sideways, with previous and next buttons and scroll
/// snapping. It loads the next batch when the user scrolls near its end. Built like a
/// [`CardGrid`], which it is, laid out in one row.
///
/// The scrollbar is hidden unless [`CardGrid::scrollbar`] keeps it; touch, trackpad and
/// Shift+wheel still scroll. A mouse can press and drag the rail sideways: after a move of more
/// than 5 pixels the click on release is cancelled, so no card opens, and the rail snaps to the
/// nearest card. Touch keeps the browser's own scrolling. Without JavaScript the buttons are
/// hidden and the rail scrolls natively.
///
/// Keyboard: the cards are links in the tab order and scroll into view as they get focus; the
/// previous and next buttons scroll by a view's width and are disabled at the ends. They are
/// always there, because the hidden scrollbar is no way to scroll for a keyboard.
///
/// ```ignore
/// Rail::of(search_products).title(t!("shop.new_arrivals")).card(|p: &Product| Card::image(p.image.clone(), p.name.clone()))
/// ```
pub struct Rail;

impl Rail {
    /// A rail that loads its cards from the given action, 12 at a time.
    #[allow(clippy::new_ret_no_self)]
    pub fn of<A, E>(source: A) -> CardGrid<E>
    where
        A: crate::action::Action<Input = DataQuery, Output = Result<Page<E>>>,
        E: Model,
    {
        let mut grid = CardGrid::of(source);
        grid.rail = true;
        grid.paging = Paging::infinite(12);
        grid
    }
}

impl<E: Model> CardGrid<E> {
    /// Cards of the rows of the given action, 24 per page with a "load more" button.
    pub fn of<A>(_source: A) -> Self
    where
        A: crate::action::Action<Input = DataQuery, Output = Result<Page<E>>>,
    {
        Self {
            action: A::META,
            fetch: fetch_via::<A, E>,
            card: None,
            item: None,
            title: None,
            paging: Paging::infinite(24),
            sorts: Vec::new(),
            search: String::new(),
            image: (300, 400),
            rail: false,
            list: false,
            scrollbar: false,
        }
    }

    /// Keeps the scrollbar of a [`Rail`] visible (thin). Rails hide it by default; card grids and
    /// lists do not scroll sideways, so it changes nothing for them.
    pub fn scrollbar(mut self, show: bool) -> Self {
        self.scrollbar = show;
        self
    }

    /// Lays the rows out as a [`super::List`]: see [`super::List::of`].
    pub(crate) fn into_list(mut self) -> Self {
        self.list = true;
        self.paging = Paging::infinite(20);
        self
    }

    /// How a row becomes a list row, for a list made with [`super::List::of`]. Card grids and
    /// rails use [`CardGrid::card`] instead.
    pub fn item(mut self, build: impl Fn(&E) -> ListItem + Send + Sync + 'static) -> Self {
        self.item = Some(Box::new(build));
        self
    }

    /// How a row becomes a card.
    pub fn card(mut self, build: impl Fn(&E) -> ImageCard + Send + Sync + 'static) -> Self {
        self.card = Some(Box::new(build));
        self
    }

    /// A heading over the cards, which also names the list for screen readers.
    pub fn title(mut self, title: impl Into<Text>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// `Paging::infinite(n)` (the default, 24) loads `n` more with a button that also fires when
    /// it scrolls into view; `Paging::pages(n)` shows numbered pages with previous and next.
    /// Other kinds of paging work as `infinite`.
    pub fn paging(mut self, paging: Paging) -> Self {
        self.paging = paging;
        self
    }

    /// A sort order users can pick. The first one is the order the cards start in.
    pub fn sort_option<T>(
        mut self,
        label: impl Into<Text>,
        field: crate::model::Field<E, T>,
        desc: bool,
    ) -> Self {
        self.sorts.push((
            label.into(),
            Sort {
                field: field.meta().name.to_string(),
                desc,
            },
        ));
        self
    }

    /// Shows only rows that match this free text ([`DataQuery::q`]), such as the text of a
    /// search results screen.
    pub fn search(mut self, text: impl Into<String>) -> Self {
        self.search = text.into();
        self
    }

    /// Width and height of the card images in pixels, so the page does not jump while they load.
    /// 300 by 400 unless set.
    pub fn image_size(mut self, width: u32, height: u32) -> Self {
        self.image = (width.clamp(1, 4000), height.clamp(1, 4000));
        self
    }

    fn size(&self) -> u32 {
        match self.paging {
            Paging::Pages { size } => size,
            Paging::Infinite { batch } => batch,
            _ => 24,
        }
    }

    fn pages(&self) -> bool {
        matches!(self.paging, Paging::Pages { .. }) && !self.rail
    }

    /// The query the server runs: the client's position and one of the offered sort orders; the
    /// page size and search text come from the server; client filters are dropped.
    fn allow(&self, query: &mut DataQuery) {
        let size = self.size();
        query.page = match &query.page {
            PageRequest::Offset { offset, .. } if self.pages() => PageRequest::Offset {
                offset: *offset,
                limit: size,
            },
            PageRequest::After { cursor, .. } if !self.pages() => PageRequest::After {
                cursor: cursor.clone(),
                limit: size,
            },
            _ if self.pages() => PageRequest::Offset {
                offset: 0,
                limit: size,
            },
            _ => PageRequest::After {
                cursor: None,
                limit: size,
            },
        };
        query
            .sort
            .retain(|s| self.sorts.iter().any(|(_, o)| o == s));
        query.sort.truncate(1);
        if query.sort.is_empty() {
            query.sort.extend(
                self.sorts
                    .first()
                    .map(|(_, s)| s.clone()),
            );
        }
        query.filters.clear();
        query.q = self.search.clone();
        query.with_total = self.pages();
        query.aggregates.clear();
        query.group = None;
    }

    fn cards(&self, page: &LoadedPage, r: &Render) -> String {
        let mut out = String::new();
        let Some(rows) = page.items.downcast_ref::<Vec<E>>() else {
            return out;
        };
        match (&self.card, &self.item) {
            (_, Some(item)) if self.list => rows
                .iter()
                .for_each(|row| item(row).html(&mut out, r)),
            (Some(card), _) if !self.list => rows
                .iter()
                .for_each(|row| card(row).html(&mut out, r, self.image)),
            _ => {}
        }
        out
    }

    fn render_with(&self, out: &mut String, r: &Render, page: Option<&LoadedPage>) {
        let id = dom_id(r, "cards");
        let t = |key: &str| r.text(&Text::key(format!("zeyn.ui.cards.{key}")));
        let class = match (self.rail, self.list) {
            (true, _) if self.scrollbar => "z-rail z-rail-bar",
            (true, _) => "z-rail",
            (_, true) => "z-cards z-cards-rows",
            _ => "z-cards",
        };
        let labelled = if self.title.is_some() {
            format!(r#" aria-labelledby="{id}-title""#)
        } else {
            String::new()
        };
        out.push_str(&format!(
            r#"<section class="{class}" data-zeyn-cards data-zeyn-paging="{}" data-testid="{}.cards"{labelled} data-text-loaded="{}" data-text-page="{}" data-text-error="{}""#,
            if self.pages() { "pages" } else { "infinite" },
            r.scope,
            t("loaded"),
            t("page"),
            t("error"),
        ));
        if let Some(p) = page {
            out.push_str(&format!(
                r#" data-zeyn-offset="{}" data-zeyn-count="{}" data-zeyn-size="{}""#,
                p.offset,
                p.count,
                self.size()
            ));
            if let Some(total) = p.total {
                out.push_str(&format!(r#" data-zeyn-total="{total}""#));
            }
            if let Some(Cursor(next)) = &p.next {
                out.push_str(&format!(r#" data-zeyn-next="{}""#, escape(next)));
            }
        }
        out.push('>');
        let title = self
            .title
            .as_ref()
            .map(|t| {
                format!(
                    r#"<h2 class="z-cards-title" id="{id}-title">{}</h2>"#,
                    r.text(t)
                )
            })
            .unwrap_or_default();
        let sorts = if self.sorts.len() > 1 && !self.rail {
            let options: String = self
                .sorts
                .iter()
                .enumerate()
                .map(|(i, (label, s))| {
                    format!(
                        r#"<option value="{i}" data-sort="{}">{}</option>"#,
                        attr(s),
                        r.text(label)
                    )
                })
                .collect();
            format!(
                r#"<div class="z-cards-sort"><label for="{id}-sort">{}</label><div class="z-select" data-text-none=""><select id="{id}-sort" data-zeyn-cards-sort>{options}</select></div></div>"#,
                t("sort")
            )
        } else {
            String::new()
        };
        if self.rail {
            out.push_str(&format!(
                r#"<div class="z-rail-head">{title}<div class="z-rail-nav"><button type="button" class="z-rail-button" data-zeyn-rail-prev aria-controls="{id}-list" aria-label="{}" aria-disabled="true"><span aria-hidden="true">&#8249;</span></button><button type="button" class="z-rail-button" data-zeyn-rail-next aria-controls="{id}-list" aria-label="{}"><span aria-hidden="true">&#8250;</span></button></div></div>"#,
                t("previous"),
                t("next")
            ));
        } else if !title.is_empty() || !sorts.is_empty() {
            out.push_str(&format!(
                r#"<div class="z-cards-head">{title}{sorts}</div>"#
            ));
        }
        let list = match (self.rail, self.list) {
            (true, _) => "z-rail-list",
            (_, true) => "z-list",
            _ => "z-cards-list",
        };
        out.push_str(&format!(
            r#"<ul class="{list}" id="{id}-list" data-zeyn-rows>"#
        ));
        if let Some(p) = page {
            out.push_str(&self.cards(p, r));
        }
        out.push_str("</ul>");
        let empty = page.is_none_or(|p| p.count == 0);
        out.push_str(&format!(
            r#"<p class="z-cards-empty" data-zeyn-cards-empty{}>{}</p>"#,
            if empty { "" } else { " hidden" },
            t("empty")
        ));
        let more = page.is_some_and(|p| p.next.is_some());
        if self.pages() {
            out.push_str(&format!(
                r#"<nav class="z-cards-pager" aria-label="{}"><button type="button" class="z-button" data-zeyn-cards-prev aria-disabled="true">{}</button><span class="z-cards-page" data-zeyn-cards-page></span><button type="button" class="z-button" data-zeyn-cards-next aria-disabled="{}">{}</button></nav>"#,
                t("pages"),
                t("previous_page"),
                !more,
                t("next_page")
            ));
        } else if !self.rail {
            out.push_str(&format!(
                r#"<div class="z-cards-more"><button type="button" class="z-button" data-zeyn-cards-more{}>{}</button></div>"#,
                if more { "" } else { " hidden" },
                t("load_more")
            ));
        }
        out.push_str(r#"<p class="z-sr-only" role="status" aria-live="polite" data-zeyn-cards-status></p></section>"#);
    }
}

impl<E: Model> GridSource for CardGrid<E> {
    fn action(&self) -> ActionMeta {
        self.action
    }

    fn first_query(&self, _view: Option<&crate::grid::DataGridView>) -> DataQuery {
        let mut query = DataQuery::default();
        self.allow(&mut query);
        query
    }

    fn clean_view(&self, _view: crate::grid::DataGridView) -> crate::grid::DataGridView {
        crate::grid::DataGridView::default()
    }

    fn head_html(&self, _r: &Render, _view: Option<&crate::grid::DataGridView>) -> String {
        String::new()
    }

    fn fetch(&self, ctx: Ctx, mut query: DataQuery) -> BoxFuture<Result<LoadedPage>> {
        self.allow(&mut query);
        query.time_zone = ctx.time_zone();
        let fetch = self.fetch;
        let offset = match &query.page {
            PageRequest::Offset { offset, .. } => *offset,
            PageRequest::After { .. } => 0,
        };
        Box::pin(async move {
            check_masks::<E>(&ctx)?;
            let page = fetch(ctx, query).await?;
            Ok(LoadedPage {
                count: page.items.len(),
                total: page.total,
                next: page.next,
                offset,
                totals: Vec::new(),
                items: Box::new(page.items),
                view: None,
                saved_views: false,
                depth: 0,
                path: Vec::new(),
                groups: None,
                parents: Vec::new(),
            })
        })
    }

    fn rows_html(&self, page: &LoadedPage, r: &Render) -> String {
        self.cards(page, r)
    }

    fn foot_html(&self, _page: &LoadedPage, _r: &Render) -> Option<String> {
        None
    }

    fn render_loaded(&self, out: &mut String, r: &Render, page: &LoadedPage) {
        self.render_with(out, r, Some(page));
    }

    fn tool_schema(&self) -> Json {
        let sorts: Vec<&Sort> = self
            .sorts
            .iter()
            .map(|(_, s)| s)
            .collect();
        json!({
            "type": "object",
            "description": "Cards of rows. The server sets the page size; sort must be one of the offered orders.",
            "properties": {
                "page": {
                    "type": "object",
                    "properties": {
                        "type": { "type": "string", "enum": ["offset", "after"] },
                        "offset": { "type": "integer", "minimum": 0 },
                        "cursor": { "type": ["string", "null"] }
                    }
                },
                "sort": { "type": "array", "items": { "enum": sorts } }
            }
        })
    }

    fn fields(&self) -> &'static [crate::model::FieldMeta] {
        E::fields()
    }
}

impl<E: Model> Component for CardGrid<E> {
    fn render(&self, out: &mut String, r: &Render) {
        self.render_with(out, r, None);
    }

    fn schema(&self) -> Json {
        json!({
            "type": if self.rail { "rail" } else if self.list { "list" } else { "card_grid" },
            "model": E::NAME,
            "action": self.action,
            "title": self.title,
            "paging": self.paging,
            "sorts": self.sorts.iter().map(|(l, s)| json!({ "label": l, "field": s.field, "desc": s.desc })).collect::<Vec<_>>(),
            "search": self.search,
        })
    }

    fn grid(&self) -> Option<&dyn GridSource> {
        Some(self)
    }
}

impl<E: Model> From<CardGrid<E>> for Node {
    fn from(g: CardGrid<E>) -> Self {
        Node::new(g)
    }
}

/// Most suggestions one search box shows.
pub const MAX_SUGGESTIONS: u32 = 20;

type SuggestFn<E> = std::sync::Arc<dyn Fn(&E) -> Option<String> + Send + Sync>;

/// A search field with suggestions (W3C APG combobox with a list box popup). As the user types,
/// it waits `instant` milliseconds, then asks the server for suggestions: the action runs with the
/// text as [`DataQuery::q`] and the suggestion text of each row comes back. Enter, or picking a
/// suggestion, opens the results screen with the text in [`SearchParams`].
///
/// The server cuts the text to [`crate::MAX_SEARCH_QUERY`] characters, sets the number of
/// suggestions itself (8 unless set, at most [`MAX_SUGGESTIONS`]), checks the screen's access,
/// the feature's guards and the action's permission, and counts each call against the write rate
/// limit (`App::write_limit`), like every data source call.
///
/// Keyboard: Down and Up move through the suggestions (Down opens them), Enter searches with the
/// highlighted suggestion or the typed text, Escape closes the suggestions and then clears the
/// field.
///
/// ```ignore
/// SearchBox::of(search_products).instant(150).results(search_results).suggestion(|p: &Product| p.name.clone())
/// ```
pub struct SearchBox<E: Model> {
    action: ActionMeta,
    fetch: FetchFn<E>,
    label: Text,
    delay: u32,
    results: Option<&'static str>,
    limit: u32,
    value: String,
    suggestion: SuggestFn<E>,
}

impl<E: Model> SearchBox<E> {
    pub fn of<A>(_source: A) -> Self
    where
        A: crate::action::Action<Input = DataQuery, Output = Result<Page<E>>>,
    {
        Self {
            action: A::META,
            fetch: fetch_via::<A, E>,
            label: Text::key("zeyn.ui.search.label"),
            delay: 150,
            results: None,
            limit: 8,
            value: String::new(),
            suggestion: std::sync::Arc::new(first_text::<E>),
        }
    }

    /// How long to wait after the last key before asking for suggestions, in milliseconds
    /// (150 unless set, between 50 and 2000).
    pub fn instant(mut self, ms: u32) -> Self {
        self.delay = ms.clamp(50, 2000);
        self
    }

    /// The screen Enter opens with the text. Its params are [`SearchParams`].
    pub fn results<S: ScreenDef<Params = SearchParams>>(mut self, _screen: S) -> Self {
        const {
            assert!(
                S::META.route.is_some(),
                "the results screen of a search box must have a route"
            )
        };
        self.results = Some(S::META.name);
        self
    }

    /// The label of the field, read by screen readers. "Search" unless set.
    pub fn label(mut self, label: impl Into<Text>) -> Self {
        self.label = label.into();
        self
    }

    /// The text the field starts with, such as the search of a results screen.
    pub fn value(mut self, text: impl Into<String>) -> Self {
        self.value = text.into();
        self
    }

    /// How many suggestions to show, at most [`MAX_SUGGESTIONS`].
    pub fn limit(mut self, n: u32) -> Self {
        self.limit = n.clamp(1, MAX_SUGGESTIONS);
        self
    }

    /// The text a row suggests. The row's first unmasked text field unless set.
    pub fn suggestion(mut self, text: impl Fn(&E) -> String + Send + Sync + 'static) -> Self {
        self.suggestion = std::sync::Arc::new(move |row| Some(text(row)));
        self
    }
}

/// The first text field of a row that is neither the key nor masked.
fn first_text<E: Model>(row: &E) -> Option<String> {
    let i = E::fields().iter().position(|f| {
        matches!(f.kind, crate::value::FieldKind::Text) && f.mask.is_none() && !f.key
    })?;
    match row.value_at(i) {
        Some(Value::Text(t)) => Some(t),
        _ => None,
    }
}

impl<E: Model> DataSource for SearchBox<E> {
    fn action(&self) -> ActionMeta {
        self.action
    }

    fn fetch(&self, ctx: Ctx, input: Json) -> BoxFuture<Result<Json>> {
        let text: String = input
            .as_str()
            .unwrap_or_default()
            .trim()
            .chars()
            .take(crate::MAX_SEARCH_QUERY)
            .collect();
        let query = DataQuery {
            page: PageRequest::After {
                cursor: None,
                limit: self.limit,
            },
            q: text.clone(),
            time_zone: ctx.time_zone(),
            ..DataQuery::default()
        };
        let fetch = self.fetch;
        let suggest = self.suggestion.clone();
        let rows = async move {
            if text.is_empty() {
                return Ok(Page::default());
            }
            check_masks::<E>(&ctx)?;
            fetch(ctx, query).await
        };
        Box::pin(async move {
            let page = rows.await?;
            let mut out: Vec<String> = Vec::new();
            for s in page
                .items
                .iter()
                .filter_map(|r| suggest(r))
            {
                if !s.is_empty() && !out.contains(&s) {
                    out.push(s);
                }
            }
            Ok(json!(out))
        })
    }
}

impl<E: Model> Component for SearchBox<E> {
    fn render(&self, out: &mut String, r: &Render) {
        let id = dom_id(r, "search");
        let t = |key: &str| r.text(&Text::key(format!("zeyn.ui.search.{key}")));
        out.push_str(&format!(
            r#"<form class="z-search" role="search" data-zeyn-searchbox data-zeyn-delay="{}" data-zeyn-max="{}"{} data-text-count="{}" data-text-none="{}" data-testid="{}.search"><label class="z-sr-only" for="{id}">{}</label><span class="z-search-field"><span class="z-icon z-icon-search" aria-hidden="true"></span><input id="{id}" type="search" role="combobox" aria-autocomplete="list" aria-expanded="false" aria-controls="{id}-list" autocomplete="off" spellcheck="false" enterkeyhint="search" maxlength="{}" placeholder="{}" value="{}"><ul class="z-search-list" role="listbox" id="{id}-list" aria-label="{}" hidden></ul></span><p class="z-sr-only" role="status" aria-live="polite" data-zeyn-search-status></p></form>"#,
            self.delay,
            crate::MAX_SEARCH_QUERY,
            self.results.map(|s| format!(r#" data-zeyn-results="{s}""#)).unwrap_or_default(),
            t("count"),
            t("none"),
            r.scope,
            r.text(&self.label),
            crate::MAX_SEARCH_QUERY,
            r.text(&self.label),
            escape(&self.value),
            t("suggestions"),
        ));
    }

    fn schema(&self) -> Json {
        json!({ "type": "search_box", "model": E::NAME, "action": self.action, "results": self.results, "label": self.label })
    }

    fn source(&self, key: &str) -> Option<&dyn DataSource> {
        (key == "suggest").then_some(self as &dyn DataSource)
    }
}

impl<E: Model> From<SearchBox<E>> for Node {
    fn from(s: SearchBox<E>) -> Self {
        Node::new(s)
    }
}