zeyn 0.0.8

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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
use crate::action::{Access, ActionMeta, Cursor, DataQuery, Result};
use crate::ctx::{BoxFuture, Ctx, Dep};
use crate::i18n::Text;
use crate::render::{Render, attr, slug};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::json;
use std::any::Any;
use std::collections::HashMap;

/// Screen params. Implemented by `#[params]`; screens without params use `()`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a screen params type",
    label = "the first argument of a screen is its params",
    note = "mark the type with `#[params]`, or use `_: ()` as the first argument when the screen has no params"
)]
pub trait Params: Serialize + DeserializeOwned + Clone + Send + Sync + 'static {}

impl Params for () {}

/// Screen definition generated by `#[screen]`.
#[derive(Clone, Copy, Debug, Serialize)]
pub struct ScreenMeta {
    pub name: &'static str,
    pub route: Option<&'static str>,
    pub access: Access,
    /// Opening the screen is audited as a read, with its params.
    pub sensitive: bool,
    /// The user must give a reason before the screen's data is shown. Implies `sensitive`.
    pub reason: bool,
    /// First paragraph of the screen's `///` doc comment, added to its AI tool descriptions.
    pub doc: &'static str,
    /// AI policy from `ai = "..."` or `ai = false`. A hidden screen offers no tools and models
    /// cannot navigate to it.
    pub ai: crate::action::Ai,
    /// Seconds a shared cache may keep the page of a public screen opened without a session
    /// (`cache = N`, at most [`MAX_SCREEN_CACHE`]); 0 sends no public cache headers.
    pub cache: u32,
    /// `no_prefetch`: the browser never loads the screen ahead of a click (`App::prefetch`); the
    /// server refuses such requests before the screen runs.
    pub no_prefetch: bool,
}

/// Longest `cache = N` a screen may ask for: one day.
pub const MAX_SCREEN_CACHE: u32 = 86_400;

/// A screen. Implemented by `#[screen]`, never written by hand.
pub trait ScreenDef: Copy + Send + Sync + 'static {
    type Params: Params;
    const META: ScreenMeta;

    /// Services the screen needs; checked when the app starts.
    fn deps() -> Vec<Dep>;

    /// Builds the screen with injected arguments. Access is checked by the caller.
    fn build(ctx: Ctx, params: Self::Params) -> BoxFuture<Result<Screen>>;

    /// Reads path segment `field` of the route (`{id}` in `/orders/{id}`) as the JSON value of
    /// that params field, or `None` when it does not parse (the request answers 404). Generated
    /// by `#[screen]` for routes with segments.
    fn path_value(field: &str, raw: &str) -> Option<serde_json::Value> {
        let _ = (field, raw);
        None
    }
}

/// A params field type that can be a path segment of a route, such as `id` in `/orders/{id}`.
/// A segment only parses in the one form the framework writes it in (`7`, not `+7` or `007`),
/// so each record has one address.
///
/// A field whose type cannot be a segment does not compile:
///
/// ```compile_fail
/// use zeyn::prelude::*;
///
/// #[params]
/// pub struct DayParams {
///     pub day: Vec<String>,
/// }
///
/// #[screen(route = "/days/{day}", public)]
/// pub fn day(_p: DayParams) -> Screen {
///     Screen::new("Day")
/// }
/// ```
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be a route path segment",
    label = "this route names a params field of type `{Self}`",
    note = "path segments take integers (`i64`, `u32`, ...), entity keys (`ProductId`), `String` or `zeyn::Slug`; take the field out of the route and it travels in the JSON `params` query instead"
)]
pub trait PathValue: Serialize + Sized {
    /// Parses a decoded segment. `None` answers 404.
    fn from_segment(raw: &str) -> Option<Self>;
}

macro_rules! path_ints {
    ($($t:ty),*) => {$(
        impl PathValue for $t {
            fn from_segment(raw: &str) -> Option<Self> {
                raw.parse::<$t>().ok().filter(|v| v.to_string() == raw)
            }
        }
    )*};
}

path_ints!(i8, i16, i32, i64, u8, u16, u32, u64, usize);

impl PathValue for String {
    fn from_segment(raw: &str) -> Option<Self> {
        (!raw.is_empty() && raw != "." && raw != ".." && raw.len() <= MAX_SEGMENT)
            .then(|| raw.to_string())
    }
}

/// Longest path segment value read or written, in bytes.
pub const MAX_SEGMENT: usize = 256;

#[doc(hidden)]
/// Reads a segment as the type of the params field `field` points to. The closure is never
/// called; it only names the field, so a missing field is a compile error at the route.
pub fn __path_value<P, T: PathValue>(
    raw: &str,
    field: impl Fn(&P) -> &T,
) -> Option<serde_json::Value> {
    let _ = field;
    T::from_segment(raw).and_then(|v| serde_json::to_value(v).ok())
}

/// Names of the path segments of a route: `["slug", "n"]` for `/catalog/{slug}/{n}`.
pub(crate) fn route_segments(route: &str) -> impl Iterator<Item = &str> {
    route.split('/').filter_map(|s| {
        s.strip_prefix('{')
            .and_then(|s| s.strip_suffix('}'))
    })
}

/// Whether a route has path segments. Usable in constant checks.
pub const fn route_has_segments(route: Option<&str>) -> bool {
    let Some(route) = route else { return false };
    let bytes = route.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'{' {
            return true;
        }
        i += 1;
    }
    false
}

/// URL of a screen at `path` (its route with the feature prefix) with these params: path segments
/// filled from the params fields of the same name, the other fields in the JSON `params` query.
/// Fields that are `null` (an empty `Option`) are left out of the query, so the address stays
/// canonical. `None` when a segment's field is missing or not a number or a usable string.
///
/// ```
/// use serde_json::json;
/// use zeyn::screen_url;
/// assert_eq!(screen_url("/orders/{id}", &json!({ "id": 42, "tab": "lines" })).unwrap(), "/orders/42?params=%7B%22tab%22%3A%22lines%22%7D");
/// assert_eq!(screen_url("/orders/{id}", &json!({ "id": 42, "tab": null })).unwrap(), "/orders/42");
/// assert_eq!(screen_url("/catalog/{slug}/{n}", &json!({ "slug": "cay-bardagi", "n": 2 })).unwrap(), "/catalog/cay-bardagi/2");
/// assert_eq!(screen_url("/orders", &json!({ "q": 1 })).unwrap(), "/orders?params=%7B%22q%22%3A1%7D");
/// assert_eq!(screen_url("/orders/{id}", &json!({})), None);
/// ```
pub fn screen_url(path: &str, params: &serde_json::Value) -> Option<String> {
    if !route_has_segments(Some(path)) {
        return Some(if params.is_null() {
            path.to_string()
        } else {
            format!("{path}?params={}", encode(&params.to_string()))
        });
    }
    let fields = params.as_object()?;
    let mut out = String::with_capacity(path.len() + 16);
    for (i, part) in path.split('/').enumerate() {
        if i > 0 {
            out.push('/');
        }
        match part
            .strip_prefix('{')
            .and_then(|p| p.strip_suffix('}'))
        {
            Some(name) => {
                let value = match fields.get(name)? {
                    serde_json::Value::Number(n) => n.to_string(),
                    serde_json::Value::String(s) => String::from_segment(s)?,
                    _ => return None,
                };
                out.push_str(&encode(&value));
            }
            None => out.push_str(part),
        }
    }
    let segments: Vec<&str> = route_segments(path).collect();
    let rest: serde_json::Map<String, serde_json::Value> = fields
        .iter()
        .filter(|(k, v)| !v.is_null() && !segments.contains(&k.as_str()))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    if !rest.is_empty() {
        out.push_str("?params=");
        out.push_str(&encode(&serde_json::Value::Object(rest).to_string()));
    }
    Some(out)
}

/// Full paths (feature prefix, no base path) of the routed screens of a running app, so links
/// rendered for a request use the path form. Kept by the server as a service on every request.
#[derive(Clone, Default)]
pub(crate) struct Routes(
    pub(crate) std::sync::Arc<HashMap<&'static str, String>>,
    /// The default language when the app keeps the language in the URL (`App::locale_paths`):
    /// links in another language get its segment in front, so they stay in that language.
    pub(crate) Option<std::sync::Arc<str>>,
);

impl crate::ctx::Service for Routes {}

impl Routes {
    /// App path of `screen` with `params`, without the base path; see [`screen_url`].
    pub(crate) fn href(r: &Render, screen: &str, params: &serde_json::Value) -> Option<String> {
        let ctx = r.ctx?;
        let routes = ctx.service::<Routes>()?;
        let url = screen_url(routes.0.get(screen)?, params)?;
        Some(match routes.1.as_deref() {
            Some(default) if ctx.locale() != default && url == "/" => format!("/{}/", ctx.locale()),
            Some(default) if ctx.locale() != default => format!("/{}{url}", ctx.locale()),
            _ => url,
        })
    }
}

/// Percent encodes a path segment or query value. Dots are encoded too, so a segment never looks
/// like a file name to the browser runtime.
fn encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'~' => out.push(b as char),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// What the client does after a user interaction.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "effect", rename_all = "snake_case")]
pub enum Effect {
    OpenWindow {
        screen: &'static str,
        params: serde_json::Value,
    },
    Navigate {
        screen: &'static str,
        params: serde_json::Value,
    },
    Toast {
        message: Text,
    },
    CloseAndRefresh,
    /// Asks the user to confirm `message`, then runs `then`. Built with [`Effect::confirm`].
    Confirm {
        message: Text,
        then: Box<Effect>,
    },
    /// A toast with a tone and an optional action button. Built with [`Toast`] and
    /// [`UiCtx::notify`]. Danger toasts are announced at once (assertive), the others politely.
    Notice {
        message: Text,
        tone: crate::grid::Tone,
        action: Option<(Text, Box<Effect>)>,
    },
    /// Goes to a local path of the app. With `frame` the whole app frame (menu, title, session
    /// settings) is loaded again, as after signing in or out; still without a page load.
    Go {
        url: String,
        frame: bool,
    },
}

impl Effect {
    /// Goes to a local path of the app (see [`Effect::Go`]). Anything that is not a local path
    /// goes to the start page, so a `return_to` from a request can never leave the app.
    ///
    /// ```
    /// use zeyn::Effect;
    /// assert_eq!(Effect::go("/orders?x=1", false), Effect::Go { url: "/orders?x=1".into(), frame: false });
    /// assert_eq!(Effect::go("//evil.example", true), Effect::Go { url: "/".into(), frame: true });
    /// ```
    pub fn go(url: &str, frame: bool) -> Effect {
        let local = url.starts_with('/')
            && !url.starts_with("//")
            && !url.contains('\\')
            && !url.chars().any(char::is_control)
            && url.len() <= 2048;
        Effect::Go {
            url: if local { url.to_string() } else { "/".into() },
            frame,
        }
    }

    /// Runs `then` only after the user confirms `message` in a dialog.
    ///
    /// ```
    /// use zeyn::Effect;
    /// let e = Effect::confirm("Close without saving?", Effect::CloseAndRefresh);
    /// assert!(matches!(e, Effect::Confirm { .. }));
    /// ```
    pub fn confirm(message: impl Into<Text>, then: Effect) -> Effect {
        Effect::Confirm {
            message: message.into(),
            then: Box::new(then),
        }
    }

    /// Goes to a screen in place, like a link. Params of the wrong type do not compile.
    pub fn navigate<S: ScreenDef>(_screen: S, params: S::Params) -> Effect {
        Effect::Navigate {
            screen: S::META.name,
            params: params_json(&params),
        }
    }

    /// JSON sent to the client, with texts resolved in the user's language.
    pub fn to_json(&self, r: &Render) -> serde_json::Value {
        match self {
            Effect::Toast { message } => {
                json!({ "effect": "toast", "message": r.i18n.text(r.locale, message) })
            }
            Effect::Notice {
                message,
                tone,
                action,
            } => {
                let mut j = json!({ "effect": "toast", "message": r.i18n.text(r.locale, message), "tone": tone });
                if let Some((label, then)) = action {
                    j["action"] =
                        json!({ "label": r.i18n.text(r.locale, label), "effect": then.to_json(r) });
                }
                j
            }
            Effect::Confirm { message, then } => json!({
                "effect": "confirm",
                "message": r.i18n.text(r.locale, message),
                "title": r.i18n.text(r.locale, &Text::key("zeyn.ui.confirm.title")),
                "ok": r.i18n.text(r.locale, &Text::key("zeyn.ui.confirm.ok")),
                "cancel": r.i18n.text(r.locale, &Text::key("zeyn.ui.confirm.cancel")),
                "then": then.to_json(r),
            }),
            other => serde_json::to_value(other).unwrap_or(serde_json::Value::Null),
        }
    }
}

/// Serializes params. Cannot fail for types marked with `#[params]`.
fn params_json<P: Params>(params: &P) -> serde_json::Value {
    serde_json::to_value(params).expect("screen params must serialize to JSON")
}

/// Most toasts the runtime shows at once; older ones make room for new ones.
pub const MAX_TOASTS: usize = 3;

/// A toast with a tone and an optional action button, for [`UiCtx::notify`].
///
/// ```
/// use zeyn::{Effect, Toast};
/// let e: Effect = Toast::success("Order saved").action("Undo", Effect::CloseAndRefresh).into();
/// assert!(matches!(e, Effect::Notice { .. }));
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Toast {
    message: Text,
    tone: crate::grid::Tone,
    action: Option<(Text, Box<Effect>)>,
}

impl Toast {
    fn of(tone: crate::grid::Tone, message: impl Into<Text>) -> Self {
        Toast {
            message: message.into(),
            tone,
            action: None,
        }
    }

    pub fn info(message: impl Into<Text>) -> Self {
        Self::of(crate::grid::Tone::Info, message)
    }

    pub fn success(message: impl Into<Text>) -> Self {
        Self::of(crate::grid::Tone::Success, message)
    }

    pub fn warning(message: impl Into<Text>) -> Self {
        Self::of(crate::grid::Tone::Warning, message)
    }

    /// An error or a loss the user must notice: announced at once and shown twice as long.
    pub fn danger(message: impl Into<Text>) -> Self {
        Self::of(crate::grid::Tone::Danger, message)
    }

    /// A button on the toast that runs `effect`, such as undo or opening the saved record. The
    /// toast stays while it is hovered or holds focus, so the button can be reached.
    pub fn action(mut self, label: impl Into<Text>, effect: Effect) -> Self {
        self.action = Some((label.into(), Box::new(effect)));
        self
    }
}

impl From<Toast> for Effect {
    fn from(t: Toast) -> Self {
        Effect::Notice {
            message: t.message,
            tone: t.tone,
            action: t.action,
        }
    }
}

/// Window helpers.
pub struct Window;

impl Window {
    /// Effect that opens a screen as a window. Params of the wrong type do not compile.
    pub fn open<S: ScreenDef>(_screen: S, params: S::Params) -> Effect {
        Effect::OpenWindow {
            screen: S::META.name,
            params: params_json(&params),
        }
    }
}

/// Context given to event handlers. Collects the effects they ask for.
#[derive(Debug, Default)]
pub struct UiCtx {
    effects: Vec<Effect>,
}

impl UiCtx {
    pub fn toast(&mut self, message: impl Into<Text>) {
        self.effects.push(Effect::Toast {
            message: message.into(),
        });
    }

    /// A toast with a tone and maybe an action button: `ui.notify(Toast::success(t!("saved")))`.
    pub fn notify(&mut self, toast: Toast) {
        self.effects.push(toast.into());
    }

    /// Closes the window and refreshes the screen that opened it.
    pub fn close_and_refresh(&mut self) {
        self.effects
            .push(Effect::CloseAndRefresh);
    }

    pub fn navigate<S: ScreenDef>(&mut self, _screen: S, params: S::Params) {
        self.effects.push(Effect::Navigate {
            screen: S::META.name,
            params: params_json(&params),
        });
    }

    /// Any effect, such as `Effect::confirm(...)`.
    pub fn effect(&mut self, effect: Effect) {
        self.effects.push(effect);
    }

    pub fn into_effects(self) -> Vec<Effect> {
        self.effects
    }
}

/// One loaded page of grid rows, type erased.
pub struct LoadedPage {
    pub items: Box<dyn Any + Send + Sync>,
    pub count: usize,
    pub total: Option<u64>,
    pub next: Option<Cursor>,
    pub offset: u64,
    /// Column totals over the whole filtered result.
    pub totals: Vec<crate::action::Total>,
    /// Column layout the rows are rendered in; `None` is the grid's own layout.
    pub view: Option<crate::grid::DataGridView>,
    /// Whether the user's view changes are saved on the server.
    pub saved_views: bool,
    /// How deep these rows sit in a grouped or tree grid; 0 at the top.
    pub depth: usize,
    /// Group values or ancestor keys leading to these rows, in the fixed machine form.
    pub path: Vec<Option<String>>,
    /// Groups instead of rows, when the grid groups at this depth.
    pub groups: Option<Vec<crate::action::Group>>,
    /// Keys of the rows that have children, in a tree grid.
    pub parents: Vec<String>,
}

/// An action call built on the server for one row or menu item, ready to run.
pub struct RowCall {
    pub meta: ActionMeta,
    pub run: Box<dyn FnOnce(Ctx) -> BoxFuture<Result<()>> + Send>,
}

/// A component that loads rows through an action. Implemented by `DataGrid`.
pub trait GridSource: Send + Sync {
    fn action(&self) -> ActionMeta;

    /// Query for the first page, as the grid's paging asks for it, with the sort and filters of
    /// a saved view.
    fn first_query(&self, view: Option<&crate::grid::DataGridView>) -> DataQuery;

    /// Cleans a view sent by a client so only the grid's own columns, sort keys and filters remain.
    fn clean_view(&self, view: crate::grid::DataGridView) -> crate::grid::DataGridView;

    /// Header row for a view.
    fn head_html(&self, r: &Render, view: Option<&crate::grid::DataGridView>) -> String;

    fn fetch(&self, ctx: Ctx, query: DataQuery) -> BoxFuture<Result<LoadedPage>>;

    /// Loads rows as the user sees them: in a grouped or tree grid, the groups or rows under
    /// `path` (group values or ancestor keys from the client, checked here). Flat grids ignore
    /// `path`. Exports and bulk actions use [`GridSource::fetch`], which never groups.
    fn fetch_at(
        &self,
        ctx: Ctx,
        query: DataQuery,
        path: Vec<Option<String>>,
    ) -> BoxFuture<Result<LoadedPage>> {
        let _ = path;
        self.fetch(ctx, query)
    }

    /// Rows of a loaded page as HTML.
    fn rows_html(&self, page: &LoadedPage, r: &Render) -> String;

    /// Footer row with the totals of a loaded page, or `None` when the grid has no totals or the
    /// page carries none (the client keeps the footer it has).
    fn foot_html(&self, page: &LoadedPage, r: &Render) -> Option<String>;

    /// Renders the grid with its first page already in place.
    fn render_loaded(&self, out: &mut String, r: &Render, page: &LoadedPage);

    /// JSON Schema of the query, for agent tools.
    fn tool_schema(&self) -> serde_json::Value;

    /// Loads the row with this key through the grid's own action. The result holds at most the
    /// rows the action returned for a key filter; [`GridSource::row_call`] picks the matching one.
    fn find_row(&self, ctx: Ctx, key: String) -> BoxFuture<Result<LoadedPage>> {
        let _ = (ctx, key);
        Box::pin(async { Err(crate::action::Error::NotFound) })
    }

    /// Call of bulk action `index` with these keys; `None` when there is no such action or a key
    /// does not read as the key type.
    fn bulk_call(&self, index: usize, keys: Vec<serde_json::Value>) -> Option<RowCall> {
        let _ = (index, keys);
        None
    }

    /// Access rule of bulk action `index`.
    fn bulk_meta(&self, index: usize) -> Option<ActionMeta> {
        let _ = index;
        None
    }

    /// A row key from the client as JSON of the key's type; `None` when it cannot be read.
    fn key_json(&self, key: &str) -> Option<serde_json::Value> {
        let _ = key;
        None
    }

    /// Keys of the rows of a loaded page, in order.
    fn page_keys(&self, page: &LoadedPage) -> Vec<serde_json::Value> {
        let _ = page;
        Vec::new()
    }

    /// Builds the save of an inline edit of the row with this key from the loaded page: only
    /// editable columns and the row version may be in `values`, otherwise `Forbidden`; values are
    /// read and validated as a form would (`Validation` errors name the fields).
    fn edit_call(
        &self,
        page: &LoadedPage,
        key: &str,
        values: &serde_json::Map<String, serde_json::Value>,
        locale: &str,
        tz: crate::time::TimeZone,
    ) -> Result<RowCall> {
        let _ = (page, key, values, locale, tz);
        Err(crate::action::Error::NotFound)
    }

    /// The row with this key from a loaded page as HTML, in the page's view.
    fn row_html(&self, page: &LoadedPage, key: &str, r: &Render) -> Option<String> {
        let _ = (page, key, r);
        None
    }

    /// Who may export the whole filtered result; `None` when the grid offers no export.
    fn export_access(&self) -> Option<crate::action::Access> {
        None
    }

    /// Most rows one export may hold.
    fn export_limit(&self) -> usize {
        0
    }

    /// Header line of a CSV export in a view, with the user's labels.
    fn csv_head(&self, r: &Render, view: Option<&crate::grid::DataGridView>) -> String {
        let _ = (r, view);
        String::new()
    }

    /// CSV lines of a loaded page in its view: values as the user reads them, in the user's
    /// language, with spreadsheet formulas defused.
    fn csv_rows(&self, page: &LoadedPage, r: &Render) -> String {
        let _ = (page, r);
        String::new()
    }

    /// Columns of a typed export (XLSX) in a view: labels in the user's language and widths.
    fn export_columns(
        &self,
        r: &Render,
        view: Option<&crate::grid::DataGridView>,
    ) -> Vec<crate::grid::ExportColumn> {
        let _ = (r, view);
        Vec::new()
    }

    /// Typed values of a loaded page in its view, one row per item: choices as the user's labels
    /// and exact moments as wall clock time in the user's time zone. Everything else keeps its type.
    fn export_values(&self, page: &LoadedPage, r: &Render) -> Vec<Vec<crate::value::Value>> {
        let _ = (page, r);
        Vec::new()
    }

    /// Cells of a loaded page in its view as the user reads them, for printed exports (PDF).
    fn export_text(&self, page: &LoadedPage, r: &Render) -> Vec<Vec<String>> {
        let _ = (page, r);
        Vec::new()
    }

    /// Builds the call of a row item (`a0` for the first row action) from the loaded row with
    /// this key. `None` when the row is not there or the item does not exist for it.
    fn row_call(&self, page: &LoadedPage, key: &str, item: &str) -> Option<RowCall> {
        let _ = (page, key, item);
        None
    }

    /// Fields of the row model. Used to keep searches off masked fields.
    fn fields(&self) -> &'static [crate::model::FieldMeta] {
        &[]
    }

    /// Name of the row model when it is `#[sensitive]`, so exports are audited.
    fn sensitive_model(&self) -> Option<&'static str> {
        None
    }

    /// The raw value of a masked field of the row with this key, for an audited reveal.
    fn reveal(
        &self,
        _ctx: Ctx,
        _key: String,
        _field: String,
    ) -> BoxFuture<Result<Option<crate::privacy::Revealed>>> {
        Box::pin(async { Ok(None) })
    }
}

/// A component that saves data through an action. Implemented by forms with `submit`.
pub trait FormSource: Send + Sync {
    fn action(&self) -> ActionMeta;

    /// Parses submitted values, validates and runs the action. `values` holds what the user typed.
    fn submit(
        &self,
        ctx: Ctx,
        values: serde_json::Map<String, serde_json::Value>,
    ) -> BoxFuture<Result<Vec<Effect>>>;

    /// JSON Schema of the values, for agent tools.
    fn tool_schema(&self) -> serde_json::Value;
}

/// Anything that can be placed on a screen. This is the extension point for third party components.
///
/// A component writes its own HTML and describes itself in the schema. It must escape user data
/// with [`crate::render::escape`] (or [`Render::text`] and [`Render::value`]) and give interactive
/// parts a `data-testid` that starts with `r.scope`.
pub trait Component: Send + Sync {
    fn render(&self, out: &mut String, r: &Render);

    /// Schema used by MCP tools and test generation. Include a `"type"` key.
    fn schema(&self) -> serde_json::Value;

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

    fn form(&self) -> Option<&dyn FormSource> {
        None
    }

    /// The raw value of a masked field this component shows, for an audited reveal. The server
    /// checks the unmask permission before sending it.
    fn reveal(&self, _field: &str) -> Option<crate::privacy::Revealed> {
        None
    }

    /// CSV import, for components that import rows (see [`crate::Import`]).
    fn import(&self) -> Option<&dyn crate::import::ImportSource> {
        None
    }

    /// A PDF document, for components that download one (see [`crate::PdfLink`]).
    #[cfg(feature = "pdf")]
    fn pdf(&self) -> Option<&dyn crate::pdf::PdfSource> {
        None
    }

    /// Nodes held by a container. Child `i` of the node at path `p` has the path `p.i`.
    fn children(&self) -> &[Node] {
        &[]
    }

    /// Children rendered with the page. Others, such as closed lazy tabs, load when first shown.
    fn eager_children(&self) -> &[Node] {
        self.children()
    }

    /// Data the component fetches through an action, by key (a field name for lookups).
    fn source(&self, _key: &str) -> Option<&dyn crate::ui::DataSource> {
        None
    }

    /// Keyboard shortcuts of the component's own links, as declared, for the clash checks of
    /// `App::check` and `App::check_page`.
    fn shortcuts(&self) -> Vec<&str> {
        Vec::new()
    }
}

/// Type erased component: a node of the screen tree.
pub struct Node(Box<dyn Component>);

impl Node {
    pub fn new(component: impl Component + 'static) -> Self {
        Self(Box::new(component))
    }

    pub fn render(&self, out: &mut String, r: &Render) {
        self.0.render(out, r);
    }

    pub fn schema(&self) -> serde_json::Value {
        self.0.schema()
    }

    pub fn grid(&self) -> Option<&dyn GridSource> {
        self.0.grid()
    }

    pub fn form(&self) -> Option<&dyn FormSource> {
        self.0.form()
    }

    pub fn reveal(&self, field: &str) -> Option<crate::privacy::Revealed> {
        self.0.reveal(field)
    }

    pub fn import(&self) -> Option<&dyn crate::import::ImportSource> {
        self.0.import()
    }

    #[cfg(feature = "pdf")]
    pub fn pdf(&self) -> Option<&dyn crate::pdf::PdfSource> {
        self.0.pdf()
    }

    pub fn children(&self) -> &[Node] {
        self.0.children()
    }

    pub fn eager_children(&self) -> &[Node] {
        self.0.eager_children()
    }

    pub fn source(&self, key: &str) -> Option<&dyn crate::ui::DataSource> {
        self.0.source(key)
    }

    pub fn shortcuts(&self) -> Vec<&str> {
        self.0.shortcuts()
    }

    /// Link shortcuts of this node and every node below it, lazy ones included, with the path
    /// of the node that declares each.
    pub(crate) fn all_shortcuts<'a>(&'a self, path: String, out: &mut Vec<(String, &'a str)>) {
        for keys in self.shortcuts() {
            out.push((path.clone(), keys));
        }
        for (i, child) in self.children().iter().enumerate() {
            child.all_shortcuts(format!("{path}.{i}"), out);
        }
    }
}

/// Plain text where a node is expected, escaped and in the user's language, so a slot that takes
/// any inline component, such as [`crate::ui::ListItem::meta`], also takes text.
struct TextNode(Text);

impl Component for TextNode {
    fn render(&self, out: &mut String, r: &Render) {
        out.push_str(&r.text(&self.0));
    }

    fn schema(&self) -> serde_json::Value {
        json!({ "type": "text", "text": self.0 })
    }
}

impl From<Text> for Node {
    fn from(text: Text) -> Self {
        Node::new(TextNode(text))
    }
}

impl From<&'static str> for Node {
    fn from(text: &'static str) -> Self {
        Node::new(TextNode(text.into()))
    }
}

impl From<String> for Node {
    fn from(text: String) -> Self {
        Node::new(TextNode(text.into()))
    }
}

/// Icons.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Icon {
    Plus,
    Edit,
    Delete,
    Save,
    Search,
    Box,
    Cart,
    Table,
    Home,
    Chart,
}

impl Icon {
    fn css(self) -> &'static str {
        match self {
            Icon::Plus => "plus",
            Icon::Edit => "edit",
            Icon::Delete => "delete",
            Icon::Save => "save",
            Icon::Search => "search",
            Icon::Box => "box",
            Icon::Cart => "cart",
            Icon::Table => "table",
            Icon::Home => "home",
            Icon::Chart => "chart",
        }
    }

    /// Icon markup, hidden from screen readers.
    pub fn html(self) -> String {
        format!(
            r#"<span class="z-icon z-icon-{}" aria-hidden="true"></span>"#,
            self.css()
        )
    }
}

/// Export format.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Export {
    Xlsx,
    Csv,
    /// A list report, with the `pdf` Cargo feature.
    Pdf,
}

impl Export {
    fn code(self) -> &'static str {
        match self {
            Export::Xlsx => "xlsx",
            Export::Csv => "csv",
            Export::Pdf => "pdf",
        }
    }
}

#[derive(Debug)]
struct ButtonSpec {
    label: Text,
    icon: Option<Icon>,
    shortcut: Option<String>,
    override_browser: bool,
    effect: Option<Effect>,
    tip: Option<Text>,
}

#[derive(Debug)]
#[allow(
    clippy::large_enum_variant,
    reason = "nearly every entry of the list is the large variant, so boxing it would add an allocation per entry and save no memory"
)]
enum ToolItem {
    Button(ButtonSpec),
    Export(Export),
}

/// Screen toolbar.
#[derive(Debug, Default)]
pub struct Toolbar {
    items: Vec<ToolItem>,
}

impl Toolbar {
    pub fn button(self, label: impl Into<Text>) -> ToolButton {
        ToolButton {
            bar: self,
            spec: ButtonSpec {
                label: label.into(),
                icon: None,
                shortcut: None,
                override_browser: false,
                effect: None,
                tip: None,
            },
        }
    }

    /// Export button for the grid on this screen.
    pub fn export(mut self, format: Export) -> Toolbar {
        self.items
            .push(ToolItem::Export(format));
        self
    }

    pub(crate) fn render(&self, out: &mut String, r: &Render, title: &str) {
        let scope = r.scope;
        out.push_str(&format!(
            r#"<div class="z-toolbar" role="toolbar" aria-label="{title}">"#
        ));
        for (n, item) in self.items.iter().enumerate() {
            match item {
                ToolItem::Button(b) => {
                    let tip = b.tip.as_ref().map(|t| crate::ui::tip(r, &format!("{scope}-tooltip-{n}"), t));
                    if tip.is_some() {
                        out.push_str(r#"<span class="z-tip-host">"#);
                    }
                    let english = b.label.english();
                    out.push_str(&format!(
                        r#"<button type="button" class="z-button" data-testid="{scope}.toolbar.{}""#,
                        slug(&english)
                    ));
                    if let Some(keys) = b.shortcut.as_deref().and_then(|s| crate::command::usable_shortcut(s, b.override_browser)) {
                        out.push_str(&format!(r#" aria-keyshortcuts="{}""#, crate::render::escape(&keys)));
                    }
                    if let Some(e) = &b.effect {
                        out.push_str(&format!(r#" data-zeyn-effect="{}""#, attr(e)));
                    }
                    if let Some((attrs, _)) = &tip {
                        out.push_str(attrs);
                    }
                    out.push('>');
                    if let Some(i) = b.icon {
                        out.push_str(&i.html());
                    }
                    out.push_str(&r.text(&b.label));
                    out.push_str("</button>");
                    if let Some((_, html)) = &tip {
                        out.push_str(html);
                        out.push_str("</span>");
                    }
                }
                ToolItem::Export(e) => out.push_str(&format!(
                    r#"<button type="button" class="z-button" data-testid="{scope}.toolbar.export-{code}" data-zeyn-export="{code}">{}</button>"#,
                    r.text(&Text::key(format!("zeyn.export.{}", e.code()))),
                    code = e.code()
                )),
            }
        }
        out.push_str("</div>");
    }

    pub(crate) fn schema(&self) -> serde_json::Value {
        self.items
            .iter()
            .map(|item| match item {
                ToolItem::Button(b) => json!({
                    "type": "button",
                    "label": b.label,
                    "icon": b.icon,
                    "shortcut": b.shortcut,
                    "effect": b.effect,
                }),
                ToolItem::Export(e) => json!({ "type": "export", "format": e }),
            })
            .collect()
    }
}

/// Toolbar button being configured.
pub struct ToolButton {
    bar: Toolbar,
    spec: ButtonSpec,
}

impl ToolButton {
    pub fn icon(mut self, icon: Icon) -> Self {
        self.spec.icon = Some(icon);
        self
    }

    /// Keyboard shortcut such as `"Alt+N"`. Shortcuts the browser uses (`Ctrl+P`, `Ctrl+S`,
    /// `F5`, ...) are not bound unless the button calls [`ToolButton::override_browser`]; ones the
    /// browser never passes on (`Ctrl+N`, `Ctrl+T`, `Ctrl+W`) are never bound. Both are logged.
    pub fn shortcut(mut self, keys: impl Into<String>) -> Self {
        self.spec.shortcut = Some(keys.into());
        self
    }

    /// Takes over a shortcut the browser uses, on purpose.
    pub fn override_browser(mut self) -> Self {
        self.spec.override_browser = true;
        self
    }

    /// A tooltip for the button: shown on hover, focus and long press, read as its description.
    pub fn tip(mut self, text: impl Into<Text>) -> Self {
        self.spec.tip = Some(text.into());
        self
    }

    /// Opens the screen as a window when the button is pressed.
    pub fn opens<S: ScreenDef>(mut self, screen: S, params: S::Params) -> Self {
        self.spec.effect = Some(Window::open(screen, params));
        self
    }

    pub fn button(self, label: impl Into<Text>) -> ToolButton {
        self.finish().button(label)
    }

    pub fn export(self, format: Export) -> Toolbar {
        self.finish().export(format)
    }

    fn finish(mut self) -> Toolbar {
        self.bar
            .items
            .push(ToolItem::Button(self.spec));
        self.bar
    }
}

impl From<ToolButton> for Toolbar {
    fn from(b: ToolButton) -> Self {
        b.finish()
    }
}

#[derive(Clone, Copy, Debug)]
enum ScreenKind {
    Page,
    Window { width: u32 },
}

/// Content of a screen. Screen functions return this.
pub struct Screen {
    title: Text,
    kind: ScreenKind,
    toolbar: Option<Toolbar>,
    body: Vec<Node>,
    menu: Option<crate::menu::ContextMenu>,
    moved: Option<(&'static str, serde_json::Value, bool)>,
    head: Option<Box<crate::seo::Head>>,
}

impl Screen {
    /// Full page screen.
    pub fn new(title: impl Into<Text>) -> Self {
        Self {
            title: title.into(),
            kind: ScreenKind::Page,
            toolbar: None,
            body: Vec::new(),
            menu: None,
            moved: None,
            head: None,
        }
    }

    /// Answers that this page lives at another screen's address now: the browser gets a permanent
    /// redirect (301) there, such as from an old slug to the current one. Params of the wrong type
    /// do not compile. To answer that nothing is there, return `Err(Error::NotFound)` instead.
    ///
    /// ```ignore
    /// if p.slug != product.slug {
    ///     return Ok(Screen::moved_to(product_page, ProductParams { slug: product.slug, n: p.n }));
    /// }
    /// ```
    pub fn moved_to<S: ScreenDef>(_screen: S, params: S::Params) -> Self {
        Self {
            moved: Some((S::META.name, params_json(&params), true)),
            ..Self::new("")
        }
    }

    /// Sends the browser on to another screen for this one request, such as a random pick or the
    /// newest item: `303 See Other` to the target's canonical path, never cached. In app
    /// navigation follows it without a page load and the address bar shows the target. The
    /// target is a typed screen with a route, so an address from outside can never be one; params
    /// of the wrong type do not compile. For an address that changed for good, use
    /// [`Screen::moved_to`].
    ///
    /// ```ignore
    /// #[screen(route = "/random", public)]
    /// pub async fn random(store: Store) -> Result<Screen> {
    ///     let item = store.random().await?.ok_or(Error::NotFound)?;
    ///     Ok(Screen::redirect(item_page, ItemParams { slug: item.slug }))
    /// }
    /// ```
    pub fn redirect<S: ScreenDef>(_screen: S, params: S::Params) -> Self {
        Self {
            moved: Some((S::META.name, params_json(&params), false)),
            ..Self::new("")
        }
    }

    /// Screen, params and permanence of [`Screen::moved_to`] or [`Screen::redirect`], if any.
    pub(crate) fn take_moved(&mut self) -> Option<(&'static str, serde_json::Value, bool)> {
        self.moved.take()
    }

    fn head_mut(&mut self) -> &mut crate::seo::Head {
        self.head
            .get_or_insert_with(Default::default)
    }

    /// Summary for search results and link previews: `<meta name="description">` and
    /// `og:description`.
    pub fn description(mut self, text: impl Into<Text>) -> Self {
        self.head_mut().description = Some(text.into());
        self
    }

    /// The URL search engines should index for this page: an `https` URL, or an app path written
    /// behind `App::site_url` and the base path. Other URLs are ignored with a warning.
    pub fn canonical(mut self, url: impl Into<String>) -> Self {
        self.head_mut().canonical = crate::seo::checked(url.into(), "a canonical URL");
        self
    }

    /// The same page in another language, sent as `<link rel="alternate" hreflang="..">`:
    /// `hreflang` is a language tag such as `tr` or `zh-Hans`, or `x-default` for the page shown
    /// when no language matches, and `url` an `https` URL or an app path. List every language
    /// the page has, including its own. Bad tags or URLs are ignored with a warning, and at most
    /// [`crate::seo::MAX_ALTERNATES`] are kept.
    ///
    /// ```
    /// use zeyn::Screen;
    /// let s = Screen::new("Orders").alternate("en", "/orders").alternate("tr", "/tr/orders").alternate("x-default", "/orders");
    /// ```
    pub fn alternate(mut self, hreflang: &str, url: impl Into<String>) -> Self {
        let tag = crate::seo::valid_hreflang(hreflang);
        let url = crate::seo::checked(url.into(), "an alternate URL");
        let head = self.head_mut();
        match (tag, url) {
            (true, Some(url)) if head.alternates.len() < crate::seo::MAX_ALTERNATES => {
                head.alternates
                    .push((hreflang.to_string(), url));
            }
            (false, _) => {
                tracing::warn!("hreflang `{hreflang}` is not a language tag or x-default; ignored")
            }
            _ => {}
        }
        self
    }

    /// Image of link previews (`og:image`): an `https` URL or an app path.
    pub fn og_image(mut self, url: impl Into<String>) -> Self {
        self.head_mut().og_image = crate::seo::checked(url.into(), "an og:image URL");
        self
    }

    /// Structured data for search engines, sent as `<script type="application/ld+json">`. The
    /// browser never runs it, and the JSON is escaped so it cannot end the script element.
    pub fn json_ld(mut self, data: serde_json::Value) -> Self {
        self.head_mut().json_ld = Some(data);
        self
    }

    /// Whether search engines may index the page.
    pub fn robots(mut self, robots: crate::seo::Robots) -> Self {
        self.head_mut().robots = Some(robots);
        self
    }

    /// Head tags of the page (description, canonical, alternates, preview image, robots, JSON-LD), empty
    /// when the screen sets none.
    pub fn head_html(&self, r: &Render, site: &str, prefix: &str) -> String {
        self.head
            .as_ref()
            .map(|h| h.render(r, site, prefix))
            .unwrap_or_default()
    }

    /// Screen opened as a window.
    pub fn window(title: impl Into<Text>) -> Self {
        Self {
            kind: ScreenKind::Window { width: 560 },
            ..Self::new(title)
        }
    }

    /// Window width in pixels. No effect on full page screens.
    pub fn width(mut self, px: u32) -> Self {
        if let ScreenKind::Window { width } = &mut self.kind {
            *width = px;
        }
        self
    }

    pub fn toolbar<F, R>(mut self, build: F) -> Self
    where
        F: FnOnce(Toolbar) -> R,
        R: Into<Toolbar>,
    {
        self.toolbar = Some(build(Toolbar::default()).into());
        self
    }

    pub fn body(mut self, node: impl Into<Node>) -> Self {
        self.body.push(node.into());
        self
    }

    /// Context menu for the empty space of the screen (not over rows, headers or inputs).
    pub fn context_menu(mut self, menu: crate::menu::ContextMenu) -> Self {
        self.menu = Some(menu);
        self
    }

    /// Takes the action item at `path` of the screen's context menu, to run it.
    pub fn menu_call(&self, path: &str) -> Option<RowCall> {
        self.menu.as_ref()?.take(path)
    }

    pub fn title(&self) -> &Text {
        &self.title
    }

    pub fn nodes(&self) -> &[Node] {
        &self.body
    }

    /// Renders the screen in English with no params and no preloaded rows. For tests and tools.
    pub fn html(&self, meta: &ScreenMeta) -> String {
        self.render(
            &Render::english(meta.name),
            meta,
            &serde_json::Value::Null,
            &HashMap::new(),
        )
    }

    /// Renders the screen. `loaded` holds the first page of grids by node path (`"0"`, `"1.2"`).
    pub fn render(
        &self,
        r: &Render,
        meta: &ScreenMeta,
        params: &serde_json::Value,
        loaded: &HashMap<String, LoadedPage>,
    ) -> String {
        let scope = meta.name;
        let r = Render {
            scope,
            loaded: Some(loaded),
            ..*r
        };
        let title = r.text(&self.title);
        let params = match self
            .menu
            .as_ref()
            .map(|m| m.to_json(&r))
        {
            Some(items)
                if items
                    .as_array()
                    .is_some_and(|a| !a.is_empty()) =>
            {
                format!(r#"{}" data-zeyn-menu="{}"#, attr(params), attr(&items))
            }
            _ => attr(params),
        };
        let mut out = String::new();
        let close = match self.kind {
            ScreenKind::Page => {
                out.push_str(&format!(
                    r#"<section class="z-screen" data-zeyn-screen="{scope}" data-zeyn-params="{params}" aria-labelledby="{scope}-title"><h1 id="{scope}-title">{title}</h1>"#
                ));
                "</section>"
            }
            ScreenKind::Window { width } => {
                out.push_str(&format!(
                    r#"<div class="z-window" role="dialog" aria-modal="true" data-zeyn-screen="{scope}" data-zeyn-params="{params}" aria-labelledby="{scope}-title" style="--z-width:{width}px"><h2 id="{scope}-title">{title}</h2>"#
                ));
                "</div>"
            }
        };
        if let Some(t) = &self.toolbar {
            t.render(&mut out, &r, &title);
        }
        for (i, node) in self.body.iter().enumerate() {
            crate::ui::render_node(&mut out, &r, &i.to_string(), node);
        }
        out.push_str(close);
        out
    }

    /// Screen schema used by MCP tools, test generation and validation.
    pub fn schema(&self, meta: &ScreenMeta) -> serde_json::Value {
        let (kind, width) = match self.kind {
            ScreenKind::Page => ("page", None),
            ScreenKind::Window { width } => ("window", Some(width)),
        };
        json!({
            "screen": meta,
            "title": self.title,
            "kind": kind,
            "width": width,
            "toolbar": self.toolbar.as_ref().map(Toolbar::schema),
            "body": self.body.iter().map(Node::schema).collect::<Vec<_>>(),
        })
    }
}