use std::time::Duration;
use crossbeam_channel::Receiver;
use nsh_core::{
ApproxTextEngine, Command, EventKind, EventPayload, KeyboardAppearance, KeyboardType,
MountBatch, MountItem, PayloadValue, Points, ROOT_ID, Size, StatusBarStyle, geometry::px,
};
use nsh_engine::{Bundle, Edges, Engine, EngineConfig, Environment};
use crate::ChannelSink;
fn start(app: &str) -> (Engine, Receiver<MountBatch>) {
start_in(app, Environment::default())
}
fn start_in(app: &str, environment: Environment) -> (Engine, Receiver<MountBatch>) {
start_with(app, environment, None, None)
}
pub(crate) fn start_with(
app: &str,
environment: Environment,
capabilities: Option<&str>,
config: Option<&str>,
) -> (Engine, Receiver<MountBatch>) {
static APPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"nsh-components-{}-{}",
std::process::id(),
APPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
std::fs::create_dir_all(&dir).unwrap();
let entry = dir.join("App.tsx");
std::fs::write(&entry, app).unwrap();
if let Some(config) = config {
std::fs::write(dir.join("nsh.json"), config).unwrap();
}
let ui_sets = vec![nsh_base::registry(), crate::test_ui::registry()];
let described: Vec<nsh_core::element::description::SetDescription> = ui_sets
.iter()
.flat_map(nsh_core::element::Registry::sets)
.map(Into::into)
.collect();
let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
entry,
minify: false,
split: false,
ui_sets: described.clone(),
})
.unwrap();
let bytecode = nsh_js::compile_bytecode_with(&bundle.code, false, &described).unwrap();
let (tx, rx) = crossbeam_channel::unbounded();
let config = EngineConfig {
app: nsh_engine::App::Js(
unsafe { Bundle::bytecode(bytecode) }
.with_capabilities_json(capabilities)
.unwrap(),
),
viewport: Size::new(px(390.0), px(844.0)),
trace: false,
network: None,
websocket: 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,
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,
};
(
Engine::start(config, || ApproxTextEngine, ChannelSink(tx)).unwrap(),
rx,
)
}
fn text_ids(batch: &MountBatch, wanted: &str) -> Option<u32> {
batch.items.iter().find_map(|i| match i {
MountItem::Text { id, text, .. } if text.text == wanted => Some(*id),
_ => None,
})
}
const INSET: &str = r#"import { mount, signal, Text } from "nsh";
import { ListView } from "test/ui";
const rows = signal(["A", "B", "C"]);
setTimeout(() => rows.update((r) => [...r, "D"]), 0);
mount(() => <ListView variant="inset" each={rows()}>{(row) => <Text>{row()}</Text>}</ListView>);
"#;
#[test]
fn rows_know_whether_they_are_last() {
let (_engine, rx) = start(INSET);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
let parent_of = |batch: &MountBatch, id| {
batch.items.iter().find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == id => Some(*parent),
_ => None,
})
};
let corners = |batch: &MountBatch, id| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewStyle { id: v, style } if *v == id => Some(style.corner_radius),
_ => None,
})
};
let rounded = |c: nsh_core::Corners<Option<nsh_core::Points>>| {
c.to_array().iter().map(|r| r.is_some()).collect::<Vec<_>>()
};
let wrapper = |name| parent_of(&first, text_ids(&first, name).unwrap()).unwrap();
let (a, b, c) = (wrapper("A"), wrapper("B"), wrapper("C"));
assert_eq!(
corners(&first, a).map(rounded),
Some(vec![true, true, false, false])
);
assert_eq!(
corners(&first, b).map(rounded),
Some(vec![false, false, false, false])
);
assert_eq!(
corners(&first, c).map(rounded),
Some(vec![false, false, true, true])
);
let next = rx
.recv_timeout(Duration::from_secs(5))
.expect("the new row");
let d = parent_of(&next, text_ids(&next, "D").expect("D")).unwrap();
assert_eq!(
corners(&next, c).map(rounded),
Some(vec![false, false, false, false])
);
assert_eq!(
corners(&next, d).map(rounded),
Some(vec![false, false, true, true])
);
}
#[test]
fn a_stateful_component_steps_while_held() {
a_stateful_component_steps_while_held_on(start(STEPPER));
}
fn a_stateful_component_steps_while_held_on((engine, rx): (Engine, Receiver<MountBatch>)) {
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(text_ids(&first, "5").is_some(), "the default value");
let plus = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::PressDown) => Some(*id),
_ => None,
})
.nth(1)
.expect("the + button");
let control = engine.control();
control.dispatch_event(plus, EventKind::PressDown, EventPayload::None);
std::thread::sleep(Duration::from_millis(700));
control.dispatch_event(plus, EventKind::PressUp, EventPayload::None);
std::thread::sleep(Duration::from_millis(200));
let mut shown = Vec::new();
while let Ok(batch) = rx.recv_timeout(Duration::from_millis(100)) {
for item in batch.items {
if let MountItem::Text { text, .. } = item {
shown.push(text.text.clone());
}
}
}
let value: f64 = shown
.iter()
.rev()
.find_map(|t| t.parse().ok())
.expect("the value changed");
assert!(value >= 8.0, "held: {value}");
let changes: u32 = shown
.iter()
.rev()
.find_map(|t| t.strip_prefix("changes ")?.parse().ok())
.unwrap();
assert_eq!(changes as f64, value - 5.0, "one onChange per step");
assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
}
pub(crate) fn until(
rx: &Receiver<MountBatch>,
mut done: impl FnMut(&MountBatch) -> bool,
) -> Vec<MountBatch> {
let mut batches = Vec::new();
while let Ok(batch) = rx.recv_timeout(Duration::from_millis(500)) {
let stop = done(&batch);
batches.push(batch);
if stop {
break;
}
}
batches
}
pub(crate) fn shows(batch: &MountBatch, wanted: &str) -> bool {
text_ids(batch, wanted).is_some()
}
const KEYED_CHILDREN: &str = r#"import { mount, signal, Text } from "nsh";
import { Group } from "test/ui";
const items = signal([{ id: "a", label: "A1" }, { id: "b", label: "B1" }]);
// New objects, the same keys: the rows are kept.
setTimeout(() => items.set([{ id: "a", label: "A2" }, { id: "b", label: "B2" }]), 50);
mount(() => (
<Group>
<Each of={items()} key={(i: { id: string }) => i.id}>
{(item) => <Text>{item().label}</Text>}
</Each>
</Group>
));
"#;
#[test]
fn a_components_keyed_children_keep_their_rows() {
let (_engine, rx) = start(KEYED_CHILDREN);
let batches = until(&rx, |b| shows(b, "A2"));
let first = &batches[0];
let a = text_ids(first, "A1").expect("A1 shown");
let last = batches.last().unwrap();
assert_eq!(
text_ids(last, "A2"),
Some(a),
"the row's text is updated in place"
);
let deleted = batches[1..]
.iter()
.flat_map(|b| &b.items)
.any(|i| matches!(i, MountItem::Delete { id } if *id % 2 == 0));
assert!(!deleted, "no row of the app's is made again");
let removed = batches[1..]
.iter()
.flat_map(|b| &b.items)
.any(|i| matches!(i, MountItem::Remove { id } if *id % 2 == 0));
assert!(!removed, "the moved row stays in its wrapper");
}
const LAZY_SHEET: &str = r#"import { mount, signal, untracked, Text } from "nsh";
import { Sheet } from "test/ui";
const open = signal(false);
const count = signal(1);
// Made when the sheet opens: shows the count of that moment.
function Content() {
const at = untracked(() => count());
return <Text>{`opened at ${at}`}</Text>;
}
setTimeout(() => { count.set(3); open.set(true); }, 50);
setTimeout(() => open.set(false), 150);
setTimeout(() => { count.set(5); open.set(true); }, 250);
mount(() => <Sheet open={open()}><Content /></Sheet>);
"#;
#[test]
fn a_sheet_makes_its_content_when_it_opens() {
let (_engine, rx) = start(LAZY_SHEET);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(
!first
.items
.iter()
.any(|i| matches!(i, MountItem::Text { .. })),
"closed: no content"
);
let batches = until(&rx, |b| shows(b, "opened at 3"));
assert!(
batches.iter().any(|b| shows(b, "opened at 3")),
"made on opening"
);
let batches = until(&rx, |b| shows(b, "opened at 5"));
assert!(
batches.iter().any(|b| shows(b, "opened at 5")),
"made again"
);
}
fn status_bars(rx: &Receiver<MountBatch>, count: usize) -> Vec<(StatusBarStyle, bool)> {
let mut configs = Vec::new();
until(rx, |batch| {
for item in &batch.items {
if let MountItem::Command {
id: ROOT_ID,
command: Command::StatusBar(c),
} = item
{
configs.push((c.style, c.hidden));
}
}
configs.len() >= count
});
configs
}
#[test]
fn the_topmost_page_or_dialog_decides_the_status_bar() {
let (_engine, rx) = start(STATUS_BAR);
assert_eq!(
status_bars(&rx, 5),
[
(StatusBarStyle::Dark, false),
(StatusBarStyle::Light, false),
(StatusBarStyle::Light, true),
(StatusBarStyle::Light, false),
(StatusBarStyle::Default, false),
]
);
}
#[test]
fn nsh_json_gives_the_status_bar_its_default() {
let (_engine, rx) = start_with(
STATUS_BAR_DEFAULT,
Environment::default(),
None,
Some(r#"{ "statusBar": { "foreground": "light", "hidden": true } }"#),
);
assert_eq!(
status_bars(&rx, 3),
[
(StatusBarStyle::Light, true),
(StatusBarStyle::Light, false),
(StatusBarStyle::Light, true),
]
);
}
fn frame_of(batches: &[MountBatch], id: u32) -> Option<nsh_core::Bounds<nsh_core::Points>> {
batches.iter().rev().find_map(|b| {
b.items.iter().rev().find_map(|i| match i {
MountItem::Frame { id: f, frame } if *f == id => Some(*frame),
_ => None,
})
})
}
#[test]
fn unhandled_back_presses_go_back_natively() {
unhandled_back_presses_go_back_natively_on(start(BACK));
}
fn unhandled_back_presses_go_back_natively_on((engine, rx): (Engine, Receiver<MountBatch>)) {
until(&rx, |b| shows(b, "presses 0"));
let backs = |batches: &[MountBatch]| {
batches
.iter()
.flat_map(|b| &b.items)
.filter(|i| {
matches!(
i,
MountItem::Command {
id: ROOT_ID,
command: Command::Back
}
)
})
.count()
};
let control = engine.control();
control.dispatch_event(ROOT_ID, EventKind::BackPress, EventPayload::None);
let first = until(&rx, |b| shows(b, "presses 1"));
assert_eq!(backs(&first), 0, "handled");
control.dispatch_event(ROOT_ID, EventKind::BackPress, EventPayload::None);
let second = until(&rx, |b| backs(std::slice::from_ref(b)) > 0);
assert_eq!(
backs(&second),
1,
"not handled: the platform goes back (a stack pops, or the app exits)"
);
}
#[test]
fn a_rust_text_field_clears_after_typing() {
a_rust_text_field_clears_after_typing_on(start(FIELD));
}
fn a_rust_text_field_clears_after_typing_on((engine, rx): (Engine, Receiver<MountBatch>)) {
let first = until(&rx, |b| shows(b, "name Ada"));
let input = first
.iter()
.flat_map(|b| &b.items)
.find_map(|i| match i {
MountItem::Create {
id,
kind: nsh_core::ViewKind::Input,
} => Some(*id),
_ => None,
})
.expect("an input");
let control = engine.control();
for (text, count) in [("Ada G", 1), ("Ada Gr", 2)] {
control.dispatch_event(
input,
EventKind::ChangeText,
EventPayload::Text {
text: text.into(),
count,
},
);
}
until(&rx, |b| shows(b, "name Ada Gr"));
let clear = first
.iter()
.flat_map(|b| &b.items)
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.next_back()
.expect("the clear button");
control.dispatch_event(clear, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| shows(b, "name "));
let value = after.iter().flat_map(|b| &b.items).find_map(|i| match i {
MountItem::InputValue { id, text, count } if *id == input => Some((text.clone(), *count)),
_ => None,
});
assert_eq!(value, Some((String::new(), 2)));
}
#[test]
fn a_sibling_coming_back_does_not_move_a_rust_input() {
a_sibling_coming_back_does_not_move_a_rust_input_on(start(FIELD));
}
fn a_sibling_coming_back_does_not_move_a_rust_input_on(
(engine, rx): (Engine, Receiver<MountBatch>),
) {
let first = until(&rx, |b| shows(b, "name Ada"));
let items = || first.iter().flat_map(|b| &b.items);
let input = items()
.find_map(|i| match i {
MountItem::Create {
id,
kind: nsh_core::ViewKind::Input,
} => Some(*id),
_ => None,
})
.expect("an input");
let clear = items()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.next_back()
.expect("the clear button");
let control = engine.control();
control.dispatch_event(clear, EventKind::Press, EventPayload::None);
until(&rx, |b| shows(b, "name "));
control.dispatch_event(
input,
EventKind::ChangeText,
EventPayload::Text {
text: "x".into(),
count: 1,
},
);
let after = until(&rx, |b| shows(b, "name x"));
let inserts: Vec<_> = after
.iter()
.flat_map(|b| &b.items)
.filter_map(|i| match i {
MountItem::Insert { child, before, .. } => Some((*child, *before)),
_ => None,
})
.collect();
assert!(
inserts.iter().all(|&(child, _)| child != input),
"{inserts:?}"
);
assert!(
inserts.iter().any(|&(_, before)| before.is_none()),
"{inserts:?}"
);
}
const CARD: &str = r#"import { mount, signal, Text } from "nsh";
import { Button, Card } from "test/ui";
function App() {
const titled = signal(true);
return (
<Card
header={<If when={titled()}><Text>Title</Text></If>}
footer={<Button title="Hide title" onPress={() => titled.set(false)} />}
>
<Text>Body</Text>
</Card>
);
}
mount(App);
"#;
#[test]
fn slots_children_and_events() {
let (engine, rx) = start(CARD);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
for wanted in ["Title", "Body", "Hide title"] {
assert!(text_ids(&first, wanted).is_some(), "{wanted} rendered");
}
let parent_of = |id| {
first.items.iter().find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == id => Some(*parent),
_ => None,
})
};
let frame = |id| {
first.items.iter().find_map(|i| match i {
MountItem::Frame { id: f, frame } if *f == id => Some(*frame),
_ => None,
})
};
let title_parent = parent_of(text_ids(&first, "Title").unwrap()).unwrap();
let body_parent = parent_of(text_ids(&first, "Body").unwrap()).unwrap();
assert!(frame(title_parent).unwrap().origin.y.0 < frame(body_parent).unwrap().origin.y.0);
let button = first
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("a pressable button");
engine
.control()
.dispatch_event(button, EventKind::Press, EventPayload::None);
let batch = rx.recv_timeout(Duration::from_secs(5)).expect("a batch");
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == title_parent)),
"{:?}",
batch.items
);
}
const METHODS: &str = r#"import { mount, signal, Text, View } from "nsh";
import { Stepper, type StepperRef } from "test/ui";
const shown = signal("waiting");
let stepper!: StepperRef;
setTimeout(async () => {
let refused = "";
// A method returning nothing is a plain call: `undefined`, and a wrong
// argument throws in the call.
try { (stepper.setValue as any)("x"); refused = "no throw"; } catch (e) { refused = `${e.name}: ${e.message}`; }
const set = stepper.setValue(42.4);
if (set !== undefined) refused = `returned ${set}`;
// One returning a value is a promise, settled after the call before it ran.
const value = await stepper.value();
shown.set(`got ${value} | ${refused}`);
}, 0);
mount(() => (
<View>
<Stepper ref={stepper} defaultValue={1} max={50} />
<Text>{shown()}</Text>
</View>
));
"#;
#[test]
fn calls_of_a_components_methods() {
let (_engine, rx) = start(METHODS);
let mut shown = Vec::new();
while let Ok(batch) = rx.recv_timeout(Duration::from_millis(500)) {
for item in batch.items {
if let MountItem::Text { text, .. } = item {
shown.push(text.text.clone());
}
}
if shown.iter().any(|t| t.starts_with("got")) {
break;
}
}
assert!(shown.contains(&"42".to_owned()), "{shown:?}");
assert!(
shown.contains(
&"got 42 | TypeError: Stepper.setValue: `value`: expected a number, got \"x\""
.to_owned()
),
"{shown:?}"
);
}
const ALERT: &str = r#"import { mount, signal, Text } from "nsh";
import { AlertDialog } from "nsh/base";
const shown = signal("waiting");
setTimeout(async () => {
const a = await AlertDialog.show({
title: "Delete the photo?",
description: "It is gone then.",
actions: [
{ label: "Cancel", role: "cancel" },
{ label: "Delete", role: "destructive", id: "delete" },
],
});
const b = await AlertDialog.show({
presentation: "actionSheet",
actions: [{ label: "Share" }, { label: "Copy" }],
});
const c = await AlertDialog.show({ actions: [{ label: "OK" }], closeOnEscape: true });
let d = "resolved";
try {
await AlertDialog.show({ actions: [] });
} catch (e) {
d = "rejected";
}
shown.set(`answers ${a} ${b} ${c} ${d}`);
}, 0);
mount(() => <Text>{shown()}</Text>);
"#;
#[test]
fn alert_dialogs_resolve_with_the_action_chosen() {
let (engine, rx) = start(ALERT);
let next_dialog = || {
let mut dialog = None;
until(&rx, |batch| {
dialog = dialog.take().or_else(|| {
batch.items.iter().find_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command: Command::Dialog(d),
} => Some(d.clone()),
_ => None,
})
});
dialog.is_some()
});
dialog.expect("a dialog")
};
let answer = |dialog: &nsh_core::Dialog, index: f64| {
engine.control().dispatch_event(
ROOT_ID,
EventKind::Dialog,
EventPayload::Map(vec![
("id", PayloadValue::Number(dialog.id as f64)),
("index", PayloadValue::Number(index)),
]),
);
};
let alert = next_dialog();
assert_eq!(alert.title.as_deref(), Some("Delete the photo?"));
assert_eq!(alert.message.as_deref(), Some("It is gone then."));
assert!(!alert.sheet && !alert.cancelable);
assert_eq!(
alert.buttons[1].style,
nsh_core::DialogButtonStyle::Destructive
);
answer(&alert, 1.0);
let sheet = next_dialog();
assert!(sheet.sheet && sheet.cancelable);
answer(&sheet, 0.0);
let ok = next_dialog();
assert!(ok.cancelable);
answer(&ok, -1.0);
let batches = until(&rx, |b| shows(b, "answers delete Share null rejected"));
assert!(
batches
.iter()
.any(|b| shows(b, "answers delete Share null rejected"))
);
}
const SAFE_AREA: &str = r#"import { mount, Text, View } from "nsh";
import { safeArea } from "nsh";
mount(() => (
<View style={{ flex: 1, marginBottom: "env(keyboard-inset-height)" }}>
<View
style={{
flex: 1,
padding: 4,
paddingTop: "calc(env(safe-area-inset-top) + 4px)",
paddingBottom: "calc(env(safe-area-inset-bottom) + 4px)",
}}
>
<Text>inside</Text>
<Text>{`top ${safeArea().top}`}</Text>
</View>
</View>
));
"#;
#[test]
fn safe_area_and_keyboard_env_insets() {
let environment = Environment {
window: Size::new(px(390.0), px(844.0)),
safe_area: Edges {
top: Points(47.0),
right: Points(10.0),
bottom: Points(34.0),
left: Points(10.0),
},
..Default::default()
};
let (engine, rx) = start_in(SAFE_AREA, environment);
let first = until(&rx, |b| shows(b, "inside"));
let text = first
.iter()
.find_map(|b| text_ids(b, "inside"))
.expect("the text");
let frame = frame_of(&first, text).expect("laid out");
assert_eq!((frame.origin.x.0, frame.origin.y.0), (4.0, 51.0));
assert!(
first.iter().any(|b| shows(b, "top 47")),
"the environment's accessor"
);
engine.control().set_environment(Environment {
keyboard_height: px(300.0),
safe_area: Edges {
top: Points(20.0),
..environment.safe_area
},
..environment
});
let after = until(&rx, |b| shows(b, "top 20"));
assert!(
after.iter().any(|b| shows(b, "top 20")),
"the accessor follows"
);
assert!(
after.iter().flat_map(|b| &b.items).any(
|i| matches!(i, MountItem::Frame { frame, .. } if frame.size.height.0 == 844.0 - 300.0)
),
"the view above the keyboard"
);
}
const RUNTIME_MODULES: &str = r#"import { mount, signal, Text } from "nsh";
import { reduceMotion, setAccessibilityFocus } from "nsh";
import { platform } from "nsh";
import { Image } from "nsh";
const shown = signal("waiting");
let note: unknown;
setTimeout(async () => {
setAccessibilityFocus(note);
const size = await Image.getSize("https://example.com/a.png");
let failed = "no";
try {
await Image.getSize("https://example.com/missing.png");
} catch (e) {
failed = String((e as Error).message);
}
shown.set(`${size.width}x${size.height} ${failed} ${platform.os} ${reduceMotion()}`);
}, 0);
mount(() => <Text ref={note}>{shown()}</Text>);
"#;
#[test]
fn runtime_modules() {
let (engine, rx) = start(RUNTIME_MODULES);
let note = rx
.recv_timeout(Duration::from_secs(5))
.ok()
.and_then(|b| text_ids(&b, "waiting"))
.expect("first frame");
let mut focused = None;
let mut requests = Vec::new();
let control = engine.control();
until(&rx, |batch| {
for item in &batch.items {
match item {
MountItem::Command {
id,
command: Command::AccessibilityFocus,
} => focused = Some(*id),
MountItem::Command {
id: ROOT_ID,
command: Command::ImageInfo { id, uri },
} => {
requests.push(uri.clone());
let payload = if requests.len() == 1 {
vec![
("id", PayloadValue::Number(*id as f64)),
("width", PayloadValue::Number(640.0)),
("height", PayloadValue::Number(480.0)),
]
} else {
vec![
("id", PayloadValue::Number(*id as f64)),
("error", PayloadValue::Str("not found".into())),
]
};
control.dispatch_event(
ROOT_ID,
EventKind::ImageInfo,
EventPayload::Map(payload),
);
}
_ => {}
}
}
shows(batch, "640x480 not found ios false")
});
assert_eq!(focused, Some(note));
}
const MEASURE: &str = r#"import { mount, signal, Scroll, Text, View, type YNode } from "nsh";
const shown = signal("waiting");
let box!: YNode;
let ghost!: YNode;
const detached = <View ref={(n: YNode) => (ghost = n)} />;
setTimeout(async () => {
const m = (await box.measure())!;
const none = await ghost.measure();
const b = m.bounds;
shown.set(`at ${b.origin.x},${b.origin.y} ${b.size.width}x${b.size.height} page ${m.pagePosition.x},${m.pagePosition.y} ${none}`);
}, 0);
mount(() => (
<View>
<Text>{shown()}</Text>
<Scroll
style={{ marginTop: 50, height: 300 }}
onScroll={async () => shown.set(`scrolled ${(await box.measure())!.pagePosition.y}`)}
>
<View style={{ padding: 20, height: 1000 }}>
<View ref={box} style={{ marginTop: 500, height: 30 }} />
</View>
</Scroll>
</View>
));
void detached;
"#;
#[test]
fn measure_reports_frames_and_page_positions() {
let (engine, rx) = start(MEASURE);
let mut scroll = None;
let batches = until(&rx, |batch| {
for item in &batch.items {
if let MountItem::Create {
id,
kind: nsh_core::ViewKind::Scroll,
} = item
{
scroll = Some(*id);
}
}
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Text { text, .. } if text.text.starts_with("at ")))
});
let shown: Vec<_> = batches
.iter()
.flat_map(|b| &b.items)
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.to_string()),
_ => None,
})
.collect();
assert!(
shown
.iter()
.any(|t| t == "at 20,520 350x30 page 20,587 null"),
"{shown:?}"
);
engine.control().scroll(
scroll.expect("scroll view"),
nsh_core::geometry::point(nsh_core::geometry::px(0.0), nsh_core::geometry::px(400.0)),
0,
);
let after = until(&rx, |b| shows(b, "scrolled 187"));
assert!(after.iter().any(|b| shows(b, "scrolled 187")));
}
const CLIPBOARD: &str = r#"import { mount, signal, Text } from "nsh";
import { Clipboard } from "nsh";
const shown = signal("waiting");
setTimeout(async () => {
const before = await Clipboard.hasText();
Clipboard.writeText("copied");
const has = await Clipboard.hasText();
const text = await Clipboard.readText();
shown.set(`${before} ${has} ${text}`);
}, 0);
mount(() => <Text>{shown()}</Text>);
"#;
fn serve_clipboard(engine: &Engine, rx: &Receiver<MountBatch>, wanted: &str) -> Vec<Command> {
let control = engine.control();
let mut board: Option<String> = None;
let mut commands = Vec::new();
until(rx, |batch| {
for item in &batch.items {
let MountItem::Command {
id: ROOT_ID,
command,
} = item
else {
continue;
};
match command {
Command::SetClipboard(text) => board = Some(text.clone()),
Command::ReadClipboard { id, has_only } => {
let mut payload = vec![
("id", PayloadValue::Number(*id as f64)),
("has", PayloadValue::Bool(board.is_some())),
];
if let (false, Some(text)) = (has_only, &board) {
payload.push(("text", PayloadValue::Str(text.clone())));
}
control.dispatch_event(
ROOT_ID,
EventKind::Clipboard,
EventPayload::Map(payload),
);
}
_ => continue,
}
commands.push(command.clone());
}
shows(batch, wanted)
});
commands
}
#[test]
fn the_clipboard_round_trips_through_the_platform() {
let (engine, rx) = start(CLIPBOARD);
let commands = serve_clipboard(&engine, &rx, "false true copied");
assert_eq!(
commands,
[
Command::ReadClipboard {
id: 1,
has_only: true
},
Command::SetClipboard("copied".into()),
Command::ReadClipboard {
id: 2,
has_only: true
},
Command::ReadClipboard {
id: 3,
has_only: false
},
]
);
}
#[test]
fn the_clipboard_needs_its_capability() {
let (engine, rx) = start_with(CLIPBOARD, Environment::default(), Some("{}"), None);
let commands = serve_clipboard(&engine, &rx, "false false ");
assert!(commands.is_empty(), "{commands:?}");
let (engine, rx) = start_with(
CLIPBOARD,
Environment::default(),
Some(r#"{ "clipboard": true }"#),
None,
);
serve_clipboard(&engine, &rx, "false true copied");
}
const CLIPBOARD_IMAGE: &str = r#"import { mount, signal, Text } from "nsh";
import { Clipboard } from "nsh";
const shown = signal("waiting");
setTimeout(async () => {
const before = await Clipboard.hasImage();
Clipboard.writeImage("data:image/png;base64,aGk=");
const image = await Clipboard.readImage();
const bytes = new Uint8Array(await (await fetch(image!.url)).arrayBuffer());
const files = await Clipboard.readFiles();
shown.set(`${before} ${image!.size.width}x${image!.size.height} ${bytes.join(",")} ${files.join(" ")}`);
}, 0);
mount(() => <Text>{shown()}</Text>);
"#;
#[test]
fn clipboard_images_and_files_reach_js() {
let (engine, rx) = start(CLIPBOARD_IMAGE);
let control = engine.control();
let mut board: Option<String> = None;
let mut commands = Vec::new();
until(&rx, |batch| {
for item in &batch.items {
let MountItem::Command {
id: ROOT_ID,
command,
} = item
else {
continue;
};
let payload = match command {
Command::SetClipboardImage(uri) => {
board = Some(uri.clone());
None
}
Command::ReadClipboardImage { id, has_only } => {
let mut payload = vec![
("id", PayloadValue::Number(*id as f64)),
("has", PayloadValue::Bool(board.is_some())),
];
if let (false, Some(uri)) = (has_only, &board) {
payload.push(("uri", PayloadValue::Str(uri.clone())));
payload.push(("width", PayloadValue::Number(2.0)));
payload.push(("height", PayloadValue::Number(1.0)));
}
Some(payload)
}
Command::ReadClipboardFiles { id } => Some(vec![
("id", PayloadValue::Number(*id as f64)),
("has", PayloadValue::Bool(true)),
(
"files",
PayloadValue::Str("file:///tmp/a%20b.txt\nfile:///tmp/c/".into()),
),
]),
_ => continue,
};
if let Some(payload) = payload {
control.dispatch_event(ROOT_ID, EventKind::Clipboard, EventPayload::Map(payload));
}
commands.push(command.clone());
}
shows(
batch,
"false 2x1 104,105 file:///tmp/a%20b.txt file:///tmp/c/",
)
});
assert_eq!(
commands,
[
Command::ReadClipboardImage {
id: 1,
has_only: true
},
Command::SetClipboardImage("data:image/png;base64,aGk=".into()),
Command::ReadClipboardImage {
id: 2,
has_only: false
},
Command::ReadClipboardFiles { id: 3 },
]
);
}
const PICKER: &str = r#"import { mount, signal, Text } from "nsh";
import { Picker } from "nsh";
const shown = signal("");
setTimeout(async () => {
const images = await Picker.pickImages({ multiple: true, limit: 3, maxDimension: 1024 });
const [{ file, size }] = images;
const bytes = await file.bytes();
const url = URL.createObjectURL(file);
shown.set(
`${images.length} ${file instanceof File} ${file.name} ${file.type} ${file.size} ${size.width}x${size.height} ${bytes.slice(1, 4).join(",")} ${url.startsWith("blob:")} ${file.lastModified}`,
);
}, 0);
mount(() => <Text>{shown()}</Text>);
"#;
#[test]
fn picked_images_reach_js_as_files() {
let (engine, rx) = start(PICKER);
let control = engine.control();
let mut asked = None;
until(&rx, |batch| {
for item in &batch.items {
if let MountItem::Command {
id: ROOT_ID,
command: Command::PickImages { id, request },
} = item
{
asked = Some(*request);
let mut file = nsh_core::picker::PickedFile::new(
"IMG_0042.HEIC",
"image/jpeg",
nsh_core::ImageData::new(vec![0xff, 0xd8, 0xff, 0xe0, 0, 0]),
);
file.size = Size::new(
nsh_core::geometry::DevicePixels(1024),
nsh_core::geometry::DevicePixels(768),
);
file.last_modified = Some(
std::time::UNIX_EPOCH + std::time::Duration::from_millis(1_700_000_000_000),
);
control.dispatch_event(
ROOT_ID,
EventKind::Pick,
EventPayload::Picked {
id: *id,
files: vec![file],
},
);
}
}
shows(
batch,
"1 true IMG_0042.jpg image/jpeg 6 1024x768 216,255,224 true 1700000000000",
)
});
let asked = asked.expect("a pick");
assert_eq!(asked.limit, 3);
assert_eq!(
asked.max_dimension,
Some(nsh_core::geometry::DevicePixels(1024))
);
}
const INPUT_TRAITS: &str = r##"import { mount, Text } from "nsh";
import { Input } from "nsh/base";
mount(() => (
<>
<Input keyboardType="numeric" ios={{ keyboardAppearance: "dark" }} />
<Input
keyboardType="numbers-and-punctuation"
masked
readonly
multiline
style={{ placeholderColor: "#00ff00", selectionColor: "#0000ff" }}
/>
<Input class="placeholder:text-white selection:bg-black" />
<Text selectable style={{ selectionColor: "#ff0000" }}>Pick me</Text>
</>
));
"##;
#[test]
fn inputs_and_selectable_text_carry_their_traits() {
let (_engine, rx) = start(INPUT_TRAITS);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
let inputs: Vec<_> = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Input { config, .. } => Some(config.clone()),
_ => None,
})
.collect();
let traits: Vec<_> = inputs
.iter()
.map(|c| (c.keyboard, c.keyboard_appearance))
.collect();
assert_eq!(
traits,
[
(KeyboardType::Numeric, KeyboardAppearance::Dark),
(
KeyboardType::NumbersAndPunctuation,
KeyboardAppearance::Default
),
(KeyboardType::Default, KeyboardAppearance::Default),
]
);
let c = &inputs[1];
assert!(c.secure && !c.editable && c.multiline);
assert_eq!(c.placeholder_color, nsh_core::Color::parse("#00ff00"));
assert_eq!(c.selection_color, nsh_core::Color::parse("#0000ff"));
assert!(!inputs[0].secure && inputs[0].editable && inputs[0].placeholder_color.is_none());
assert_eq!(
inputs[2].placeholder_color,
nsh_core::Color::parse("#ffffff")
);
assert_eq!(inputs[2].selection_color, nsh_core::Color::parse("#000000"));
let text = first
.items
.iter()
.find_map(|i| match i {
MountItem::Text { text, .. } if text.text == "Pick me" => Some(text.clone()),
_ => None,
})
.expect("the text");
assert!(text.is_selectable());
assert_eq!(
text.selection_color,
Some(nsh_core::Color::rgba(255, 0, 0, 255))
);
}
const ROWS: &str = r#"import { mount, Text } from "nsh";
import { Group, ListView } from "test/ui";
const rows = Array.from({ length: 100 }, (_, i) => ({ id: i, label: `Row ${i}` }));
mount(() => (
<ListView
each={rows}
header={() => (
<Group>
<Text>First</Text>
<Text>Second</Text>
</Group>
)}
>
{(row) => <Text>{row().label}</Text>}
</ListView>
));
"#;
#[test]
fn components_place_the_apps_children_and_rows() {
let (_engine, rx) = start(ROWS);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
let parent_of = |id| {
first.items.iter().find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == id => Some(*parent),
_ => None,
})
};
let frame = |id| {
first.items.iter().find_map(|i| match i {
MountItem::Frame { id: f, frame } if *f == id => Some(*frame),
_ => None,
})
};
let top_border = |id| {
first.items.iter().any(|i| {
matches!(i, MountItem::ViewStyle { id: v, style } if *v == id && style.borders.widths.top.0 == 1.0)
})
};
let a = parent_of(text_ids(&first, "First").expect("First")).unwrap();
let b = parent_of(text_ids(&first, "Second").expect("Second")).unwrap();
assert!(a % 2 == 1 && b % 2 == 1 && a != b);
assert!(!top_border(a) && top_border(b));
let row0 = parent_of(text_ids(&first, "Row 0").expect("Row 0")).unwrap();
let row1 = parent_of(text_ids(&first, "Row 1").expect("Row 1")).unwrap();
assert!(row0 % 2 == 1 && row1 % 2 == 1);
assert_eq!(
frame(text_ids(&first, "Row 0").unwrap()).map(|f| f.origin.x.0),
Some(16.0)
);
assert!(!top_border(row0) && top_border(row1));
assert!(text_ids(&first, "Row 99").is_none());
}
const STEPPER: &str = r#"import { mount, signal, Text, View } from "nsh";
import { Stepper } from "test/ui";
const changes = signal(0);
mount(() => (
<View>
<Stepper defaultValue={5} min={0} max={100} onChange={() => changes.update((c) => c + 1)} />
<Text>{`changes ${changes()}`}</Text>
</View>
));
"#;
const STATUS_BAR: &str = r##"import { signal, mount, View } from "nsh";
import { Dialog, NavPage, NavStack, createNavStack } from "nsh/base";
type Route = { name: string };
const nav = createNavStack<Route>([{ name: "home" }]);
const home = signal<"auto" | "dark">("dark");
const open = signal(false);
setTimeout(() => nav.push({ name: "detail" }), 30);
setTimeout(() => home.set("auto"), 50);
setTimeout(() => open.set(true), 70);
setTimeout(() => open.set(false), 100);
setTimeout(() => nav.pop(), 130);
mount(() => (
<View style={{ flex: 1 }}>
<NavStack state={nav} style={{ flex: 1 }}>
{(route) => (
<NavPage
title={route.name}
statusBar={route.name === "home" ? { foreground: home() } : { foreground: "light" }}
>
<View />
</NavPage>
)}
</NavStack>
<Dialog open={open()} statusBar={{ hidden: true }}>
<View />
</Dialog>
</View>
));
"##;
const STATUS_BAR_DEFAULT: &str = r##"import { signal, mount, View } from "nsh";
import { Dialog } from "nsh/base";
const open = signal(false);
setTimeout(() => open.set(true), 30);
setTimeout(() => open.set(false), 60);
mount(() => (
<View>
<Dialog open={open()} statusBar={{ hidden: false }}>
<View />
</Dialog>
</View>
));
"##;
const BACK: &str = r#"import { mount, signal, Text } from "nsh";
import { BackHandler } from "nsh/mobile";
const presses = signal(0);
BackHandler.onBackPress(() => {
presses.update((p) => p + 1);
// The first press is handled, the second one leaves the app.
return presses() === 1;
});
mount(() => <Text>{`presses ${presses()}`}</Text>);
"#;
const FIELD: &str = r#"import { mount, signal, Text, View } from "nsh";
import { TextField } from "test/ui";
const name = signal("Ada");
mount(() => (
<View>
<TextField value={name()} onChange={(v: string) => name.set(v)} />
<Text>{`name ${name()}`}</Text>
</View>
));
"#;
const APPEARANCE: &str = r#"import { mount, Text, View } from "nsh";
import { colorScheme, setColorScheme } from "nsh";
setTimeout(() => setColorScheme("light"), 20);
mount(() => (
<View class="bg-white dark:bg-black">
<Text>{`scheme ${colorScheme()}`}</Text>
</View>
));
"#;
#[test]
fn the_apps_appearance_overrides_the_systems() {
let (_engine, rx) = start_with(
APPEARANCE,
Environment::default(),
None,
Some(r#"{ "appearance": "dark" }"#),
);
let background = |batches: &[MountBatch]| {
batches
.iter()
.flat_map(|b| &b.items)
.rev()
.find_map(|i| match i {
MountItem::ViewStyle { style, .. } if style.background_color.0 & 0xff == 0xff => {
Some(style.background_color)
}
_ => None,
})
};
let first = until(&rx, |b| shows(b, "scheme dark"));
assert!(first.iter().any(|b| shows(b, "scheme dark")));
assert_eq!(background(&first), Some(nsh_core::Color(0x0000_00ff)));
assert!(first.iter().flat_map(|b| &b.items).any(|i| matches!(
i,
MountItem::Appearance {
appearance: nsh_core::platform::Appearance::Dark
}
)));
let later = until(&rx, |b| shows(b, "scheme light"));
assert!(later.iter().any(|b| shows(b, "scheme light")), "{later:?}");
assert_eq!(background(&later), Some(nsh_core::Color(0xffff_ffff)));
}
const TOKENS: &str = r#"import { mount, Text, token } from "nsh";
mount(() => (
<Text>{`up ${token("up")} radius ${token("radius")} font ${token("font-sans")} primary ${token("primary") !== undefined}`}</Text>
));
"#;
#[test]
fn token_reads_the_apps_theme_in_the_appearance_shown() {
let shown = |appearance: &str| {
let config = format!(
r##"{{ "appearance": "{appearance}", "theme": {{ "cssVars": {{
"theme": {{ "font-sans": "Inter, sans-serif", "radius": "0.5rem" }},
"light": {{ "up": "#00ff00" }}, "dark": {{ "up": "#004400" }} }} }} }}"##
);
let (_engine, rx) = start_with(TOKENS, Environment::default(), None, Some(&config));
let up = if appearance == "dark" {
"#004400ff"
} else {
"#00ff00ff"
};
let wanted = format!("up {up} radius 8 font Inter primary true");
let batches = until(&rx, |b| shows(b, &wanted));
assert!(batches.iter().any(|b| shows(b, &wanted)), "{batches:?}");
};
shown("light");
shown("dark");
}
const MENU: &str = r#"import { mount, signal, Text } from "nsh";
import { Menu } from "nsh/desktop";
const chosen = signal("none");
Menu.setApplicationMenu([
false,
{
label: "File",
submenu: [
{ label: "New", shortcut: "mod+n", onSelect: () => chosen.set("new") },
{ type: "separator" },
{ role: "quit" },
],
},
]);
Menu.popup([{ label: "Copy link", onSelect: () => chosen.set("copied") }]).then(() =>
chosen.set(`${chosen()} closed`),
);
mount(() => <Text>{chosen()}</Text>);
"#;
#[test]
fn menus_reach_the_platform_and_call_back() {
use nsh_core::desktop::{DesktopCommand, Key, MenuAction, MenuItem, MenuRole, Shortcut};
let (engine, rx) = start_in(
MENU,
Environment {
os: nsh_engine::Os::Windows,
..Environment::default()
},
);
let mut menu = None;
until(&rx, |batch| {
for item in &batch.items {
if let MountItem::Command {
id: ROOT_ID,
command: Command::Desktop(command),
} = item
&& let DesktopCommand::SetMenu(Some(items)) = &**command
{
menu = Some(items.clone());
}
}
shows(batch, "none")
});
let menu = menu.expect("the menu");
let new = MenuAction {
id: 1,
label: "New".into(),
shortcut: Some(Shortcut {
ctrl: true,
..Shortcut::key(Key::Char('n'))
}),
enabled: true,
checked: None,
role: None,
when: nsh_core::keymap::When::Always,
};
let quit = MenuAction {
id: 0,
label: String::new(),
shortcut: MenuRole::Quit.shortcut(false),
enabled: true,
checked: None,
role: Some(MenuRole::Quit),
when: nsh_core::keymap::When::Always,
};
assert_eq!(
&*menu,
[MenuItem::Submenu {
label: "File".into(),
enabled: true,
items: vec![
MenuItem::Action(new),
MenuItem::Separator,
MenuItem::Action(quit)
],
}]
);
engine.control().dispatch_event(
ROOT_ID,
EventKind::Menu,
EventPayload::Map(vec![("id", PayloadValue::Number(1.0))]),
);
assert!(
until(&rx, |batch| shows(batch, "new"))
.iter()
.any(|b| shows(b, "new"))
);
let control = engine.control();
control.dispatch_event(
ROOT_ID,
EventKind::Menu,
EventPayload::Map(vec![("id", PayloadValue::Number(2.0))]),
);
control.dispatch_event(
ROOT_ID,
EventKind::Menu,
EventPayload::Map(vec![
("id", PayloadValue::Number(0.0)),
("closed", PayloadValue::Bool(true)),
]),
);
assert!(
until(&rx, |batch| shows(batch, "copied closed"))
.iter()
.any(|b| shows(b, "copied closed"))
);
let (_engine, rx) = start(MENU);
let batches = until(&rx, |batch| shows(batch, "none"));
assert!(!batches.iter().flat_map(|b| &b.items).any(|i| matches!(
i,
MountItem::Command {
command: Command::Desktop(_),
..
}
)));
}
const LOCALE: &str = r#"import { mount, Text } from "nsh";
import { fontScale, locale } from "nsh";
mount(() => (
<Text>{`${locale()} ${new Intl.NumberFormat().format(1234.5)} ${fontScale()}`}</Text>
));
"#;
#[test]
fn locale_and_font_scale_follow_the_environment() {
let (engine, rx) = start(LOCALE);
let first = until(&rx, |b| shows(b, "en-US 1,234.5 1"));
assert!(first.iter().any(|b| shows(b, "en-US 1,234.5 1")));
let mut environment = Environment::default();
nsh_engine::HostEnvironment {
locale: nsh_engine::Locale::parse("de-DE"),
font_scale: Some(1.5),
}
.apply(&mut environment);
engine.control().set_environment(environment);
let after = until(&rx, |b| shows(b, "de-DE 1.234,5 1.5"));
assert!(after.iter().any(|b| shows(b, "de-DE 1.234,5 1.5")));
}
const BASE_BUTTON: &str = r#"import { mount, signal, Text } from "nsh";
import { Button } from "nsh/base";
function App() {
const count = signal(0);
return (
<Button selected={count() > 0} onPress={() => count.update((n) => n + 1)}>
<Text>{`Pressed ${count()}`}</Text>
</Button>
);
}
mount(App);
"#;
#[test]
fn a_base_button_has_behavior_and_no_look() {
let (engine, rx) = start(BASE_BUTTON);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(text_ids(&first, "Pressed 0").is_some());
let button = first
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("a pressable button");
assert!(
!first
.items
.iter()
.any(|i| matches!(i, MountItem::ViewStyle { id, .. } if *id == button)),
"no style of its own: {:?}",
first.items
);
let props = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == button => Some(props.clone()),
_ => None,
})
};
let first_props = props(&first).expect("its props");
assert_eq!(
first_props.accessibility.role,
nsh_core::AccessibilityRole::Button
);
assert!(!first_props.accessibility.state.selected);
engine
.control()
.dispatch_event(button, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| shows(b, "Pressed 1"));
let selected = after.iter().rev().find_map(props).expect("new props");
assert!(
selected.accessibility.state.selected,
"selected follows the app"
);
}
const BASE_SWITCH: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Switch } from "nsh/base";
function App() {
const on = signal(false);
const changes = signal<boolean[]>([]);
const parts = {
trackClass: "w-[20px] checked:bg-[#00ff00]",
thumbClass: "w-[10px] checked:translate-x-[6px] disabled:opacity-50",
};
return (
<View>
<Switch
testID="wifi"
checked={on()}
checkedStyle={{ backgroundColor: "#0000ff" }}
onChange={(next) => {
changes.set([...changes(), next]);
on.set(next);
}}
{...parts}
>
<Text>Wi-Fi</Text>
</Switch>
<Switch
testID="locked"
checked
accessibilityLabel="Locked"
onChange={(next) => changes.set([...changes(), next])}
{...parts}
/>
<Switch testID="off" checked disabled {...parts} />
<Text>{`Changes: ${changes().join(",")}`}</Text>
</View>
);
}
mount(App);
"##;
#[test]
fn a_base_switch_reports_the_next_value_and_styles_its_parts() {
use nsh_core::{AccessibilityRole, Checked, ViewProps};
let (engine, rx) = start(BASE_SWITCH);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(shows(&first, "Changes: "));
let view_props = |batch: &MountBatch, view| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == view => Some(props.clone()),
_ => None,
})
};
let root = |test_id: &str| {
first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect(test_id)
};
let child = |parent: u32| {
let views: Vec<u32> = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Create {
id,
kind: nsh_core::ViewKind::View,
} => Some(*id),
_ => None,
})
.collect();
first
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent: p, child, ..
} if *p == parent && views.contains(child) => Some(*child),
_ => None,
})
.expect("a part")
};
let (wifi, locked, off) = (root("wifi"), root("locked"), root("off"));
let (track, thumb) = (child(wifi), child(child(wifi)));
let style = |batches: &[MountBatch], view| {
batches
.iter()
.rev()
.flat_map(|b| b.items.iter().rev())
.find_map(|i| match i {
MountItem::ViewStyle { id, style } if *id == view => Some(style.clone()),
_ => None,
})
.unwrap_or_default()
};
let state = |props: &ViewProps| props.accessibility.state;
let props = view_props(&first, wifi).unwrap();
assert_eq!(props.accessibility.role, AccessibilityRole::Switch);
assert_eq!(state(&props).checked, Some(Checked::False));
assert!(view_props(&first, track).is_none());
assert!(view_props(&first, thumb).is_none());
assert_eq!(
view_props(&first, locked)
.unwrap()
.accessibility
.label
.as_deref(),
Some("Locked")
);
let unchecked = std::slice::from_ref(&first);
assert!(style(unchecked, thumb).transform.ops().is_empty());
engine
.control()
.dispatch_event(wifi, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| shows(b, "Changes: true"));
let props = after
.iter()
.rev()
.find_map(|b| view_props(b, wifi))
.unwrap();
assert_eq!(state(&props).checked, Some(Checked::True));
assert_eq!(style(&after, wifi).background_color.0, 0x0000_ffff);
assert_eq!(style(&after, track).background_color.0, 0x00ff_00ff);
assert_eq!(style(&after, thumb).transform.ops()[0].value, 6.0);
assert!(after.iter().all(|b| view_props(b, thumb).is_none()));
engine
.control()
.dispatch_event(locked, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| shows(b, "Changes: true,false"));
assert!(after.iter().any(|b| shows(b, "Changes: true,false")));
assert!(after.iter().all(|b| view_props(b, locked).is_none()));
let disabled = view_props(&first, off).unwrap();
assert!(state(&disabled).disabled);
assert_eq!(state(&disabled).checked, Some(Checked::True));
assert!(!first.items.iter().any(|i| matches!(
i,
MountItem::Events { id, events } if *id == off && events.contains(EventKind::Press)
)));
let off_thumb = child(child(off));
let thumb_style = style(unchecked, off_thumb);
assert_eq!(thumb_style.opacity, 0.5);
assert_eq!(thumb_style.transform.ops()[0].value, 6.0);
assert!(view_props(&first, off_thumb).is_none());
}
const BASE_CHECKBOX: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Checkbox } from "nsh/base";
function App() {
const all = signal(false);
const some = signal(true);
const changes = signal<boolean[]>([]);
const parts = {
indicatorClass:
"w-[20px] checked:bg-[#00ff00] indeterminate:bg-[#ff0000] disabled:opacity-50",
};
return (
<View>
<Checkbox
testID="all"
checked={all()}
indeterminate={some() && !all()}
checkedStyle={{ backgroundColor: "#0000ff" }}
indeterminateStyle={{ backgroundColor: "#ffff00" }}
onChange={(next) => {
changes.set([...changes(), next]);
all.set(next);
}}
indicator={<Text>{all() ? "✓" : "-"}</Text>}
{...parts}
>
<Text>All</Text>
</Checkbox>
<Checkbox
testID="kept"
checked
accessibilityLabel="Kept"
onChange={(next) => changes.set([...changes(), next])}
{...parts}
/>
<Checkbox testID="off" checked disabled role="menuitem" {...parts} />
<Text>{`Changes: ${changes().join(",")}`}</Text>
</View>
);
}
mount(App);
"##;
#[test]
fn a_base_checkbox_reports_the_next_value_and_styles_its_indicator() {
use nsh_core::{AccessibilityRole, Checked, ViewProps};
let (engine, rx) = start(BASE_CHECKBOX);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(shows(&first, "Changes: "));
assert!(shows(&first, "-"), "the app's mark in the indicator");
let view_props = |batch: &MountBatch, view| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == view => Some(props.clone()),
_ => None,
})
};
let root = |test_id: &str| {
first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect(test_id)
};
let indicator = |parent: u32| {
let views: Vec<u32> = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Create {
id,
kind: nsh_core::ViewKind::View,
} => Some(*id),
_ => None,
})
.collect();
first
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent: p, child, ..
} if *p == parent && views.contains(child) => Some(*child),
_ => None,
})
.expect("the indicator")
};
let (all, kept, off) = (root("all"), root("kept"), root("off"));
let mark = indicator(all);
let style = |batches: &[MountBatch], view| {
batches
.iter()
.rev()
.flat_map(|b| b.items.iter().rev())
.find_map(|i| match i {
MountItem::ViewStyle { id, style } if *id == view => Some(style.clone()),
_ => None,
})
.unwrap_or_default()
};
let state = |props: &ViewProps| props.accessibility.state;
let props = view_props(&first, all).unwrap();
assert_eq!(props.accessibility.role, AccessibilityRole::Checkbox);
assert_eq!(state(&props).checked, Some(Checked::Mixed));
assert!(view_props(&first, mark).is_none());
let mixed = std::slice::from_ref(&first);
assert_eq!(style(mixed, all).background_color.0, 0xffff_00ff);
assert_eq!(style(mixed, mark).background_color.0, 0xff00_00ff);
assert_eq!(
view_props(&first, kept)
.unwrap()
.accessibility
.label
.as_deref(),
Some("Kept")
);
engine
.control()
.dispatch_event(all, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| shows(b, "Changes: true"));
let props = after.iter().rev().find_map(|b| view_props(b, all)).unwrap();
assert_eq!(state(&props).checked, Some(Checked::True));
assert_eq!(style(&after, all).background_color.0, 0x0000_ffff);
assert_eq!(style(&after, mark).background_color.0, 0x00ff_00ff);
assert!(after.iter().any(|b| shows(b, "✓")));
assert!(after.iter().all(|b| view_props(b, mark).is_none()));
engine
.control()
.dispatch_event(kept, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| shows(b, "Changes: true,false"));
assert!(after.iter().all(|b| view_props(b, kept).is_none()));
let disabled = view_props(&first, off).unwrap();
assert!(state(&disabled).disabled);
assert_eq!(state(&disabled).checked, Some(Checked::True));
assert_eq!(disabled.accessibility.role, AccessibilityRole::Menuitem);
assert!(!first.items.iter().any(|i| matches!(
i,
MountItem::Events { id, events } if *id == off && events.contains(EventKind::Press)
)));
let off_mark = style(mixed, indicator(off));
assert_eq!(off_mark.opacity, 0.5);
assert_eq!(off_mark.background_color.0, 0x00ff_00ff);
}
const BASE_RADIO: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Radio, RadioGroup } from "nsh/base";
function App() {
const plan = signal("a");
const changes = signal<string[]>([]);
const radio = (value: string, label: string, disabled = false) => (
<Radio
testID={value}
checked={plan() === value}
disabled={disabled}
accessibilityLabel={label}
class="group flex-row disabled:opacity-50"
checkedStyle={{ backgroundColor: "#0000ff" }}
onChange={(next) => {
changes.set([...changes(), `${value}:${next}`]);
plan.set(value);
}}
>
<View class="w-[20px] group-checked:bg-[#00ff00]" />
<Text>{label}</Text>
</Radio>
);
return (
<View>
<RadioGroup testID="plans" class="flex-row">
{radio("a", "Basic")}
{radio("b", "Pro")}
{radio("c", "Team", true)}
</RadioGroup>
<Text>{`Changes: ${changes().join(",")}`}</Text>
</View>
);
}
mount(App);
"##;
#[test]
fn a_base_radio_asks_to_be_checked_and_its_group_holds_no_value() {
use nsh_core::{AccessibilityRole, Checked, ViewProps};
let (engine, rx) = start(BASE_RADIO);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(shows(&first, "Changes: "));
let view_props = |batch: &MountBatch, view| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == view => Some(props.clone()),
_ => None,
})
};
let root = |test_id: &str| {
first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect(test_id)
};
let dot = |parent: u32| {
let views: Vec<u32> = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Create {
id,
kind: nsh_core::ViewKind::View,
} => Some(*id),
_ => None,
})
.collect();
first
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent: p, child, ..
} if *p == parent && views.contains(child) => Some(*child),
_ => None,
})
.expect("the dot")
};
let style = |batches: &[MountBatch], view| {
batches
.iter()
.rev()
.flat_map(|b| b.items.iter().rev())
.find_map(|i| match i {
MountItem::ViewStyle { id, style } if *id == view => Some(style.clone()),
_ => None,
})
.unwrap_or_default()
};
let state = |props: &ViewProps| props.accessibility.state;
let (plans, a, b, c) = (root("plans"), root("a"), root("b"), root("c"));
let (dot_a, dot_b) = (dot(a), dot(b));
let initial = std::slice::from_ref(&first);
let group = view_props(&first, plans).unwrap();
assert_eq!(group.accessibility.role, AccessibilityRole::Radiogroup);
assert_eq!(group.accessibility.label, None);
let props = view_props(&first, a).unwrap();
assert_eq!(props.accessibility.role, AccessibilityRole::Radio);
assert_eq!(props.accessibility.label.as_deref(), Some("Basic"));
assert_eq!(state(&props).checked, Some(Checked::True));
assert!(state(&props).selected);
assert_eq!(style(initial, a).background_color.0, 0x0000_ffff);
assert_eq!(style(initial, dot_a).background_color.0, 0x00ff_00ff);
let props = view_props(&first, b).unwrap();
assert_eq!(state(&props).checked, Some(Checked::False));
assert!(!state(&props).selected);
assert_eq!(style(initial, dot_b).background_color.0, 0);
assert!(view_props(&first, dot_a).is_none());
engine
.control()
.dispatch_event(b, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| shows(b, "Changes: b:true"));
assert!(after.iter().any(|batch| shows(batch, "Changes: b:true")));
let now = |view| after.iter().rev().find_map(|batch| view_props(batch, view));
assert_eq!(state(&now(b).unwrap()).checked, Some(Checked::True));
assert_eq!(state(&now(a).unwrap()).checked, Some(Checked::False));
assert_eq!(style(&after, b).background_color.0, 0x0000_ffff);
assert_eq!(style(&after, dot_b).background_color.0, 0x00ff_00ff);
assert_eq!(style(&after, dot_a).background_color.0, 0);
engine
.control()
.dispatch_event(b, EventKind::Press, EventPayload::None);
engine
.control()
.dispatch_event(a, EventKind::Press, EventPayload::None);
let after = until(&rx, |batch| shows(batch, "Changes: b:true,a:true"));
assert!(
after
.iter()
.any(|batch| shows(batch, "Changes: b:true,a:true"))
);
let disabled = view_props(&first, c).unwrap();
assert!(state(&disabled).disabled);
assert_eq!(state(&disabled).checked, Some(Checked::False));
assert!(!first.items.iter().any(|i| matches!(
i,
MountItem::Events { id, events } if *id == c && events.contains(EventKind::Press)
)));
assert_eq!(style(initial, c).opacity, 0.5);
}
const BASE_TABS: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Tab, Tabs } from "nsh/base";
function App() {
const current = signal("a");
const presses = signal<string[]>([]);
const tab = (value: string, label: string, disabled = false) => (
<Tab
testID={value}
selected={current() === value}
disabled={disabled}
accessibilityLabel={label}
class="group flex-row disabled:opacity-50"
selectedStyle={{ backgroundColor: "#0000ff" }}
onPress={() => {
presses.set([...presses(), value]);
current.set(value);
}}
>
<View class="w-[20px] group-selected:bg-[#00ff00]" />
<Text>{label}</Text>
</Tab>
);
return (
<View>
<Tabs testID="sections" class="flex-row">
{tab("a", "Overview")}
{tab("b", "Activity")}
{tab("c", "Billing", true)}
</Tabs>
<Text>{`Presses: ${presses().join(",")}`}</Text>
</View>
);
}
mount(App);
"##;
#[test]
fn a_base_tab_reports_presses_and_its_list_holds_no_value() {
use nsh_core::{AccessibilityRole, ViewProps};
let (engine, rx) = start(BASE_TABS);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(shows(&first, "Presses: "));
let view_props = |batch: &MountBatch, view| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == view => Some(props.clone()),
_ => None,
})
};
let root = |test_id: &str| {
first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect(test_id)
};
let marker = |parent: u32| {
let views: Vec<u32> = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Create {
id,
kind: nsh_core::ViewKind::View,
} => Some(*id),
_ => None,
})
.collect();
first
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent: p, child, ..
} if *p == parent && views.contains(child) => Some(*child),
_ => None,
})
.expect("the marker")
};
let style = |batches: &[MountBatch], view| {
batches
.iter()
.rev()
.flat_map(|b| b.items.iter().rev())
.find_map(|i| match i {
MountItem::ViewStyle { id, style } if *id == view => Some(style.clone()),
_ => None,
})
.unwrap_or_default()
};
let state = |props: &ViewProps| props.accessibility.state;
let (sections, a, b, c) = (root("sections"), root("a"), root("b"), root("c"));
let (marker_a, marker_b) = (marker(a), marker(b));
let initial = std::slice::from_ref(&first);
let list = view_props(&first, sections).unwrap();
assert_eq!(list.accessibility.role, AccessibilityRole::Tablist);
assert_eq!(list.accessibility.label, None);
let props = view_props(&first, a).unwrap();
assert_eq!(props.accessibility.role, AccessibilityRole::Tab);
assert_eq!(props.accessibility.label.as_deref(), Some("Overview"));
assert!(state(&props).selected);
assert_eq!(state(&props).checked, None);
assert_eq!(style(initial, a).background_color.0, 0x0000_ffff);
assert_eq!(style(initial, marker_a).background_color.0, 0x00ff_00ff);
let props = view_props(&first, b).unwrap();
assert_eq!(props.accessibility.role, AccessibilityRole::Tab);
assert!(!state(&props).selected);
assert_eq!(style(initial, b).background_color.0, 0);
assert_eq!(style(initial, marker_b).background_color.0, 0);
assert!(view_props(&first, marker_a).is_none());
engine
.control()
.dispatch_event(b, EventKind::Press, EventPayload::None);
let after = until(&rx, |batch| shows(batch, "Presses: b"));
let now = |view| after.iter().rev().find_map(|batch| view_props(batch, view));
assert!(state(&now(b).unwrap()).selected);
assert!(!state(&now(a).unwrap()).selected);
assert_eq!(style(&after, b).background_color.0, 0x0000_ffff);
assert_eq!(style(&after, marker_b).background_color.0, 0x00ff_00ff);
assert_eq!(style(&after, a).background_color.0, 0);
assert_eq!(style(&after, marker_a).background_color.0, 0);
engine
.control()
.dispatch_event(b, EventKind::Press, EventPayload::None);
let after = until(&rx, |batch| shows(batch, "Presses: b,b"));
assert!(after.iter().any(|batch| shows(batch, "Presses: b,b")));
let disabled = view_props(&first, c).unwrap();
assert!(state(&disabled).disabled);
assert!(!state(&disabled).selected);
assert!(!first.items.iter().any(|i| matches!(
i,
MountItem::Events { id, events } if *id == c && events.contains(EventKind::Press)
)));
assert_eq!(style(initial, c).opacity, 0.5);
}
const BASE_COLLAPSIBLE: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Collapsible } from "nsh/base";
function App() {
const open = signal(false);
const count = signal(0);
return (
<View>
<Collapsible
testID="region"
open={open()}
class="gap-[4px]"
content={<Text>{`Details ${count()}`}</Text>}
>
<View
testID="trigger"
role="button"
accessibilityState={{ expanded: open() }}
onPress={() => open.set(!open())}
>
<Text>Summary</Text>
</View>
</Collapsible>
<View testID="bump" onPress={() => count.set(count() + 1)} />
</View>
);
}
mount(App);
"##;
#[test]
fn a_base_collapsible_places_its_content_while_open() {
let (engine, rx) = start(BASE_COLLAPSIBLE);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(shows(&first, "Summary"));
assert!(
!first
.items
.iter()
.any(|i| matches!(i, MountItem::Text { text, .. } if text.text.starts_with("Details"))),
"collapsed: no content"
);
let by_test_id = |test_id: &str| {
first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect(test_id)
};
let (region, trigger, bump) = (
by_test_id("region"),
by_test_id("trigger"),
by_test_id("bump"),
);
let expanded = |batches: &[MountBatch]| {
batches
.iter()
.rev()
.flat_map(|b| b.items.iter().rev())
.find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == trigger => {
Some(props.accessibility.state.expanded)
}
_ => None,
})
.flatten()
};
assert_eq!(expanded(std::slice::from_ref(&first)), Some(false));
let region_props = first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == region => Some(props.clone()),
_ => None,
})
.unwrap();
assert_eq!(
region_props.accessibility.role,
nsh_core::AccessibilityRole::None
);
let press = |view| {
engine
.control()
.dispatch_event(view, EventKind::Press, EventPayload::None)
};
press(trigger);
let opened = until(&rx, |b| shows(b, "Details 0"));
let text = opened
.iter()
.find_map(|b| text_ids(b, "Details 0"))
.expect("the content shows");
assert_eq!(expanded(&opened), Some(true));
let parent_of = |batches: &[MountBatch], child: u32| {
batches
.iter()
.flat_map(|b| b.items.iter())
.find_map(|i| match i {
MountItem::Insert {
parent, child: c, ..
} if *c == child => Some(*parent),
_ => None,
})
};
let holder = parent_of(&opened, text).expect("the holder");
assert_eq!(parent_of(&opened, holder), Some(region));
press(trigger);
let closed = until(&rx, |b| {
b.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == holder))
});
assert_eq!(expanded(&closed), Some(false));
assert!(
!closed
.iter()
.flat_map(|b| b.items.iter())
.any(|i| matches!(i, MountItem::Delete { id } if *id == holder || *id == text)),
"kept, not released"
);
press(bump);
press(trigger);
let reopened = until(&rx, |b| {
b.items.iter().any(
|i| matches!(i, MountItem::Insert { parent, child, .. } if *parent == region && *child == holder),
)
});
assert_eq!(expanded(&reopened), Some(true));
let all: Vec<&MountBatch> = closed.iter().chain(reopened.iter()).collect();
assert!(
all.iter().any(|b| shows(b, "Details 1")),
"the content followed the app"
);
}
const BASE_PROGRESS: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Progress } from "nsh/base";
function App() {
const value = signal(40);
const loading = signal(false);
return (
<View>
<Progress
testID="download"
value={value()}
indeterminate={loading()}
accessibilityLabel="Downloading"
class="w-[200px]"
trackClass="h-[4px]"
indicatorClass={loading() ? "h-full w-[50px]" : "h-full"}
indicatorStyle={{ backgroundColor: "#00ff00" }}
>
<Text>{`${value()}%`}</Text>
</Progress>
<View testID="more" onPress={() => value.set(value() + 80)} />
<View testID="loading" onPress={() => loading.set(!loading())} />
</View>
);
}
mount(App);
"##;
#[test]
fn a_base_progress_shows_the_apps_value_in_its_indicator() {
use nsh_core::{AccessibilityRole, AccessibilityValue};
let (engine, rx) = start(BASE_PROGRESS);
let first = rx
.recv_timeout(Duration::from_secs(5))
.expect("first frame");
assert!(shows(&first, "40%"));
let by_test_id = |test_id: &str| {
first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect(test_id)
};
let (root, more, loading) = (
by_test_id("download"),
by_test_id("more"),
by_test_id("loading"),
);
let child = |parent: u32| {
let views: Vec<u32> = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Create {
id,
kind: nsh_core::ViewKind::View,
} => Some(*id),
_ => None,
})
.collect();
first
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent: p, child, ..
} if *p == parent && views.contains(child) => Some(*child),
_ => None,
})
.expect("a part")
};
let (track, indicator) = (child(root), child(child(root)));
let value = |batches: &[MountBatch]| {
batches
.iter()
.rev()
.flat_map(|b| b.items.iter().rev())
.find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == root => {
Some(props.accessibility.value.clone())
}
_ => None,
})
.flatten()
};
let range = |now| AccessibilityValue {
min: Some(0.0),
max: Some(100.0),
now,
text: None,
};
let width = |batches: &[MountBatch]| frame_of(batches, indicator).map(|f| f.size.width.0);
let props = first
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == root => Some(props.clone()),
_ => None,
})
.unwrap();
assert_eq!(props.accessibility.role, AccessibilityRole::Progressbar);
assert_eq!(props.accessibility.accessible, Some(true));
assert_eq!(props.accessibility.label.as_deref(), Some("Downloading"));
let first = std::slice::from_ref(&first);
assert_eq!(value(first), Some(range(Some(40.0))));
assert!(first.iter().all(|b| !b.items.iter().any(
|i| matches!(i, MountItem::ViewProps { id, .. } if *id == track || *id == indicator)
)));
assert_eq!(width(first), Some(80.0));
assert_eq!(
first
.iter()
.flat_map(|b| b.items.iter())
.find_map(|i| match i {
MountItem::ViewStyle { id, style } if *id == indicator => {
Some(style.background_color.0)
}
_ => None,
}),
Some(0x00ff_00ff)
);
let press = |view| {
engine
.control()
.dispatch_event(view, EventKind::Press, EventPayload::None)
};
press(more);
let after = until(&rx, |b| shows(b, "120%"));
assert_eq!(value(&after), Some(range(Some(100.0))));
assert_eq!(width(&after), Some(200.0));
press(loading);
let after = until(&rx, |b| {
frame_of(std::slice::from_ref(b), indicator).is_some()
});
assert_eq!(value(&after), Some(range(None)));
assert_eq!(width(&after), Some(50.0));
}
const TAB_BAR: &str = r##"import { mount, signal } from "nsh";
import { TabBar } from "nsh/mobile";
const selected = signal(0);
function App() {
return (
<TabBar
items={[
{ title: "Records", icon: "list.bullet" },
{ title: "Stats", icon: "chart.bar" },
]}
selectedIndex={selected()}
onChange={(index: number) => selected.set(index)}
/>
);
}
mount(App);
"##;
fn is_tab_bar(item: &MountItem) -> bool {
matches!(item, MountItem::Component { name, .. }
if &**name == nsh_core::platform::TAB_BAR_COMPONENT)
}
#[test]
fn the_tab_bar_is_the_systems_component_on_ios_and_android() {
use nsh_core::platform::Os;
for os in [Os::Ios, Os::Android] {
let (_engine, rx) = start_in(
TAB_BAR,
Environment {
os,
..Environment::default()
},
);
let batches = until(&rx, |batch| batch.items.iter().any(is_tab_bar));
let props = batches.iter().find_map(|batch| {
batch.items.iter().find_map(|i| match i {
MountItem::ComponentProps { props, .. } => Some(props.clone()),
_ => None,
})
});
let props = props.expect("its props reach it");
let value = |key: &str| {
props
.iter()
.find(|(name, _)| &**name == key)
.and_then(|(_, value)| value.clone())
};
assert_eq!(
value("items"),
Some(serde_json::json!([
{ "title": "Records", "icon": "list.bullet" },
{ "title": "Stats", "icon": "chart.bar" },
])),
"{os:?}"
);
assert_eq!(value("selectedIndex"), Some(serde_json::json!(0)), "{os:?}");
}
}
#[test]
fn the_tab_bar_renders_nothing_on_the_desktops_and_the_web() {
use nsh_core::platform::Os;
let app = TAB_BAR
.replace("mount, signal", "mount, signal, Text")
.replace("import { TabBar }", "import { TabBar, isAvailable }")
.replace(
"mount(App);",
"mount(() => <><App /><Text>{`Ready: ${isAvailable}`}</Text></>);",
);
for (os, available) in [(Os::Ios, true), (Os::Android, true)] {
let (_engine, rx) = start_in(
&app,
Environment {
os,
..Environment::default()
},
);
let ready = format!("Ready: {available}");
let batches = until(&rx, |batch| shows(batch, &ready));
assert!(batches.iter().any(|batch| shows(batch, &ready)), "{os:?}");
}
for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Web] {
let (_engine, rx) = start_in(
&app,
Environment {
os,
..Environment::default()
},
);
let batches = until(&rx, |batch| shows(batch, "Ready: false"));
assert!(
batches.iter().any(|batch| shows(batch, "Ready: false")),
"{os:?}"
);
let platform = batches
.iter()
.any(|batch| batch.items.iter().any(is_tab_bar));
assert!(!platform, "no system bar on {os:?}, no component");
}
}
#[test]
fn the_tab_bar_reports_the_users_choice_and_follows_its_props() {
let app = r#"import { mount, signal, Text, View } from "nsh";
import { TabBar } from "nsh/mobile";
const selected = signal<number | undefined>(0);
const items = signal([{ title: "Records" }, { title: "Stats" }]);
mount(() => <View>
<TabBar items={items()} selectedIndex={selected()}
onChange={(index) => {
selected.set(index);
items.set([{ title: "Records" }, { title: "Statistics" }]);
}} />
<Text>{`Selected: ${selected()}`}</Text>
<Text onPress={() => selected.set(undefined)}>Reset</Text>
</View>);
"#;
let (engine, rx) = start(app);
let initial = until(&rx, |batch| shows(batch, "Selected: 0"));
let bar = initial
.iter()
.flat_map(|batch| &batch.items)
.find_map(|item| match item {
MountItem::Component { id, .. } if is_tab_bar(item) => Some(*id),
_ => None,
})
.expect("the system bar");
engine.control().dispatch_event(
bar,
EventKind::NativeEvent,
EventPayload::Native {
name: "change".into(),
data: serde_json::json!(1),
},
);
let updates = until(&rx, |batch| shows(batch, "Selected: 1"));
assert!(updates.iter().any(|batch| shows(batch, "Selected: 1")));
let props: Vec<_> = updates
.iter()
.flat_map(|batch| &batch.items)
.filter_map(|item| match item {
MountItem::ComponentProps { id, props } if *id == bar => Some(props),
_ => None,
})
.flatten()
.collect();
assert!(
props
.iter()
.any(|(name, value)| &**name == "selectedIndex"
&& *value == Some(serde_json::json!(1)))
);
assert!(props.iter().any(|(name, value)| &**name == "items"
&& *value == Some(serde_json::json!([{ "title": "Records" }, { "title": "Statistics" }]))));
let reset = initial
.iter()
.find_map(|batch| text_ids(batch, "Reset"))
.expect("reset text");
engine
.control()
.dispatch_event(reset, EventKind::Press, EventPayload::None);
let reset = until(&rx, |batch| shows(batch, "Selected: undefined"));
assert!(reset.iter().any(|batch| batch.items.iter().any(|item| {
matches!(item, MountItem::ComponentProps { id, props } if *id == bar
&& props.iter().any(|(name, value)| &**name == "selectedIndex"
&& *value == Some(serde_json::json!(0))))
})));
}
const BASE_PLOT: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Area, Grid, Line, Plot } from "nsh/base/plot";
type Row = { t: number; price: number; avg?: number; name: string };
function App() {
const rows = signal<Row[]>([
{ t: 0, price: 10, avg: 15, name: "a" },
{ t: 1, price: 20, avg: 15, name: "b" },
{ t: 2, price: 30, name: "c" },
]);
const hovered = signal<number | null>(null);
return (
<View>
<Plot
testID="plot"
data={rows()}
y="price"
yScale={{ type: "linear", domain: [0, 40] }}
accessibilityLabel="Price"
class="w-[200px] h-[100px] stroke-[#ff0000]"
style={{ color: "#0000ff" }}
onHoverChange={(index) => hovered.set(index)}
>
<Grid y={[0, 20, 40]} class="stroke-[#00ff00]" style={{ strokeDasharray: "2 2" }} />
<Area class="fill-[#0000ff]/50" curve="linear" />
<Line curve="linear" class="stroke-2" />
<Line y="avg" curve="stepAfter" class="stroke-current" />
</Plot>
<Text>{`hover ${hovered()}`}</Text>
<View testID="more" onPress={() => rows.set([...rows(), { t: 3, price: 40, name: "d" }])} />
</View>
);
}
mount(App);
"##;
#[test]
fn a_base_plot_draws_its_marks_from_the_rows() {
use nsh_core::{
AccessibilityRole, Color, HoverEvent,
canvas::{CanvasOp, Num, Paint, PathOp},
};
let (engine, rx) = start(BASE_PLOT);
let drawings = |batches: &[MountBatch]| {
batches
.iter()
.flat_map(|b| b.items.iter())
.filter_map(|i| match i {
MountItem::Canvas { id, drawing } => Some((*id, drawing.clone())),
_ => None,
})
.collect::<Vec<_>>()
};
let points = |ops: &[CanvasOp]| {
ops.iter()
.filter_map(|op| match op {
CanvasOp::Path(PathOp::MoveTo(Num::Const(x), Num::Const(y)))
| CanvasOp::Path(PathOp::LineTo(Num::Const(x), Num::Const(y))) => Some((*x, *y)),
_ => None,
})
.collect::<Vec<_>>()
};
let mut batches = Vec::new();
while let Ok(batch) = rx.recv_timeout(Duration::from_millis(500)) {
let done = drawings(std::slice::from_ref(&batch))
.iter()
.any(|(_, d)| points(&d.ops).len() > 3);
batches.push(batch);
if done {
break;
}
}
assert!(shows(&batches[0], "hover null"));
assert_eq!(plot_bleeds(&batches), [8.0; 4]);
let latest = plot_drawings(&batches);
let [(_, grid), (_, area), (line, price), (_, avg)] = &latest[..] else {
panic!("four marks: {latest:?}")
};
let (red, blue, green) = (Color(0xff00_00ff), Color(0x0000_ffff), Color(0x00ff_00ff));
assert_eq!(grid.ops[0], CanvasOp::StrokeStyle(Paint::Color(green)));
assert_eq!(grid.ops[2], CanvasOp::LineDash([px(2.0), px(2.0)].into()));
assert_eq!(
points(&grid.ops),
[
(0.0, 100.5),
(200.0, 100.5),
(0.0, 50.5),
(200.0, 50.5),
(0.0, 0.5),
(200.0, 0.5)
]
);
assert_eq!(
area.ops[0],
CanvasOp::FillStyle(Paint::Color(Color(0x0000_ff80)))
);
assert_eq!(
&points(&area.ops)[..5],
[
(0.0, 75.0),
(100.0, 50.0),
(200.0, 25.0),
(200.0, 100.0),
(0.0, 100.0)
]
);
assert_eq!(price.ops[0], CanvasOp::StrokeStyle(Paint::Color(red)));
assert_eq!(price.ops[1], CanvasOp::LineWidth(Num::Const(2.0)));
assert_eq!(
points(&price.ops),
[(0.0, 75.0), (100.0, 50.0), (200.0, 25.0)]
);
assert_eq!(avg.ops[0], CanvasOp::StrokeStyle(Paint::Color(blue)));
assert_eq!(
points(&avg.ops),
[(0.0, 62.5), (100.0, 62.5), (100.0, 62.5)]
);
assert!(area.ops.contains(&CanvasOp::StrokeStyle(Paint::Color(red))));
let plot = batches
.iter()
.flat_map(|b| b.items.iter())
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some("plot") => {
Some((*id, props.clone()))
}
_ => None,
})
.unwrap();
assert_eq!(plot.1.accessibility.role, AccessibilityRole::Image);
assert_eq!(plot.1.accessibility.accessible, Some(true));
assert_eq!(plot.1.accessibility.label.as_deref(), Some("Price"));
let hover = |x: f32| {
engine.control().dispatch_event(
plot.0,
EventKind::HoverMove,
EventPayload::Hover(HoverEvent {
position: nsh_core::geometry::point(px(x), px(10.0)),
..Default::default()
}),
)
};
hover(90.0);
until(&rx, |b| shows(b, "hover 1"));
hover(160.0);
until(&rx, |b| shows(b, "hover 2"));
engine
.control()
.dispatch_event(plot.0, EventKind::HoverOut, EventPayload::None);
until(&rx, |b| shows(b, "hover null"));
let more = batches
.iter()
.flat_map(|b| b.items.iter())
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some("more") => {
Some(*id)
}
_ => None,
})
.unwrap();
engine
.control()
.dispatch_event(more, EventKind::Press, EventPayload::None);
let after = until(&rx, |b| !drawings(std::slice::from_ref(b)).is_empty());
let redrawn = drawings(&after[after.len() - 1..]);
assert_eq!(redrawn.len(), 3, "the area and the lines: {redrawn:?}");
let (_, price) = redrawn.iter().find(|(id, _)| id == line).unwrap();
assert_eq!(
points(&price.ops),
[
(0.0, 75.0),
(66.666664, 50.0),
(133.33333, 25.0),
(200.0, 0.0)
]
);
}
fn plot_drawings(batches: &[MountBatch]) -> Vec<(u32, std::sync::Arc<nsh_core::canvas::Drawing>)> {
use nsh_core::canvas::CanvasOp;
plot_canvases(batches)
.into_iter()
.map(|(id, d)| {
let mut d = (*d).clone();
if matches!(d.ops.first(), Some(CanvasOp::Translate(..))) {
d.ops.remove(0);
}
(id, std::sync::Arc::new(d))
})
.collect()
}
fn plot_bleeds(batches: &[MountBatch]) -> Vec<f32> {
use nsh_core::canvas::{CanvasOp, Num};
plot_canvases(batches)
.iter()
.filter_map(|(_, d)| match d.ops.first() {
Some(CanvasOp::Translate(Num::Const(x), Num::Const(y))) if x == y => Some(*x),
_ => None,
})
.collect()
}
fn plot_canvases(batches: &[MountBatch]) -> Vec<(u32, std::sync::Arc<nsh_core::canvas::Drawing>)> {
let mut latest: Vec<(u32, std::sync::Arc<nsh_core::canvas::Drawing>)> = Vec::new();
for item in batches.iter().flat_map(|b| b.items.iter()) {
if let MountItem::Canvas { id, drawing } = item {
match latest.iter_mut().find(|(i, _)| i == id) {
Some(entry) => entry.1 = drawing.clone(),
None => latest.push((*id, drawing.clone())),
}
}
}
latest.sort_by_key(|(id, _)| *id);
latest
}
fn path_points(ops: &[nsh_core::canvas::CanvasOp]) -> Vec<(f32, f32)> {
use nsh_core::canvas::{CanvasOp, Num, PathOp};
ops.iter()
.filter_map(|op| match op {
CanvasOp::Path(PathOp::MoveTo(Num::Const(x), Num::Const(y)))
| CanvasOp::Path(PathOp::LineTo(Num::Const(x), Num::Const(y))) => Some((*x, *y)),
CanvasOp::Path(PathOp::CubicTo(n)) => match (n[4], n[5]) {
(Num::Const(x), Num::Const(y)) => Some((x, y)),
_ => None,
},
_ => None,
})
.collect()
}
fn test_view(batches: &[MountBatch], test_id: &str) -> u32 {
batches
.iter()
.flat_map(|b| b.items.iter())
.find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect(test_id)
}
fn until_drawn(
rx: &Receiver<MountBatch>,
done: impl Fn(&nsh_core::canvas::Drawing) -> bool,
) -> Vec<MountBatch> {
until(rx, |b| {
b.items
.iter()
.any(|i| matches!(i, MountItem::Canvas { drawing, .. } if done(drawing)))
})
}
const BASE_PLOT_SHAPES: &str = r##"import { mount, signal, View } from "nsh";
import { Area, Grid, Line, Plot } from "nsh/base/plot";
type Row = { t: number; v: number | null };
function App() {
const width = signal(200);
const rows: Row[] = [
{ t: 0, v: -10 },
{ t: 1, v: null },
{ t: 2, v: 10 },
{ t: 3, v: 30 },
];
return (
<View>
{/* The default curve, a gap and negatives; a function of each row. */}
<Plot testID="curved" data={rows} y="v" style={{ width: width(), height: 100 }}>
<Line />
<Line y={(d: Row) => d.v ?? 0} />
</Plot>
{/* Rows of a mark's own, on a linear x scale. */}
<Plot data={rows} x="t" y="v" xScale={{ type: "linear", domain: [0, 4] }} yScale={{ type: "linear", domain: [-10, 30] }} style={{ width: 200, height: 100 }}>
<Line data={[{ at: 1, w: 30 }, { at: 3, w: -10 }]} x="at" y="w" curve="linear" />
</Plot>
{/* No rows, one row, all equal values. */}
<Plot data={[]} y="v" style={{ width: 200, height: 100 }}><Line /></Plot>
<Plot data={[{ v: 5 }]} y="v" style={{ width: 200, height: 100 }}><Line /></Plot>
<Plot data={[{ v: 5 }, { v: 5 }]} y="v" style={{ width: 200, height: 100 }}><Area /></Plot>
{/* currentColor follows the appearance. */}
<Plot data={[{ v: 1 }, { v: 2 }]} y="v" class="text-black dark:text-white" style={{ width: 200, height: 100 }}>
<Grid y={[1, 2]} />
{/* A theme's chart token, a series' color. */}
<Grid y={[1]} class="stroke-chart-1" />
</Plot>
<View testID="wider" onPress={() => width.set(400)} style={{ height: 20 }} />
</View>
);
}
mount(App);
"##;
#[test]
fn base_plot_marks_draw_the_edges_of_their_data() {
use nsh_core::canvas::{CanvasOp, Paint, PathOp};
let environment = Environment {
color_scheme: nsh_core::platform::ColorScheme::Dark,
..Environment::default()
};
let (engine, rx) = start_in(BASE_PLOT_SHAPES, environment);
let batches = until_drawn(&rx, |d| {
path_points(&d.ops)
== [
(0.0, 100.0),
(66.666664, 75.0),
(133.33333, 50.0),
(200.0, 0.0),
]
});
assert_eq!(plot_bleeds(&batches), [8.0; 8]);
let marks = plot_drawings(&batches);
let [
(_, curved),
_,
(_, own),
(_, empty),
(_, one),
(_, equal),
(_, grid),
(_, chart),
] = &marks[..]
else {
panic!("eight marks: {marks:?}")
};
assert!(
curved
.ops
.iter()
.any(|op| matches!(op, CanvasOp::Path(PathOp::CubicTo(_))))
);
assert_eq!(
path_points(&curved.ops),
[(0.0, 100.0), (133.33333, 50.0), (200.0, 0.0)]
);
assert_eq!(path_points(&own.ops), [(50.0, 0.0), (150.0, 100.0)]);
assert!(path_points(&empty.ops).is_empty());
assert_eq!(path_points(&one.ops), [(100.0, 50.0)]);
assert_eq!(path_points(&equal.ops)[..2], [(0.0, 50.0), (200.0, 50.0)]);
assert_eq!(
grid.ops[0],
CanvasOp::StrokeStyle(Paint::Color(nsh_core::Color(0xffff_ffff)))
); let CanvasOp::StrokeStyle(Paint::Color(c)) = chart.ops[0] else {
panic!("{:?}", chart.ops[0])
};
assert!(c.0 & 0xff == 0xff && c != nsh_core::Color(0xffff_ffff));
let wider = test_view(&batches, "wider");
engine
.control()
.dispatch_event(wider, EventKind::Press, EventPayload::None);
let after = until_drawn(&rx, |d| path_points(&d.ops).last() == Some(&(400.0, 0.0)));
assert!(!plot_drawings(&after).is_empty());
}
const BASE_PLOT_MOTION: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Line, Plot } from "nsh/base/plot";
function App() {
const hovered = signal<number | null>(null);
return (
<View>
<Plot
testID="plot"
data={[{ v: 1 }, { v: 2 }, { v: 3 }]}
y="v"
appearGeneration={1}
motion={{ appear: { duration: 300 }, enter: { duration: 120 }, exit: { duration: 80 }, pointer: { stiffness: 300, damping: 30 } }}
accessibilityValue={{ text: hovered() == null ? undefined : `row ${hovered()}` }}
crossLineClass="w-px bg-[#999999]"
dotClass="size-2 rounded-full bg-[#3366ff]"
tooltipContent={<Text>tip</Text>}
onHoverChange={(index) => hovered.set(index)}
style={{ width: 200, height: 100 }}
>
<Line dot dotClass="size-1" />
</Plot>
<Text>{`hover ${hovered()}`}</Text>
</View>
);
}
mount(App);
"##;
#[test]
fn base_plot_moves_natively_with_its_motion() {
use nsh_core::{
animation::{AnimationOp, Driver},
canvas::CanvasOp,
};
let (engine, rx) = start(BASE_PLOT_MOTION);
let batches = until_drawn(&rx, |d| {
d.ops.iter().any(|op| matches!(op, CanvasOp::Clip(..)))
});
let timings = |batches: &[MountBatch]| -> Vec<(f32, f32)> {
batches
.iter()
.flat_map(|b| b.items.iter())
.filter_map(|i| match i {
MountItem::Animation(AnimationOp::Start {
driver:
Driver::Timing {
to, duration_ms, ..
},
..
}) => Some((*to, *duration_ms)),
_ => None,
})
.collect()
};
let springs = |batches: &[MountBatch]| {
batches
.iter()
.flat_map(|b| b.items.iter())
.filter(|i| {
matches!(
i,
MountItem::Animation(AnimationOp::Start {
driver: Driver::Spring { .. },
..
})
)
})
.count()
};
let mut batches = batches;
if !timings(&batches).contains(&(1.0, 300.0)) {
batches.extend(until(&rx, |b| {
timings(std::slice::from_ref(b)).contains(&(1.0, 300.0))
}));
}
assert!(timings(&batches).contains(&(1.0, 300.0)));
let line = plot_drawings(&batches);
assert!(!line[0].1.slots.is_empty());
assert!(shows(&batches[0], "hover null"));
let plot = test_view(&batches, "plot");
let hover = |x: f32| {
engine.control().dispatch_event(
plot,
EventKind::HoverMove,
EventPayload::Hover(nsh_core::HoverEvent {
position: nsh_core::geometry::point(px(x), px(10.0)),
..Default::default()
}),
)
};
hover(90.0);
let entered = until(&rx, |b| shows(b, "hover 1"));
assert!(timings(&entered).contains(&(1.0, 120.0)));
assert_eq!(springs(&entered), 0);
assert!(plot_drawings(&entered).is_empty());
assert!(entered.iter().flat_map(|b| b.items.iter()).any(|i| matches!(
i,
MountItem::ViewProps { id, props } if *id == plot
&& props.accessibility.value.as_ref().and_then(|v| v.text.as_deref()) == Some("row 1")
)));
hover(190.0);
let glided = until(&rx, |b| shows(b, "hover 2"));
assert!(springs(&glided) > 0);
assert!(plot_drawings(&glided).is_empty());
engine
.control()
.dispatch_event(plot, EventKind::HoverOut, EventPayload::None);
let left = until(&rx, |b| shows(b, "hover null"));
assert!(timings(&left).contains(&(0.0, 80.0)));
let environment = Environment {
reduce_motion: true,
..Environment::default()
};
let (_engine, rx) = start_in(BASE_PLOT_MOTION, environment);
let mut batches = until(&rx, |b| shows(b, "hover null"));
batches.extend(until(&rx, |_| false));
assert!(!timings(&batches).contains(&(1.0, 300.0)));
assert!(
plot_drawings(&batches)
.iter()
.all(|(_, d)| !d.ops.iter().any(|op| matches!(op, CanvasOp::Clip(..))))
);
}
const BASE_PLOT_PARTS: &str = r##"import { mount, signal, Text, View } from "nsh";
import { Area, Line, Plot } from "nsh/base/plot";
function App() {
const hovered = signal<number | null>(null);
const placement = signal<"top" | "pointer">("top");
return (
<View>
<Plot
testID="plot"
data={[{ v: 10, w: 5 }, { v: 20, w: 15 }, { v: 30, w: 35 }]}
y="v"
yScale={{ type: "linear", domain: [0, 40] }}
dotClass="size-2"
dotStyle={{ backgroundColor: "#ffffff" }}
tooltipContent={<View testID="tip" style={{ width: 60, height: 20 }} />}
tooltipPlacement={placement()}
tooltipOffset={8}
onHoverChange={(index) => hovered.set(index)}
style={{ width: 200, height: 100 }}
>
<Area curve="linear" backgroundClass="bg-linear-to-b from-[#ff0000] to-transparent" hoverDotClass="hidden" />
<Line curve="linear" hoverDotStyle={{ backgroundColor: "#ff0000" }} />
<Line y="w" curve="linear" />
</Plot>
<Text>{`hover ${hovered()} ${placement()}`}</Text>
<View testID="pointer" onPress={() => placement.set("pointer")} style={{ height: 20 }} />
</View>
);
}
mount(App);
"##;
#[test]
fn base_plot_marks_have_parts_of_their_own_and_the_tooltip_stays_inside() {
use nsh_core::{
Color, HoverEvent,
animation::Animator,
canvas::{CanvasOp, GradientShape, Paint},
geometry::point,
};
let (engine, rx) = start(BASE_PLOT_PARTS);
let mut all = until_drawn(&rx, |d| {
d.ops
.iter()
.any(|op| matches!(op, CanvasOp::FillStyle(Paint::Gradient(_))))
});
all.extend(until(&rx, |_| false));
let drawings = plot_drawings(&all);
let (background, gradient) = drawings
.iter()
.find_map(|(id, d)| {
d.ops.iter().find_map(|op| match op {
CanvasOp::FillStyle(Paint::Gradient(g)) => Some((*id, g.clone())),
_ => None,
})
})
.expect("a gradient");
assert_eq!(
gradient.shape,
GradientShape::Linear {
start: point(px(100.0), px(25.0)),
end: point(px(100.0), px(100.0)),
}
);
assert_eq!(gradient.stops[0].1, Color(0xff00_00ff));
let style = all
.iter()
.flat_map(|b| b.items.iter())
.filter_map(|i| match i {
MountItem::ViewStyle { id, style } if *id == background => Some(style.clone()),
_ => None,
})
.next_back()
.unwrap();
assert!(style.background_color.is_transparent());
assert!(
style
.effects
.as_deref()
.is_none_or(|e| e.background_images.is_empty())
);
assert!(drawings.iter().any(|(id, d)| *id != background
&& d.ops.first() == Some(&CanvasOp::FillStyle(Paint::Color(Color::TRANSPARENT)))));
let backgrounds = |all: &[MountBatch], color: Color| {
let mut ids: Vec<u32> = all
.iter()
.flat_map(|b| b.items.iter())
.filter_map(|i| match i {
MountItem::ViewStyle { id, style } if style.background_color == color => Some(*id),
_ => None,
})
.collect();
ids.sort();
ids.dedup();
ids.len()
};
assert_eq!(backgrounds(&all, Color(0xff00_00ff)), 1);
assert!(backgrounds(&all, Color(0xffff_ffff)) >= 1);
let plot = test_view(&all, "plot");
let hover = |x: f32, y: f32| {
engine.control().dispatch_event(
plot,
EventKind::HoverMove,
EventPayload::Hover(HoverEvent {
position: point(px(x), px(y)),
..Default::default()
}),
)
};
let tip = test_view(&all, "tip");
let parent = |all: &[MountBatch], child: u32| {
all.iter()
.flat_map(|b| b.items.iter())
.find_map(|i| match i {
MountItem::Insert {
parent, child: c, ..
} if *c == child => Some(*parent),
_ => None,
})
.unwrap()
};
let (holder, point_view) = {
let holder = parent(&all, parent(&all, tip));
(holder, parent(&all, holder))
};
let placed = |all: &[MountBatch]| {
let frame = all
.iter()
.flat_map(|b| b.items.iter())
.filter_map(|i| match i {
MountItem::Frame { id, frame } if *id == holder => Some(*frame),
_ => None,
})
.next_back()
.unwrap();
let mut animator = Animator::default();
for item in all.iter().flat_map(|b| b.items.iter()) {
animator.apply(item);
}
let mut moved = (f32::NAN, f32::NAN);
animator.write(
|id| (id == point_view).then_some(id),
|_, values, _| {
moved = (
values.transform[0].unwrap_or(f32::NAN),
values.transform[1].unwrap_or(f32::NAN),
)
},
);
(
(frame.origin.x.0, frame.origin.y.0),
(frame.size.width.0, frame.size.height.0),
moved,
)
};
let near = |(x, y): (f32, f32), (wx, wy): (f32, f32)| {
assert!(
(x - wx).abs() < 0.01 && (y - wy).abs() < 0.01,
"({x}, {y}) is not ({wx}, {wy})"
);
};
hover(190.0, 10.0);
all.extend(until(&rx, |b| shows(b, "hover 2 top")));
all.extend(until(&rx, |_| false));
let (at, size, moved) = placed(&all);
near(at, (0.0, 8.0));
near(size, (60.0, 20.0));
near(moved, (140.0, 0.0));
let pointer = test_view(&all, "pointer");
engine
.control()
.dispatch_event(pointer, EventKind::Press, EventPayload::None);
all.extend(until(&rx, |b| shows(b, "hover 2 pointer")));
hover(190.0, 80.0);
all.extend(until(&rx, |_| false));
let (at, _, moved) = placed(&all);
near(at, (-68.0, -28.0));
near(moved, (200.0, 80.0));
hover(10.0, 10.0);
all.extend(until(&rx, |b| shows(b, "hover 0 pointer")));
all.extend(until(&rx, |_| false));
let (at, _, moved) = placed(&all);
near(at, (8.0, 8.0));
near(moved, (0.0, 10.0));
}