nsh-core 0.8.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
//! The host attributes a view gives a nested component's element go on the
//! node of that component's root, over the root's own: its tooltip, focus
//! stop and the screen readers' description, value, actions, active
//! descendant and controlled element.

use std::{cell::RefCell, time::Duration};

use super::*;
use crate::{
    AccessibilityActionDef, AccessibilityValue, PayloadValue,
    element::{Props, Root, Scope},
    prelude::*,
};

thread_local! {
    static HEARD: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    static STEP: Cell<Option<Signal<u8>>> = const { Cell::new(None) };
}

fn action(name: &str, label: Option<&str>) -> AccessibilityActionDef {
    AccessibilityActionDef {
        name: name.into(),
        label: label.map(Into::into),
    }
}

fn heard() -> Vec<String> {
    HEARD.with(|h| std::mem::take(&mut *h.borrow_mut()))
}

#[derive(Clone, PartialEq, Props)]
struct ActsProps {
    /// What its root says of itself.
    #[prop(default = "own".into())]
    says: crate::element::Prop<SharedString>,
}

/// A pressable root that describes itself, offers `activate` and hears the
/// actions performed on it.
#[component]
fn Acts(props: ActsProps, _cx: Scope<NoEvent>) -> impl IntoElement {
    view()
        .size_10()
        .label("acts")
        .accessibility_description(props.says)
        .accessibility_actions(vec![action("activate", None)])
        .on_press(|| {})
        .on_accessibility_action(|name: &str| {
            HEARD.with(|h| h.borrow_mut().push(format!("own {name}")))
        })
}

/// [`Acts`] given every host attribute while the step is 0, none after; a
/// row and a list it names.
#[component]
fn Gives() -> impl IntoElement {
    let step = signal(0u8);
    STEP.with(|s| s.set(Some(step)));
    let row = element_ref();
    let list = element_ref();
    view()
        .child(dynamic(move || {
            let acts = acts();
            match step.get() {
                0 => acts
                    .accessibility_description("given")
                    .accessibility_value(Some(AccessibilityValue {
                        text: Some("3 of 5".into()),
                        ..AccessibilityValue::default()
                    }))
                    .accessibility_actions(vec![action("pin", Some("Pin"))])
                    .on_accessibility_action(|name: &str| {
                        HEARD.with(|h| h.borrow_mut().push(format!("given {name}")))
                    })
                    .focusable(false)
                    .accessibility_active_descendant(Some(row))
                    .accessibility_controls(Some(list)),
                _ => acts,
            }
        }))
        .child(
            view()
                .label("list")
                .element_ref(&list)
                .child(view().label("row").element_ref(&row)),
        )
}

/// The view props node `id` has.
fn props_of(c: &Core<FakeEngine>, id: NodeId) -> crate::ViewProps {
    c.nodes[c.key(id).unwrap() as usize]
        .props
        .as_deref()
        .cloned()
        .unwrap_or_default()
}

/// The id of the view labeled `label`.
fn labeled(c: &Core<FakeEngine>, label: &str) -> NodeId {
    c.nodes
        .iter()
        .find(|(_, n)| {
            n.props
                .as_deref()
                .is_some_and(|p| p.accessibility.label.as_deref() == Some(label))
        })
        .map(|(_, n)| n.id)
        .unwrap_or_else(|| panic!("no view labeled {label}"))
}

fn perform(c: &mut Core<FakeEngine>, id: NodeId, name: &str) {
    c.component_event(
        id,
        EventKind::AccessibilityAction,
        &EventPayload::Map(vec![("actionName", PayloadValue::Str(name.into()))]),
    );
}

fn set_step(c: &mut Core<FakeEngine>, to: u8) {
    let step = STEP.with(Cell::get).unwrap();
    let _entered = c.components.runtime.enter();
    step.set(to);
}

#[test]
fn host_attributes_given_a_component_go_on_its_roots_node_and_go_back() {
    heard();
    let mut c = core();
    c.mount_root(&Root::new::<Gives>(|| ()));
    c.commit().unwrap();
    let root = labeled(&c, "acts");
    let a11y = props_of(&c, root).accessibility;
    assert_eq!(a11y.description.as_deref(), Some("given"));
    assert_eq!(a11y.value.and_then(|v| v.text).as_deref(), Some("3 of 5"));
    // The root's own actions, then the ones given it.
    assert_eq!(
        a11y.actions,
        [action("activate", None), action("pin", Some("Pin"))]
    );
    assert_eq!(a11y.active_descendant, Some(labeled(&c, "row")));
    assert_eq!(a11y.controls, Some(labeled(&c, "list")));
    assert_eq!(props_of(&c, root).focusable, Some(false));
    // The root's listener hears an action, then the one given it.
    perform(&mut c, root, "pin");
    assert_eq!(heard(), ["own pin", "given pin"]);

    // Given none: the root's own come back.
    set_step(&mut c, 1);
    c.commit().unwrap();
    let root = labeled(&c, "acts");
    let props = props_of(&c, root);
    assert_eq!(props.accessibility.description.as_deref(), Some("own"));
    assert_eq!(props.accessibility.value, None);
    assert_eq!(props.accessibility.actions, [action("activate", None)]);
    assert_eq!(props.accessibility.active_descendant, None);
    assert_eq!(props.accessibility.controls, None);
    assert_eq!(props.focusable, None);
    perform(&mut c, root, "activate");
    assert_eq!(heard(), ["own activate"]);
}

/// [`Acts`] as the root of a view that gives it attributes of its own.
#[component]
fn Wraps() -> impl IntoElement {
    acts()
        .accessibility_description("inner")
        .accessibility_actions(vec![
            action("pin", Some("Pin")),
            action("copy", Some("Copy")),
        ])
        .focusable(true)
}

/// [`Wraps`] given attributes over the ones it gives its root.
#[component]
fn Outer() -> impl IntoElement {
    view().child(
        wraps()
            .accessibility_description("outer")
            .accessibility_actions(vec![action("pin", Some("Pin it"))])
            .focusable(false),
    )
}

#[test]
fn along_a_chain_of_components_the_outer_attributes_win_and_actions_add_up() {
    let mut c = core();
    c.mount_root(&Root::new::<Outer>(|| ()));
    c.commit().unwrap();
    let props = props_of(&c, labeled(&c, "acts"));
    assert_eq!(props.accessibility.description.as_deref(), Some("outer"));
    assert_eq!(props.focusable, Some(false));
    assert_eq!(
        props.accessibility.actions,
        [
            action("activate", None),
            action("pin", Some("Pin it")),
            action("copy", Some("Copy")),
        ]
    );
}

/// [`Acts`] with a tooltip while the step is 0, none after.
#[component]
fn Hints() -> impl IntoElement {
    let step = signal(0u8);
    STEP.with(|s| s.set(Some(step)));
    view()
        .mt(px(100.0))
        .child(dynamic(move || match step.get() {
            0 => acts().tooltip(text("Pins it")).into_element(),
            _ => acts().into_element(),
        }))
}

#[test]
fn a_tooltip_given_a_component_shows_on_its_root() {
    let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
    let _clock = clock.enter();
    let mut c = core();
    c.set_environment(crate::element::Environment {
        os: crate::platform::Os::Linux,
        idiom: crate::platform::Idiom::Desktop,
        ..crate::element::Environment::default()
    });
    c.mount_root(&Root::new::<Hints>(|| ()));
    let batch = c.commit().unwrap();
    assert!(texts_of(&batch).is_empty(), "{:?}", texts_of(&batch));
    let root = labeled(&c, "acts");
    // The hint overlay the element is made of is the tooltip itself, in
    // the root's node.
    let made = c.overlay_state.tooltips[&root];
    let key = c.key(made.overlay).unwrap();
    assert_eq!(c.nodes[c.nodes[key as usize].parent as usize].id, root);

    c.component_event(
        root,
        EventKind::MouseEnter,
        &EventPayload::Mouse(crate::MouseEvent::default()),
    );
    clock.advance_to(crate::time::now() + Duration::from_millis(500));
    c.run_component_tasks();
    let batch = c.commit().unwrap();
    assert_eq!(texts_of(&batch), ["Pins it"]);

    // Given none: it goes with its nodes.
    set_step(&mut c, 1);
    c.commit().unwrap();
    let root = labeled(&c, "acts");
    assert!(!c.overlay_state.tooltips.contains_key(&root));
    assert!(
        c.key(made.overlay).is_err(),
        "the tooltip's nodes are released"
    );
}

/// [`Acts`] given what screen readers call it.
#[component]
fn Names() -> impl IntoElement {
    view().child(acts().accessibility_label("Error. Try again later"))
}

#[test]
fn a_label_given_a_component_names_its_root() {
    let mut c = core();
    c.mount_root(&Root::new::<Names>(|| ()));
    c.commit().unwrap();
    // The root's own node (its own description), named as given.
    let root = labeled(&c, "Error. Try again later");
    assert_eq!(
        props_of(&c, root).accessibility.description.as_deref(),
        Some("own")
    );
    assert!(
        !c.nodes
            .iter()
            .any(|(_, n)| n
                .props
                .as_deref()
                .is_some_and(|p| p.accessibility.label.as_deref() == Some("acts"))),
        "the root's own label gives way"
    );
}

thread_local! {
    static ON: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}

fn turn_off(c: &mut Core<FakeEngine>) {
    let on = ON.with(Cell::get).unwrap();
    let _entered = c.components.runtime.enter();
    on.set(false);
}

/// [`Acts`] given a description and a focus stop bound to a signal: no view
/// renders again, only the binding changes them.
#[component]
fn Binds() -> impl IntoElement {
    let on = signal(true);
    ON.with(|s| s.set(Some(on)));
    view().child(
        acts()
            .accessibility_description(move || if on.get() { "given a" } else { "given b" })
            .focusable(move || !on.get()),
    )
}

#[test]
fn bound_attributes_given_a_component_follow_their_signal() {
    let mut c = core();
    c.mount_root(&Root::new::<Binds>(|| ()));
    c.commit().unwrap();
    let root = labeled(&c, "acts");
    let props = props_of(&c, root);
    assert_eq!(props.accessibility.description.as_deref(), Some("given a"));
    assert_eq!(props.focusable, Some(false));
    turn_off(&mut c);
    c.commit().unwrap();
    assert_eq!(labeled(&c, "acts"), root, "the same node");
    let props = props_of(&c, root);
    assert_eq!(props.accessibility.description.as_deref(), Some("given b"));
    assert_eq!(props.focusable, Some(true));
}

#[derive(Clone, PartialEq, Props)]
struct PlacesProps {
    trigger: crate::element::Prop<Option<Slot>>,
}

/// Places its trigger and says of it what a disclosure would.
#[component]
fn Places(props: PlacesProps) -> impl IntoElement {
    view().child(props.trigger.place(|t| {
        t.px_2()
            .accessibility_description("slot's own")
            .focusable(true)
    }))
}

/// Fills [`Places`]' trigger with an [`Acts`] given a description and a
/// focus stop bound to a signal.
#[component]
fn Fills() -> impl IntoElement {
    let on = signal(true);
    ON.with(|s| s.set(Some(on)));
    view().child(
        places().trigger(
            acts()
                .accessibility_description(move || if on.get() { "given a" } else { "given b" })
                .focusable(move || !on.get()),
        ),
    )
}

/// What a slot's component sets on the element filling it wins over what
/// the placing view gives it, on the first render and after a given
/// attribute changes alike.
#[test]
fn a_slots_own_attributes_win_over_ones_given_its_fill_after_they_change() {
    let mut c = core();
    c.mount_root(&Root::new::<Fills>(|| ()));
    c.commit().unwrap();
    let root = labeled(&c, "acts");
    let first = props_of(&c, root);
    assert_eq!(
        first.accessibility.description.as_deref(),
        Some("slot's own")
    );
    assert_eq!(first.focusable, Some(true));
    turn_off(&mut c);
    // Nothing the node shows changes.
    c.commit();
    let after = props_of(&c, root);
    assert_eq!(
        after.accessibility.description.as_deref(),
        Some("slot's own")
    );
    assert_eq!(after.focusable, Some(true));
}

/// Makes a host of component `C` the way a TSX app does, with `props` on
/// it.
fn js_host<C: Component>(c: &mut Core<FakeEngine>, props: Vec<crate::Prop>) {
    let mut registry = crate::element::Registry::new();
    registry.register::<C>();
    c.set_components(registry);
    let mut ops = vec![
        Op::Create {
            id: 2,
            tag: Tag::View,
        },
        Op::SetProp {
            id: 2,
            prop: crate::Prop::Component(std::any::type_name::<C>().into()),
        },
    ];
    ops.extend(props.into_iter().map(|prop| Op::SetProp { id: 2, prop }));
    ops.push(Op::Insert {
        parent: ROOT_ID,
        child: 2,
        before: None,
    });
    apply(c, ops);
}

fn js_description(says: Option<&str>) -> crate::Prop {
    crate::Prop::Accessibility(crate::AccessibilityProp::Description(says.map(Into::into)))
}

/// A TSX app's `<Acts accessibilityDescription="tsx" focusable={false}>`:
/// its host is the outermost, over the root's own; cleared, the root's own
/// come back.
#[test]
fn a_tsx_hosts_attributes_win_over_the_roots_own_and_go_back() {
    let mut c = core();
    js_host::<Acts>(
        &mut c,
        vec![
            js_description(Some("tsx")),
            crate::Prop::Focusable(Some(false)),
        ],
    );
    c.commit().unwrap();
    let root = labeled(&c, "acts");
    let props = props_of(&c, root);
    assert_eq!(props.accessibility.description.as_deref(), Some("tsx"));
    assert_eq!(props.focusable, Some(false));

    apply(
        &mut c,
        vec![
            Op::SetProp {
                id: 2,
                prop: js_description(None),
            },
            Op::SetProp {
                id: 2,
                prop: crate::Prop::Focusable(None),
            },
        ],
    );
    c.commit().unwrap();
    let props = props_of(&c, root);
    assert_eq!(props.accessibility.description.as_deref(), Some("own"));
    assert_eq!(props.focusable, None);
}

/// A TSX app's `<Wraps accessibilityDescription="tsx">`, whose view gives
/// its root ([`Acts`]) "inner": the TSX host is the outer.
#[test]
fn a_tsx_hosts_attributes_win_over_what_a_rust_view_gives_its_root() {
    let mut c = core();
    js_host::<Wraps>(&mut c, vec![js_description(Some("tsx"))]);
    c.commit().unwrap();
    let props = props_of(&c, labeled(&c, "acts"));
    assert_eq!(props.accessibility.description.as_deref(), Some("tsx"));
    // What [`Wraps`] gives and JS does not stays.
    assert_eq!(props.focusable, Some(true));
}

/// A root that names its own active descendant and controlled element (a
/// list's cursor row).
#[component]
fn OwnsRow() -> impl IntoElement {
    let row = element_ref();
    view()
        .size_10()
        .label("owner")
        .on_press(|| {})
        .accessibility_active_descendant(Some(row))
        .accessibility_controls(Some(row))
        .child(view().label("own row").element_ref(&row))
}

/// Gives [`OwnsRow`] no active descendant and no controlled element
/// (`None`), as a bound `Option<ElementRef>` is between rows.
#[component]
fn GivesNone() -> impl IntoElement {
    view().child(
        owns_row()
            .accessibility_active_descendant(None::<crate::element::ElementRef>)
            .accessibility_controls(None::<crate::element::ElementRef>),
    )
}

/// `None` is none given, as for `accessibility_value`: the root's own stay.
#[test]
fn no_active_descendant_given_a_component_leaves_the_roots_own() {
    let mut c = core();
    c.mount_root(&Root::new::<GivesNone>(|| ()));
    c.commit().unwrap();
    let a11y = props_of(&c, labeled(&c, "owner")).accessibility;
    let row = labeled(&c, "own row");
    assert_eq!(a11y.active_descendant, Some(row));
    assert_eq!(a11y.controls, Some(row));
}