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
//! Registered native components end to end: `nsh/native`'s props reach the
//! platform as JSON, events come back to the handlers, commands go out.

use std::time::Duration;

use crossbeam_channel::Receiver;
use nsh_core::{
    ApproxTextEngine, Command, EventKind, EventPayload, JsonValue, MountBatch, MountItem, Size,
    ViewKind, geometry::px,
};
use nsh_engine::{Bundle, Engine, EngineConfig};
use serde_json::json;

use crate::ChannelSink;

const APP: &str = r#"import { mount, signal, Text, View } from "nsh";
import { nativeComponent } from "nsh";

const Map = nativeComponent<
  { center: { lat: number; lng: number }; zoom?: number; title?: string },
  { regionChange: { zoom: number } }
>("com.example.map", { props: ["center", "zoom", "title"], events: ["regionChange"] });

function App() {
  const zoom = signal(3);
  let map: any;
  return (
    <View>
      <Map
        ref={(n: any) => (map = n)}
        center={{ lat: 1.5, lng: 2 }}
        zoom={zoom()}
        style={{ height: 100 }}
        onRegionChange={(e: { zoom: number }) => {
          zoom.set(e.zoom);
          map?.command("flyTo", { zoom: e.zoom, animated: true });
        }}
      />
      <Text>{`zoom ${zoom()}`}</Text>
    </View>
  );
}

mount(App);
"#;

fn start(app: &str) -> (Engine, Receiver<MountBatch>) {
    start_with(app, None)
}

fn start_with(
    app: &str,
    declared: Option<nsh_core::access::Capabilities>,
) -> (Engine, Receiver<MountBatch>) {
    start_in(app, declared, Default::default())
}

fn start_in(
    app: &str,
    declared: Option<nsh_core::access::Capabilities>,
    environment: nsh_core::platform::Environment,
) -> (Engine, Receiver<MountBatch>) {
    // One directory per app started: the tests run in parallel.
    static STARTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let n = STARTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!("nsh-native-{}-{n}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(&entry, app).unwrap();
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: vec![nsh_base::registry().into()],
    })
    .unwrap();
    let mut app = Bundle::source(bundle.code);
    app.policy.declared = declared;
    let (tx, rx) = crossbeam_channel::unbounded();
    let config = EngineConfig {
        app: nsh_engine::App::Js(app),
        viewport: Size::new(px(320.0), px(480.0)),
        trace: false,
        network: None,
        websocket: None,
        refuse_connections: None,
        filesystem: None,
        assets: None,
        environment,
        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,
    };
    (
        Engine::start(config, || ApproxTextEngine, ChannelSink(tx)).unwrap(),
        rx,
    )
}

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

#[test]
fn props_events_and_commands_cross_as_json() {
    cross_as_json(start(APP));
}

fn cross_as_json((engine, rx): (Engine, Receiver<MountBatch>)) {
    let first = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("first frame");
    let id = first
        .items
        .iter()
        .find_map(|i| match i {
            MountItem::Create {
                id,
                kind: ViewKind::Native,
            } => Some(*id),
            _ => None,
        })
        .expect("a native container");
    assert!(first.items.iter().any(
        |i| matches!(i, MountItem::Component { id: c, name } if *c == id && &**name == "com.example.map")
    ));
    let props: Vec<(String, Option<JsonValue>)> = first
        .items
        .iter()
        .filter_map(|i| match i {
            MountItem::ComponentProps { id: c, props } if *c == id => Some(props.clone()),
            _ => None,
        })
        .flatten()
        .map(|(k, v)| (k.to_string(), v))
        .collect();
    assert!(props.contains(&("center".into(), Some(json!({ "lat": 1.5, "lng": 2 })))));
    assert!(props.contains(&("zoom".into(), Some(json!(3)))));
    // Unset props are not sent.
    assert!(!props.iter().any(|(k, _)| k == "title"));
    assert!(texts(&first).contains(&"zoom 3".to_owned()));

    // The component emits; the handler re-renders and calls a command.
    engine.control().dispatch_event(
        id,
        EventKind::NativeEvent,
        EventPayload::Native {
            name: "regionChange".into(),
            data: json!({ "zoom": 7 }),
        },
    );
    let batch = rx.recv_timeout(Duration::from_secs(5)).expect("a batch");
    assert!(texts(&batch).contains(&"zoom 7".to_owned()));
    assert!(batch.items.iter().any(|i| matches!(
        i,
        MountItem::ComponentProps { id: c, props } if *c == id && props == &[("zoom".into(), Some(json!(7)))]
    )));
    assert!(batch.items.iter().any(|i| matches!(
        i,
        MountItem::Command { id: c, command: Command::Native { name, args } }
            if *c == id && &**name == "flyTo" && *args == json!({ "zoom": 7, "animated": true })
    )));
}

const ANIMATED_APP: &str = r#"import { mount, signal, View } from "nsh";
import { createAnimatedValue } from "nsh";
import { nativeComponent } from "nsh";

const Thing = nativeComponent<{ progress?: number }, { mode: { animated: boolean; tick: number } }>(
  "com.example.thing",
  { props: ["progress"], events: ["mode"] },
);

function App() {
  const v = createAnimatedValue(36);
  const animated = signal(true);
  const tick = signal(0);
  return (
    <View>
      <Thing
        progress={(tick(), animated() ? v.interpolate({ inputRange: [0, 72], outputRange: [0, 1] }) : 0.3)}
        style={{ height: 100 }}
        onMode={(e: { animated: boolean; tick: number }) => {
          tick.set(e.tick);
          animated.set(e.animated);
        }}
      />
    </View>
  );
}

mount(App);
"#;

fn native_id(batch: &MountBatch) -> u32 {
    batch
        .items
        .iter()
        .find_map(|i| match i {
            MountItem::Create {
                id,
                kind: ViewKind::Native,
            } => Some(*id),
            _ => None,
        })
        .expect("a native container")
}

fn component_props(batch: &MountBatch, id: u32) -> Vec<(String, Option<JsonValue>)> {
    batch
        .items
        .iter()
        .filter_map(|i| match i {
            MountItem::ComponentProps { id: c, props } if *c == id => Some(props.clone()),
            _ => None,
        })
        .flatten()
        .map(|(k, v)| (k.to_string(), v))
        .collect()
}

fn bound_slots(batch: &MountBatch, id: u32) -> Option<Vec<nsh_core::animation::AnimationProp>> {
    batch.items.iter().rev().find_map(|i| match i {
        MountItem::AnimationBindings { id: c, bindings } if *c == id => {
            Some(bindings.iter().map(|(p, _)| *p).collect())
        }
        _ => None,
    })
}

fn set_mode(engine: &Engine, id: u32, animated: bool, tick: u32) {
    engine.control().dispatch_event(
        id,
        EventKind::NativeEvent,
        EventPayload::Native {
            name: "mode".into(),
            data: json!({ "animated": animated, "tick": tick }),
        },
    );
}

#[test]
fn animated_props_bind_instead_of_crossing_as_json() {
    let (engine, rx) = start(ANIMATED_APP);
    let first = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("first frame");
    let id = native_id(&first);
    assert!(first.items.iter().any(|i| matches!(
        i,
        MountItem::ComponentPropSlots { id: c, names } if *c == id && names.len() == 1 && &*names[0] == "progress"
    )));
    assert_eq!(
        bound_slots(&first, id),
        Some(vec![nsh_core::animation::AnimationProp::ComponentSlot(0)])
    );
    // Never as `{ "__av": n }`.
    assert!(
        component_props(&first, id)
            .iter()
            .all(|(k, _)| k != "progress")
    );

    // A plain number again: sent as JSON, the slot unbound.
    set_mode(&engine, id, false, 1);
    let batch = rx.recv_timeout(Duration::from_secs(5)).expect("a batch");
    assert_eq!(
        component_props(&batch, id),
        vec![("progress".to_owned(), Some(json!(0.3)))]
    );
    assert_eq!(bound_slots(&batch, id), Some(vec![]));
}

#[test]
fn animated_component_prop_survives_rerender() {
    let (engine, rx) = start(ANIMATED_APP);
    let first = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("first frame");
    let id = native_id(&first);
    // The prop is read again; the same interpolation is the same node.
    set_mode(&engine, id, true, 1);
    if let Ok(batch) = rx.recv_timeout(Duration::from_secs(2)) {
        assert!(
            !batch.items.iter().any(|i| matches!(
                i,
                MountItem::AnimationBindings { id: c, .. } | MountItem::ComponentPropSlots { id: c, .. } if *c == id
            )),
            "{:?}",
            batch.items
        );
    }
}

const WEB_INPUT_APP: &str = r#"import { mount, View, WebView } from "nsh";

function App() {
  return (
    <View>
      <WebView
        src="https://example.com/"
        style={{ height: 100 }}
        ref={(page: any) =>
          page &&
          queueMicrotask(() => {
            page.sendInput({ type: "click", x: 12.5, y: 40 });
            page.sendInput({ type: "text", text: "a b!" });
            page.sendInput({ type: "key", key: "Enter" });
            // Not one of its forms: nothing is sent.
            page.sendInput({ type: "key", key: "F13" });
            page.sendInput({ type: "click", x: 1 });
          })
        }
      />
    </View>
  );
}

mount(App);
"#;

/// The web view's id and the input the app sent it, within `wait`.
fn sent_input(
    declared: Option<nsh_core::access::Capabilities>,
    wait: Duration,
) -> (
    nsh_core::NodeId,
    Vec<(nsh_core::NodeId, nsh_core::WebInput)>,
) {
    let (_engine, rx) = start_with(WEB_INPUT_APP, declared);
    let mut web = None;
    let mut sent = Vec::new();
    let deadline = std::time::Instant::now() + wait;
    while sent.len() < 3 && std::time::Instant::now() < deadline {
        let Ok(batch) = rx.recv_timeout(Duration::from_millis(200)) else {
            continue;
        };
        for item in &batch.items {
            match item {
                MountItem::Create {
                    id,
                    kind: ViewKind::WebView,
                } => web = Some(*id),
                MountItem::Command {
                    id,
                    command: Command::SendInput(input),
                } => sent.push((*id, input.clone())),
                _ => {}
            }
        }
    }
    (web.expect("a web view"), sent)
}

#[test]
fn a_web_view_ref_sends_trusted_input_to_its_view() {
    use nsh_core::{WebInput, WebKey, access::Capabilities};
    let declared =
        Capabilities::from_json(&json!({ "webview": { "hosts": ["example.com"], "input": true } }))
            .unwrap();
    let (web, sent) = sent_input(Some(declared), Duration::from_secs(5));
    assert_eq!(
        sent,
        [
            (
                web,
                WebInput::Click {
                    x: nsh_core::Points(12.5),
                    y: nsh_core::Points(40.0)
                }
            ),
            (web, WebInput::Text("a b!".into())),
            (web, WebInput::Key(WebKey::Enter)),
        ]
    );
    // Not declared (also with no declaration at all): the core sends none.
    let hosts =
        Capabilities::from_json(&json!({ "webview": { "hosts": ["example.com"] } })).unwrap();
    for declared in [Some(hosts), None] {
        let (_, sent) = sent_input(declared, Duration::from_secs(1));
        assert_eq!(sent, []);
    }
}

const WEB_INPUT_AVAILABLE_APP: &str = r#"import { mount, signal, Text, WebView } from "nsh";

function App() {
  const available = signal("asking");
  WebView.inputAvailable().then((v: boolean) => available.set(`web input ${v}`));
  return <Text>{available()}</Text>;
}

mount(App);
"#;

/// What `WebView.inputAvailable()` resolves with on a platform that does
/// (`platform`) or does not deliver trusted web input, with the
/// capabilities `declared`.
fn web_input_available(platform: bool, declared: Option<nsh_core::access::Capabilities>) -> String {
    let environment = nsh_core::platform::Environment {
        web_input: platform,
        ..Default::default()
    };
    let (_engine, rx) = start_in(WEB_INPUT_AVAILABLE_APP, declared, environment);
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while std::time::Instant::now() < deadline {
        let Ok(batch) = rx.recv_timeout(Duration::from_millis(200)) else {
            continue;
        };
        if let Some(shown) = texts(&batch)
            .into_iter()
            .find(|t| t.starts_with("web input"))
        {
            return shown;
        }
    }
    panic!("WebView.inputAvailable() did not resolve");
}

#[test]
fn web_view_input_available_needs_the_platform_and_the_grant() {
    use nsh_core::access::Capabilities;
    let granted = || {
        Some(
            Capabilities::from_json(&json!({ "webview": { "hosts": [], "input": true } })).unwrap(),
        )
    };
    assert_eq!(web_input_available(true, granted()), "web input true");
    assert_eq!(web_input_available(false, granted()), "web input false");
    let hosts = Capabilities::from_json(&json!({ "webview": { "hosts": [] } })).unwrap();
    assert_eq!(web_input_available(true, Some(hosts)), "web input false");
    assert_eq!(web_input_available(true, None), "web input false");
}