nsh-engine 0.4.0

Engine thread that drives the JS host and the core and emits mount batches.
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
//! A UI set of the tests' own (`test/ui`): small components that exercise
//! the machinery of Rust components (slots and how their content lays out, children placed one by one,
//! virtualized `items`, `#[prop(lazy)]` children, `#[methods]` refs, events,
//! waiting for the app's answer to them, inputs) as an app's crate would,
//! with no UI set of nsh's.

use std::{rc::Rc, time::Duration};

use nsh_base::{dialog, input, theme};
use nsh_core::{element::Registry, prelude::*};

/// The module the tests' apps import these components from.
pub(crate) const SPECIFIER: &str = "test/ui";

/// The set, for the bundler, the compiler and the engine.
pub(crate) fn registry() -> Registry {
    let mut registry = Registry::ui_set(SPECIFIER);
    registry
        .register::<Button>()
        .register::<Card>()
        .register::<Disclosure>()
        .register::<Field>()
        .register::<Group>()
        .register::<ListView>()
        .register::<Pick>()
        .register::<Stepper>()
        .register::<TextField>()
        .register::<Sheet>()
        .register::<Shortcut>();
    registry
}

// --- Button: a press target with a label, and its event --------------------

/// A press target with a label, drawn in full: the component benchmarks
/// compare it with the same Button written in TSX.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct ButtonProps {
    /// The label.
    pub(crate) title: Prop<SharedString>,
    /// `primary` (default): filled; `secondary`: tinted; `danger`: a
    /// destructive action; `plain`: text only.
    #[prop(default)]
    pub(crate) variant: Prop<ButtonVariant>,
    /// No presses, no feedback, dimmed.
    #[prop(default)]
    pub(crate) disabled: Prop<bool>,
    /// For screen readers, when `title` is not enough.
    pub(crate) accessibility_label: Prop<Option<SharedString>>,
}

/// How a [`Button`] looks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub(crate) enum ButtonVariant {
    /// Filled with the primary color.
    #[default]
    Primary,
    /// Filled with the secondary color.
    Secondary,
    /// Filled with the danger color.
    Danger,
    /// Text only; a background while pressed.
    Plain,
}

/// The events of a [`Button`].
#[derive(Debug, Clone, PartialEq, Event)]
pub(crate) enum ButtonEvent {
    /// The button was pressed.
    Press,
}

/// The background, the background while pressed and the label's color of
/// `variant`.
fn colors(variant: ButtonVariant) -> (AdaptiveColor, AdaptiveColor, AdaptiveColor) {
    let theme = theme();
    match variant {
        // shadcn's buttons: the role's color, 90% (80%) of it pressed.
        ButtonVariant::Primary => (
            theme.primary,
            theme.primary.opacity(0.9),
            theme.primary_foreground,
        ),
        ButtonVariant::Secondary => (
            theme.secondary,
            theme.secondary.opacity(0.8),
            theme.secondary_foreground,
        ),
        ButtonVariant::Danger => (
            theme.destructive,
            theme.destructive.opacity(0.9),
            AdaptiveColor::rgb(0xffffff, 0xffffff),
        ),
        ButtonVariant::Plain => (AdaptiveColor::TRANSPARENT, theme.accent, theme.foreground),
    }
}

/// A press target with a label ([`ButtonProps`]).
#[component]
pub(crate) fn Button(props: ButtonProps, cx: Scope<ButtonEvent>) -> impl IntoElement {
    let colors = computed(move || colors(props.variant.get()));
    view()
        .flex_row()
        .items_center()
        .justify_center()
        .px_4()
        .py_3()
        .rounded(move || theme().radius)
        .bg(move || colors.get().0)
        .active(|s| s.bg(move || colors.get().1))
        .style_when(props.disabled, |v| v.opacity(0.5))
        .disabled(props.disabled)
        .role(AccessibilityRole::Button)
        .label(move || {
            props
                .accessibility_label
                .get()
                .unwrap_or_else(|| props.title.get())
        })
        .on_press(move |_: &()| cx.emit(ButtonEvent::Press))
        .child(
            text(props.title)
                .text_size(px(16.0))
                .font_weight(FontWeight::SEMIBOLD)
                .text_color(move || colors.get().2),
        )
}

// --- Card: named slots placed around the children --------------------------

/// A surface with an optional header and footer around its content.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct CardProps {
    /// Above the content.
    pub(crate) header: Prop<Option<Slot>>,
    /// Below the content.
    pub(crate) footer: Prop<Option<Slot>>,
    /// The content.
    pub(crate) children: Prop<Children>,
}

/// A surface ([`CardProps`]): the header in its slot's holder, the
/// children in a padded box.
#[component]
pub(crate) fn Card(props: CardProps) -> impl IntoElement {
    view()
        .border_1()
        .child(props.header.place(|header| header.px_4().pt_4()))
        .child(view().gap_2().p_4().child(props.children))
        .child(
            props
                .footer
                .place(|footer| footer.flex_row().justify_end().px_4().py_3()),
        )
}

// --- Disclosure: a slot the view makes a button ------------------------------

/// A trigger the app passes, made a disclosure button.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct DisclosureProps {
    /// No presses.
    #[prop(default)]
    pub(crate) disabled: Prop<bool>,
    /// What the user presses.
    pub(crate) trigger: Prop<Option<Slot>>,
}

/// A trigger the view gives a role, the keyboard focus, `disabled`, an
/// expanded state and presses that flip it ([`DisclosureProps`]), as a
/// popup's trigger: they are the app's element's own, so its state classes
/// follow them.
#[component]
pub(crate) fn Disclosure(props: DisclosureProps) -> impl IntoElement {
    let open = signal(false);
    view().child(props.trigger.place(move |trigger| {
        trigger
            .role(AccessibilityRole::Button)
            .focusable(true)
            .disabled(props.disabled)
            .accessibility_state(move || AccessibilityState {
                expanded: Some(open.get()),
                ..AccessibilityState::default()
            })
            .on_press(move |_: &()| open.update(|o| *o = !*o))
    }))
}

// --- Field: a slot placed as it is, in a row -------------------------------

/// A label the app passes before a control of fixed size, in a row.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct FieldProps {
    /// Before the control.
    pub(crate) label: Prop<Option<Slot>>,
    /// After the control, in a padded box of the view's.
    pub(crate) hint: Prop<Option<Slot>>,
}

/// A row 300 × 40 ([`FieldProps`]): the label placed as it is, then a
/// 50 × 20 control, then the hint in a padded box. The app's element in
/// the label's slot lays out as an item of the row.
#[component]
pub(crate) fn Field(props: FieldProps) -> impl IntoElement {
    view()
        .flex_row()
        .items_center()
        .w(px(300.0))
        .h(px(40.0))
        .child(props.label.place(|label| label))
        .child(view().w(px(50.0)).h(px(20.0)))
        .child(props.hint.place(|hint| hint.px_2()))
}

// --- Group: children placed one by one --------------------------------------

/// Rows, each JSX child one, divided by hairlines.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct GroupProps {
    /// The rows, one per child.
    pub(crate) children: Prop<Children>,
}

/// Rows in a box ([`GroupProps`]): every row but the first has a top
/// border.
#[component]
pub(crate) fn Group(props: GroupProps) -> impl IntoElement {
    view().children_each(props.children, move |row, at| {
        view()
            .px_4()
            .py_3()
            .style_when(
                move || !at.is_first(),
                |s| s.border_t_1().border_color(move || theme().border),
            )
            .child(row)
    })
}

// --- ListView: a virtualized list of the app's rows -------------------------

/// A scrolling list of the app's rows, padded and divided.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct ListViewProps {
    /// The rows.
    pub(crate) items: Items,
    /// `plain` (default): full-width rows; `inset`: rows in a rounded box.
    #[prop(default)]
    pub(crate) variant: Prop<ListViewVariant>,
}

/// How a [`ListView`] shows its rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub(crate) enum ListViewVariant {
    /// Full-width rows.
    #[default]
    Plain,
    /// Rows in a rounded box: the first rounds its top corners, the last
    /// its bottom ones.
    Inset,
}

/// A scrolling list of rows ([`ListViewProps`]): each row in a wrapper of
/// the list's (its padding, its divider, its corners).
#[component]
pub(crate) fn ListView(props: ListViewProps, _cx: Scope<NoEvent>) -> impl IntoElement {
    let inset = computed(move || props.variant.get() == ListViewVariant::Inset);
    view().flex_1().list(
        props.items,
        move |list| {
            list.flex_1()
                .estimated_item_size(px(48.0))
                .content_padding(move || if inset.get() { 16.0_f32 } else { 0.0 })
        },
        move |row, at| {
            let radius = move || px(12.0);
            view()
                .px_4()
                .py_3()
                .min_h(px(48.0))
                .style_when(
                    move || !at.is_first(),
                    |v| v.border_t_1().border_color(move || theme().border),
                )
                .style_when(
                    move || inset.get() && at.is_first(),
                    |v| v.rounded_t(radius),
                )
                .style_when(move || inset.get() && at.is_last(), |v| v.rounded_b(radius))
                .child(row)
        },
    )
}

// --- Stepper: own state, timers, and methods on a ref -----------------------

/// A number with − and + buttons, within `min`–`max`; holding a button
/// keeps stepping.
#[derive(Debug, Clone, Copy, PartialEq, Props)]
pub(crate) struct StepperProps {
    /// The first value.
    #[prop(default)]
    pub(crate) default_value: Prop<f64>,
    /// The smallest value.
    #[prop(default = 0.0)]
    pub(crate) min: Prop<f64>,
    /// The largest value.
    #[prop(default = 100.0)]
    pub(crate) max: Prop<f64>,
}

/// The events of a [`Stepper`].
#[derive(Debug, Clone, PartialEq, Event)]
pub(crate) enum StepperEvent {
    /// The value changed (the new one).
    Change(f64),
}

/// How long a press is held before it repeats, and how fast it repeats.
const HOLD: Duration = Duration::from_millis(400);
const REPEAT: Duration = Duration::from_millis(80);

/// What JS (and Rust, through a `ComponentRef`) calls on a stepper.
pub(crate) struct StepperApi {
    value: Signal<f64>,
    change: Rc<dyn Fn(f64)>,
}

#[methods]
impl StepperApi {
    /// Sets the value (rounded, within the bounds) and reports it as a
    /// press would.
    pub(crate) fn set_value(&self, value: f64) {
        (self.change)(value);
    }

    /// The value shown.
    pub(crate) fn value(&self) -> f64 {
        self.value.get_untracked()
    }
}

/// A number with − and + buttons ([`StepperProps`]).
#[component(methods = StepperApi)]
pub(crate) fn Stepper(props: StepperProps, cx: Scope<StepperEvent>) -> impl IntoElement {
    let fit = move |value: f64| {
        let (min, max) = (props.min.get_untracked(), props.max.get_untracked());
        value.round().clamp(min.min(max), min.max(max))
    };
    let value = signal(untracked(|| fit(props.default_value.get())));
    let repeat = stored(None::<Spawned<()>>);
    let stop = move || {
        if let Some(task) = repeat.replace(None) {
            task.cancel();
        }
    };
    let change = move |next: f64| {
        let next = fit(next);
        if next == value.get_untracked() {
            stop();
            return;
        }
        value.set(next);
        cx.emit(StepperEvent::Change(next));
    };
    let step = move |direction: f64| change(value.get_untracked() + direction);
    // A press: one step now, more while it is held.
    let press = move |direction: f64| {
        stop();
        step(direction);
        repeat.replace(Some(spawn(async move {
            timer(HOLD).await;
            loop {
                step(direction);
                timer(REPEAT).await;
            }
        })));
    };
    cx.methods(StepperApi {
        value,
        change: Rc::new(change),
    });
    let button = move |label: &'static str, direction: f64| {
        view()
            .size_10()
            .items_center()
            .justify_center()
            .role(AccessibilityRole::Button)
            .on(EventKind::PressDown, move |_: &EventPayload| {
                press(direction)
            })
            .on(EventKind::PressUp, move |_: &EventPayload| stop())
            .child(text(label))
    };
    view()
        .flex_row()
        .items_center()
        .gap_3()
        .child(button("−", -1.0))
        .child(text(move || format!("{}", value.get())))
        .child(button("+", 1.0))
}

// --- TextField: an input the component controls -----------------------------

/// A text input with a clear button; the app controls the text.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct TextFieldProps {
    /// The text.
    #[prop(default)]
    pub(crate) value: Prop<SharedString>,
}

/// The events of a [`TextField`].
#[derive(Debug, Clone, PartialEq, Event)]
pub(crate) enum TextFieldEvent {
    /// The text changed (the new text).
    Change(String),
}

/// A text input ([`TextFieldProps`]): the clear button comes and goes
/// after the input as the text does.
#[component]
pub(crate) fn TextField(props: TextFieldProps, cx: Scope<TextFieldEvent>) -> impl IntoElement {
    let field = element_ref();
    let change = move |text: String| cx.emit(TextFieldEvent::Change(text));
    view()
        .flex_row()
        .items_center()
        .min_h(px(44.0))
        .px_3()
        .child(
            input()
                .element_ref(&field)
                .flex_1()
                .value(move || props.value.get().as_str().to_owned())
                .on_change(move |text: &str| change(text.to_owned())),
        )
        .child(when(
            move || !props.value.with(|v| v.is_empty()),
            move || {
                view()
                    .size_6()
                    .role(AccessibilityRole::Button)
                    .label("Clear")
                    .on_press(move |_: &()| {
                        change(String::new());
                        field.focus();
                    })
                    .child(text("×"))
            },
        ))
}

// --- Pick: a value of its own until the app answers ------------------------

/// A value of the app's.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct PickProps {
    /// The value.
    #[prop(default)]
    pub(crate) value: Prop<u32>,
}

/// The events of a [`Pick`].
#[derive(Debug, Clone, PartialEq, Event)]
pub(crate) enum PickEvent {
    /// A press asks for one more (the value asked for).
    Change(u32),
}

/// Shows `value` (`pick <value>`); a press asks for one more, which shows
/// at once until the app has answered ([`after_answer`]), as a slider shows
/// a drag's value; then the app's, and `answered <value>`, the `value` the
/// closure saw.
#[component]
pub(crate) fn Pick(props: PickProps, cx: Scope<PickEvent>) -> impl IntoElement {
    let pending = signal(None::<u32>);
    let answered = signal(None::<u32>);
    view()
        .role(AccessibilityRole::Button)
        .on_press(move |_: &()| {
            let next = pending
                .get_untracked()
                .unwrap_or_else(|| props.value.get_untracked())
                + 1;
            pending.set(Some(next));
            cx.emit(PickEvent::Change(next));
            after_answer(move || {
                answered.set(Some(props.value.get_untracked()));
                pending.set(None);
            });
        })
        .child(text(move || {
            format!(
                "pick {}",
                pending.get().unwrap_or_else(|| props.value.get())
            )
        }))
        .child(text(move || {
            answered
                .get()
                .map_or_else(String::new, |v| format!("answered {v}"))
        }))
}

// --- Shortcut: a binding of the view's own ---------------------------------

/// Counts the presses of a keystroke the view binds itself.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct ShortcutProps {
    /// The keystroke, as `on_key` takes it.
    pub(crate) keys: Prop<SharedString>,
}

/// `<keys> <count>` ([`ShortcutProps`]), counted by the view's own binding.
#[component]
pub(crate) fn Shortcut(props: ShortcutProps) -> impl IntoElement {
    let keys = props.keys.get();
    let count = signal(0);
    on_key(&keys, move |_| count.update(|c| *c += 1));
    text(move || format!("{keys} {}", count.get()))
}

// --- Sheet: lazy children, made while it is open ----------------------------

/// A panel over the screen while `open`.
#[derive(Debug, Clone, PartialEq, Props)]
pub(crate) struct SheetProps {
    /// Shown.
    #[prop(default)]
    pub(crate) open: Prop<bool>,
    /// The content: made when the sheet opens and released when it closes.
    #[prop(lazy)]
    pub(crate) children: Children,
}

/// A panel in a modal ([`SheetProps`]).
#[component]
pub(crate) fn Sheet(props: SheetProps) -> impl IntoElement {
    let children = props.children;
    view().child(when(props.open, move || {
        dialog().animation(ModalAnimation::None).child(
            view()
                .absolute()
                .left_0()
                .right_0()
                .bottom_0()
                .p_4()
                .child(children),
        )
    }))
}