nsh-engine 0.6.1

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
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
//! The embedding app's theme: sent before the start it is in the first
//! frame, sent later it updates what read the theme, and it wins over the
//! app's own theme until cleared. The app's own theme set while it runs
//! (`setTheme`).

use std::{collections::BTreeMap, time::Duration};

use crossbeam_channel::Receiver;
use nsh_base::{Theme, theme};
use nsh_core::{ApproxTextEngine, Color, MountBatch, MountItem, Size, element::Root, prelude::*};
use nsh_engine::{App, ColorScheme, Engine, EngineConfig, Environment};

use crate::ChannelSink;

/// A square of the theme's primary color.
#[component]
fn Swatch() -> impl IntoElement {
    view().size_10().bg(move || theme().primary)
}

/// The primary color of a theme that sets none: `nsh-base`'s default.
fn default_primary() -> Color {
    Color::from(Theme::default().primary.light)
}

fn themed(hex: &str) -> Theme {
    Theme::from_json(&format!(
        r#"{{ "cssVars": {{ "light": {{ "primary": "{hex}" }} }} }}"#
    ))
    .unwrap()
}

fn start(app_theme: Option<Theme>, host_theme: Option<Theme>) -> (Engine, Receiver<MountBatch>) {
    let (tx, rx) = crossbeam_channel::unbounded();
    let mut root = Root::new::<Swatch>(|| ());
    if let Some(theme) = app_theme {
        root = root.tokens(theme.into_tokens());
    }
    let config = EngineConfig {
        app: App::Rust(root),
        viewport: Size::new(px(390.0), px(844.0)),
        trace: false,
        content_culling: false,
        network: None,
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Environment::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: Vec::new(),
        runtime: None,
        support_dir: None,
        cache: nsh_engine::CacheOptions::off(),
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        windows: None,
        login_item: None,
        data_dir: None,
    };
    let engine = Engine::start_with(
        config,
        || ApproxTextEngine,
        ChannelSink(tx),
        |control| {
            if let Some(theme) = host_theme {
                control.set_tokens(Some(theme.into_tokens()));
            }
        },
    )
    .unwrap();
    (engine, rx)
}

/// The backgrounds of the batches within a moment.
fn backgrounds(rx: &Receiver<MountBatch>) -> Vec<Color> {
    let mut seen = Vec::new();
    while let Ok(batch) = rx.recv_timeout(Duration::from_millis(300)) {
        for item in &batch.items {
            if let MountItem::ViewStyle { style, .. } = item
                && style.background_color.0 & 0xff != 0
            {
                seen.push(style.background_color);
            }
        }
    }
    seen
}

#[test]
fn a_host_theme_sent_before_the_start_is_in_the_first_frame() {
    let (_engine, rx) = start(Some(themed("#0000ff")), Some(themed("#00ff00")));
    let first = rx.recv_timeout(Duration::from_secs(5)).unwrap();
    let colors: Vec<Color> = first
        .items
        .iter()
        .filter_map(|item| match item {
            MountItem::ViewStyle { style, .. } => Some(style.background_color),
            _ => None,
        })
        .collect();
    assert_eq!(colors, vec![Color(0x00ff00ff)]);
}

#[test]
fn the_host_theme_updates_the_views_and_gives_way_to_the_apps_when_cleared() {
    let (engine, rx) = start(Some(themed("#0000ff")), None);
    assert_eq!(backgrounds(&rx), vec![Color(0x0000ffff)]);
    engine
        .control()
        .set_tokens(Some(themed("#00ff00").into_tokens()));
    assert_eq!(backgrounds(&rx), vec![Color(0x00ff00ff)]);
    engine.control().set_tokens(None);
    assert_eq!(backgrounds(&rx), vec![Color(0x0000ffff)]);
}

#[test]
fn a_tsx_apps_token_classes_follow_the_host_theme() {
    let dir = std::env::temp_dir().join(format!("nsh-theme-tokens-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(
        &entry,
        "import { mount, View } from \"nsh\";\n\
         mount(() => <View class=\"h-10 w-10 bg-primary\" />);\n",
    )
    .unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: Vec::new(),
        ..Default::default()
    })
    .unwrap();
    let bytecode = nsh_js::compile_bytecode(&bundle.code, false).unwrap();
    let (tx, rx) = crossbeam_channel::unbounded();
    let config = EngineConfig {
        // SAFETY: compiled just now by this runtime.
        app: App::Js(unsafe { nsh_engine::Bundle::bytecode(bytecode) }),
        viewport: Size::new(px(390.0), px(844.0)),
        trace: false,
        content_culling: false,
        network: None,
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Environment::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: vec![nsh_base::registry()],
        runtime: None,
        support_dir: None,
        cache: nsh_engine::CacheOptions::off(),
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        windows: None,
        login_item: None,
        data_dir: None,
    };
    let engine = Engine::start(config, || ApproxTextEngine, ChannelSink(tx)).unwrap();
    assert_eq!(backgrounds(&rx), vec![default_primary()]);
    engine
        .control()
        .set_tokens(Some(themed("#00ff00").into_tokens()));
    assert_eq!(backgrounds(&rx), vec![Color(0x00ff00ff)]);
    engine.control().set_tokens(None);
    assert_eq!(backgrounds(&rx), vec![default_primary()]);
    let _ = std::fs::remove_dir_all(&dir);
}

/// The backgrounds the views draw within a moment, by node id.
fn backgrounds_by_id(rx: &Receiver<MountBatch>) -> BTreeMap<u32, Color> {
    let mut seen = BTreeMap::new();
    while let Ok(batch) = rx.recv_timeout(Duration::from_millis(300)) {
        for item in &batch.items {
            if let MountItem::ViewStyle { id, style } = item
                && style.background_color.0 & 0xff != 0
            {
                seen.insert(*id, style.background_color);
            }
        }
    }
    seen
}

/// The SDKs' theme overrides (`nsh_base::theme_overrides`): what the host
/// sets wins over the app's own theme (`nsh.json`), light and dark, and
/// what it leaves out stays the app's.
#[test]
fn a_hosts_theme_overrides_win_over_the_apps_tokens_they_set_and_keep_the_rest() {
    let dir = std::env::temp_dir().join(format!("nsh-theme-overrides-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("nsh.json"),
        r##"{ "theme": { "cssVars": { "light": { "primary": "#0000ff", "background": "#ffff00" } } } }"##,
    )
    .unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(
        &entry,
        "import { mount, View } from \"nsh\";\n\
         mount(() => (\n\
           <View>\n\
             <View class=\"h-10 w-10 bg-primary\" />\n\
             <View class=\"h-10 w-10 bg-background\" />\n\
           </View>\n\
         ));\n",
    )
    .unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: Vec::new(),
        ..Default::default()
    })
    .unwrap();
    let bytecode = nsh_js::compile_bytecode(&bundle.code, false).unwrap();
    let (tx, rx) = crossbeam_channel::unbounded();
    let config = EngineConfig {
        // SAFETY: compiled just now by this runtime.
        app: App::Js(unsafe { nsh_engine::Bundle::bytecode(bytecode) }),
        viewport: Size::new(px(390.0), px(844.0)),
        trace: false,
        content_culling: false,
        network: None,
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Environment::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: vec![nsh_base::registry()],
        runtime: None,
        support_dir: None,
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        cache: Default::default(),
        windows: None,
        login_item: None,
        data_dir: None,
    };
    // A brand's primary, light and dark, set before the app runs.
    let overrides = nsh_base::theme_overrides(
        r##"{ "cssVars": { "light": { "primary": "#e11d48" }, "dark": { "primary": "#fb7185" } } }"##,
    )
    .unwrap();
    let engine = Engine::start_with(
        config,
        || ApproxTextEngine,
        ChannelSink(tx),
        |control| control.set_tokens(Some(overrides)),
    )
    .unwrap();
    let colors = |seen: BTreeMap<u32, Color>| seen.into_values().collect::<Vec<_>>();
    // The host's primary; the app's own background stays.
    assert_eq!(
        colors(backgrounds_by_id(&rx)),
        vec![Color(0xe11d48ff), Color(0xffff00ff)]
    );
    // Dark: the override's dark value.
    engine.control().set_environment(Environment {
        color_scheme: ColorScheme::Dark,
        ..Environment::default()
    });
    assert!(colors(backgrounds_by_id(&rx)).contains(&Color(0xfb7185ff)));
    // Changed live, then cleared: the app's own again.
    engine.control().set_tokens(Some(
        nsh_base::theme_overrides(r##"{ "cssVars": { "theme": { "primary": "#00ff00" } } }"##)
            .unwrap(),
    ));
    assert_eq!(colors(backgrounds_by_id(&rx)), vec![Color(0x00ff00ff)]);
    engine.control().set_tokens(None);
    assert!(colors(backgrounds_by_id(&rx)).contains(&Color(0x0000ffff)));
    let _ = std::fs::remove_dir_all(&dir);
}

/// The texts of a batch.
fn texts(batch: &MountBatch) -> Vec<String> {
    batch
        .items
        .iter()
        .filter_map(|item| match item {
            MountItem::Text { text, .. } => Some(text.text.clone()),
            _ => None,
        })
        .collect()
}

/// The last text the batches within a moment show.
fn last_text(rx: &Receiver<MountBatch>) -> Option<String> {
    let mut last = None;
    while let Ok(batch) = rx.recv_timeout(Duration::from_millis(300)) {
        if let Some(text) = texts(&batch).pop() {
            last = Some(text);
        }
    }
    last
}

/// A TSX app whose theme (`nsh.json`) adds a token, `brand`, which it reads
/// once as its entry evaluates and again where it renders, started with
/// the embedding app's tokens `host` sent before the start.
fn start_branded(
    name: &str,
    host: Option<nsh_core::element::Tokens>,
) -> (Engine, Receiver<MountBatch>) {
    let dir = crate::temporary_root().join(format!("nsh-theme-{name}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("nsh.json"),
        r##"{ "theme": { "cssVars": { "light": { "brand": "#123456" } } } }"##,
    )
    .unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(
        &entry,
        "import { mount, Text, token } from \"nsh\";\n\
         const atStart = token(\"brand\");\n\
         mount(() => <Text>{`${atStart} ${token(\"brand\")}`}</Text>);\n",
    )
    .unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: Vec::new(),
        ..Default::default()
    })
    .unwrap();
    let _ = std::fs::remove_dir_all(&dir);
    let bytecode = nsh_js::compile_bytecode(&bundle.code, false).unwrap();
    let (tx, rx) = crossbeam_channel::unbounded();
    let config = EngineConfig {
        // SAFETY: compiled just now by this runtime.
        app: App::Js(unsafe { nsh_engine::Bundle::bytecode(bytecode) }),
        viewport: Size::new(px(390.0), px(844.0)),
        trace: false,
        content_culling: false,
        network: None,
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment: Environment::default(),
        header_heights: (nsh_core::Points(44.0), nsh_core::Points(96.0)),
        limits: nsh_engine::Limits::default(),
        ui_sets: vec![nsh_base::registry()],
        runtime: None,
        support_dir: None,
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        audio: None,
        cache: Default::default(),
        windows: None,
        login_item: None,
        data_dir: None,
    };
    let engine = Engine::start_with(
        config,
        || ApproxTextEngine,
        ChannelSink(tx),
        |control| {
            if host.is_some() {
                control.set_tokens(host);
            }
        },
    )
    .unwrap();
    (engine, rx)
}

/// The app's theme reaches the core after the turn of the first render;
/// `token()` has it from the entry's first statement on, so the first
/// render (and what the entry reads once) shows it, in a single pass.
#[test]
fn the_apps_theme_tokens_are_read_in_the_first_render() {
    let (_engine, rx) = start_branded("first-render", None);
    let first = rx.recv_timeout(Duration::from_secs(5)).unwrap();
    assert_eq!(texts(&first), vec!["#123456ff #123456ff".to_owned()]);
}

/// The embedding app's tokens sent before the start win in the first
/// render too; changed later, what read them reactively follows.
#[test]
fn the_host_tokens_win_in_the_first_render_and_reads_follow_their_changes() {
    let overrides = |hex: &str| {
        nsh_base::theme_overrides(&format!(
            r#"{{ "cssVars": {{ "light": {{ "brand": "{hex}" }} }} }}"#
        ))
        .unwrap()
    };
    let (engine, rx) = start_branded("host-first-render", Some(overrides("#abcdef")));
    let first = rx.recv_timeout(Duration::from_secs(5)).unwrap();
    assert_eq!(texts(&first), vec!["#abcdefff #abcdefff".to_owned()]);
    engine.control().set_tokens(Some(overrides("#00ff00")));
    assert_eq!(last_text(&rx).as_deref(), Some("#abcdefff #00ff00ff"));
    engine.control().set_tokens(None);
    assert_eq!(last_text(&rx).as_deref(), Some("#abcdefff #123456ff"));
}

/// A TSX app that sets its theme while it runs: a step every 100 ms, each
/// showing what `token("brand")` reads right after it, and a view drawn
/// with `bg-brand`.
const SET_THEME: &str = r##"import { effect, mount, setColorScheme, setTheme, signal, Text, token, View } from "nsh";

const status = signal("start");
let runs = 0;
const steps = [
  () => {
    setTheme({ cssVars: { light: { brand: "#00ff00" }, dark: { brand: "#003300" } } });
    return `set ${token("brand")}`;
  },
  () => {
    setColorScheme("dark");
    return `dark ${token("brand")}`;
  },
  () => {
    setColorScheme("light");
    try {
      setTheme({ cssVars: { light: { brand: "#0000ff" }, dark: { brand: "#zz" } } });
      return "taken";
    } catch (e) {
      return `${e.name}: ${e.message}; kept ${token("brand")}`;
    }
  },
  () => {
    setTheme(null);
    return `back ${token("brand")}`;
  },
  () => `runs ${runs}`,
];
steps.forEach((step, i) => setTimeout(() => status.set(step()), 100 * (i + 1)));

function App() {
  effect(() => {
    token("brand");
    runs += 1;
  });
  return (
    <View>
      <View class="h-4 bg-brand" />
      <Text>{status()}</Text>
    </View>
  );
}

mount(() => <App />);
"##;

/// `setTheme` replaces the app's theme while it runs: `token()` reads it in
/// the same turn and the classes naming its tokens follow, in each
/// appearance; a theme with a value NSH cannot read throws a `TypeError`
/// naming it and changes nothing; `null` gives back `nsh.json`'s. Each
/// change runs what read a token once.
#[test]
fn set_theme_replaces_the_apps_theme_while_it_runs() {
    let config = r##"{ "theme": { "cssVars": { "light": { "brand": "#123456" }, "dark": { "brand": "#654321" } } } }"##;
    let (_engine, rx) =
        crate::components::start_with(SET_THEME, Environment::default(), None, Some(config));
    let batches = crate::components::until(&rx, |b| crate::components::shows(b, "runs 5"));
    let texts: Vec<&str> = batches
        .iter()
        .flat_map(|b| &b.items)
        .filter_map(|item| match item {
            MountItem::Text { text, .. } => Some(&*text.text),
            _ => None,
        })
        .collect();
    assert_eq!(
        texts,
        [
            "start",
            "set #00ff00ff",
            "dark #003300ff",
            "TypeError: setTheme: `brand`: #zz is no color in the dark appearance; kept #00ff00ff",
            "back #123456ff",
            "runs 5",
        ]
    );
    let mut backgrounds: Vec<Color> = batches
        .iter()
        .flat_map(|b| &b.items)
        .filter_map(|item| match item {
            MountItem::ViewStyle { style, .. } if style.background_color.0 & 0xff != 0 => {
                Some(style.background_color)
            }
            _ => None,
        })
        .collect();
    backgrounds.dedup();
    assert_eq!(
        backgrounds,
        [
            Color(0x123456ff),
            Color(0x00ff00ff),
            Color(0x003300ff),
            Color(0x00ff00ff),
            Color(0x123456ff),
        ]
    );
}

#[test]
fn set_theme_refuses_malformed_themes_without_changing_tokens_or_views() {
    let source = r##"import { mount, setTheme, signal, Text, token, View } from "nsh";
const status = signal("start");
setTimeout(() => {
  const invalid = [
    { cssVars: null },
    { cssVars: [] },
    { cssVars: true },
    { cssVars: 12 },
    { cssVars: "light" },
    { cssVars: { light: { brand: "rgb(255 0 0" } } },
    { cssVars: { light: { brand: "oklch(0.7 0.1" } } },
    { cssVars: { light: { brand: "var(--nothing" } } },
    { cssVars: { light: { brand: "#zz" }, dark: { brand: "12px" } } },
    { cssVars: { light: { brand: "rgb(255 0 0)garbage" } } },
    { cssVars: { light: { brand: "rgb(255 0 0)inset-x" } } },
    { cssVars: { light: { brand: "color-mix(in srgb, rgb(255 0 0) 50%, blue)garbage" } } },
    { cssVars: { light: { brand: "var(--primary)garbage" } } },
  ];
  const results = invalid.map(theme => {
    setTheme({ cssVars: { light: { brand: "#00ff00" } } });
    try { setTheme(theme); return "taken"; }
    catch (error) { return `${error.name} kept ${token("brand")}`; }
  });
  status.set(results.join("; "));
}, 100);
mount(() => <View><View class="h-4 bg-brand" /><Text>{status()}</Text></View>);
"##;
    let config = r##"{ "theme": { "cssVars": { "light": { "brand": "#123456" } } } }"##;
    let (_engine, rx) =
        crate::components::start_with(source, Environment::default(), None, Some(config));
    let expected = ["TypeError kept #00ff00ff"; 13].join("; ");
    let batches = crate::components::until(&rx, |b| crate::components::shows(b, &expected));
    let texts: Vec<&str> = batches
        .iter()
        .flat_map(|b| &b.items)
        .filter_map(|item| match item {
            MountItem::Text { text, .. } => Some(&*text.text),
            _ => None,
        })
        .collect();
    assert_eq!(texts.last().copied(), Some(expected.as_str()));
    let themed = batches
        .iter()
        .flat_map(|b| &b.items)
        .find_map(|item| match item {
            MountItem::ViewStyle { id, style } if style.background_color == Color(0x123456ff) => {
                Some(*id)
            }
            _ => None,
        })
        .expect("the built theme paints the themed view before the timer runs");
    let mut backgrounds: Vec<Color> = batches
        .iter()
        .flat_map(|b| &b.items)
        .filter_map(|item| match item {
            // Keep transparent changes too: dropping the token must not
            // leave the preceding opaque color as the last value seen.
            MountItem::ViewStyle { id, style } if *id == themed => Some(style.background_color),
            _ => None,
        })
        .collect();
    backgrounds.dedup();
    assert_eq!(backgrounds, [Color(0x123456ff), Color(0x00ff00ff)]);
}