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
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,
}
/// 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>>;
}
/// 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(¶ms) }
}
/// 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(¶ms) }
}
}
/// 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(¶ms) });
}
/// 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
}
}
/// 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)
}
}
/// 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)]
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>,
}
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 }
}
/// 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<_>>(),
})
}
}