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
//! 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.

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,
        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,
        data_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,
    };
    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(),
    })
    .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,
        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,
        data_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,
    };
    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(),
    })
    .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,
        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,
        data_dir: None,
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        cache: Default::default(),
    };
    // 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(),
    })
    .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,
        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,
        data_dir: None,
        storage: None,
        clock: Default::default(),
        context: Default::default(),
        pinned: Default::default(),
        clipboard: None,
        host: Default::default(),
        picker: None,
        speech: None,
        cache: Default::default(),
    };
    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"));
}