use std::cell::Cell;
use super::*;
use crate::{
Color, EventKind, IMAGE_SCALES, ImageScales, StyleValue,
animation::{AnimationOp, AnimationProp},
element::{input, modal, screen, stack},
geometry::{point, px},
};
/// 8pt per char, 16pt per line, wraps at `max_width`. Counts calls.
#[derive(Default)]
struct FakeEngine {
prepares: Cell<u32>,
measures: Cell<u32>,
layouts: Cell<u32>,
/// [`TextEngine::draws_colors_from_text`].
colors_at_draw: bool,
}
/// A text engine that records the options its text blocks ask for
/// ([`crate::TextOptions`]).
#[derive(Clone, Default)]
struct IndentEngine {
indent: std::rc::Rc<std::cell::Cell<Option<Option<Points>>>>,
}
impl TextEngine for IndentEngine {
type Prepared = ();
fn prepare(&self, _: &AttributedText) {}
fn prepare_with(
&self,
_: &AttributedText,
_: &crate::AttachmentAlignments,
options: &crate::TextOptions,
) {
self.indent.set(Some(options.indent));
}
fn measure(&self, _: &(), _: Option<Points>) -> Size<Points> {
size_pt(10.0, 20.0)
}
fn layout(&self, _: &(), _: Size<Points>) -> TextLayout {
TextLayout(std::sync::Arc::new(()))
}
}
/// [`FakeEngine`]'s layout: the characters laid out and where its
/// attachments go.
struct FakeLayout {
chars: usize,
points: Vec<Option<Point<Points>>>,
}
impl TextEngine for FakeEngine {
/// Characters and attachment offsets.
type Prepared = (usize, Vec<u32>);
fn prepare(&self, text: &AttributedText) -> (usize, Vec<u32>) {
self.prepares.set(self.prepares.get() + 1);
(
text.text.chars().count(),
text.attachments.iter().map(|a| a.index).collect(),
)
}
fn measure(&self, &(chars, _): &(usize, Vec<u32>), max_width: Option<Points>) -> Size<Points> {
self.measures.set(self.measures.get() + 1);
let w = chars as f32 * 8.0;
match max_width.map(|m| m.0) {
Some(max) if w > max && max > 0.0 => size_pt(max, (w / max).ceil() * 16.0),
_ => size_pt(w, 16.0),
}
}
fn draws_colors_from_text(&self) -> bool {
self.colors_at_draw
}
fn layout(&self, (chars, attachments): &(usize, Vec<u32>), _: Size<Points>) -> TextLayout {
self.layouts.set(self.layouts.get() + 1);
// One line; the third attachment on is cut off.
let points: Vec<Option<Point<Points>>> = attachments
.iter()
.enumerate()
.map(|(i, &at)| {
(i < 2).then_some(crate::geometry::point(Points(at as f32 * 8.0), Points(2.0)))
})
.collect();
TextLayout(Arc::new(FakeLayout {
chars: *chars,
points,
}))
}
fn attachments(&self, layout: &TextLayout) -> Vec<Option<Point<Points>>> {
layout
.downcast::<FakeLayout>()
.map(|l| l.points.clone())
.unwrap_or_default()
}
}
/// What the core hands JS, with Rust components' events, lazy children and
/// calls' results as the native events JS once heard (`$children`,
/// `$return` with `{ c, v }` or `{ c, e }`), their data as JSON.
fn js_events<M: TextEngine>(c: &mut Core<M>) -> Vec<(NodeId, EventKind, EventPayload)> {
use crate::element::{JsEvent, json_host};
let mut events = Vec::new();
c.take_events(&mut events);
let native = |id, name: &str, data| {
(
id,
EventKind::NativeEvent,
EventPayload::Native {
name: name.into(),
data,
},
)
};
events
.into_iter()
.filter_map(|e| {
Some(match e {
JsEvent::LayoutListener {
host,
id,
listener,
frame,
} => {
c.component_layout(host, id, &listener, frame);
return None;
}
JsEvent::Event(id, kind, payload) => (id, kind, payload),
JsEvent::Component { host, event } => native(
host,
event.name(),
json_host::event_data(&*event).unwrap_or(serde_json::Value::Null),
),
JsEvent::Children { host, wanted } => {
native(host, "$children", crate::JsonValue::Bool(wanted))
}
JsEvent::Render {
host,
prop,
key,
value,
..
} => native(
host,
"$render",
serde_json::json!({
"prop": prop,
"key": key.as_str(),
"value": json_host::render_value(&*value),
}),
),
JsEvent::Unrender { host, prop, key } => native(
host,
"$unrender",
serde_json::json!({ "prop": prop, "key": key.as_str() }),
),
JsEvent::Rows(ids) => native(ROOT_ID, "$rows", serde_json::json!(ids)),
JsEvent::Reply { call, result } => native(
ROOT_ID,
"$return",
match json_host::result(result) {
Ok(v) => serde_json::json!({ "c": call, "v": v }),
Err(e) => serde_json::json!({ "c": call, "e": e }),
},
),
})
})
.collect()
}
/// Prop `name` of a Rust component of props `P`, from JS value `value`
/// (converted as JS's assignment does).
fn rust_prop<P: crate::element::Props>(
name: &'static str,
value: Option<crate::JsonValue>,
) -> Prop {
let specs = P::spec(&mut crate::element::TsTypes::default());
let decode = specs
.iter()
.find(|p| p.name == name)
.and_then(|p| p.decode)
.expect("a value prop");
Prop::RustProp(
name,
value.map(|v| crate::element::json_host::decode(decode, v).expect("the value converts")),
)
}
#[test]
fn calls_into_rust_settle_their_promises_whatever_happens() {
use crate::element::{RustCall, RustOp, ToJs};
let op = |call, run| Op::Rust(RustOp { call, run });
let mut c = core();
// Run: its value.
c.apply(op(
1,
RustCall::Op(Box::new(|_| Ok(Box::new(42.0f64) as Box<dyn ToJs>))),
))
.unwrap();
// A panic: its message.
c.apply(op(2, RustCall::Op(Box::new(|_| panic!("op boom")))))
.unwrap();
// A method of a node that hosts no component.
c.apply(op(3, RustCall::Method(40, Box::new(|_| None))))
.unwrap();
// Not applied (the script stopped): rejected.
c.discard_ops(vec![op(
4,
RustCall::Op(Box::new(|_| Ok(Box::new(1.0f64) as Box<dyn ToJs>))),
)]);
// Call 0 (an op or method returning `()`: JS waits for nothing): run,
// failed or discarded, no reply.
c.apply(op(
0,
RustCall::Op(Box::new(|_| Ok(Box::new(()) as Box<dyn ToJs>))),
))
.unwrap();
c.apply(op(0, RustCall::Op(Box::new(|_| panic!("quiet boom")))))
.unwrap();
c.apply(op(0, RustCall::Method(40, Box::new(|_| None))))
.unwrap();
c.discard_ops(vec![op(
0,
RustCall::Op(Box::new(|_| Ok(Box::new(()) as Box<dyn ToJs>))),
)]);
let replies: Vec<_> = js_events(&mut c)
.into_iter()
.map(|(_, _, payload)| match payload {
EventPayload::Native { data, .. } => data,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
replies,
[
serde_json::json!({ "c": 1, "v": 42 }),
serde_json::json!({ "c": 2, "e": "op boom" }),
serde_json::json!({ "c": 3, "e": "node 40 hosts no Rust component" }),
serde_json::json!({ "c": 4, "e": "the script stopped before the call ran" }),
]
);
}
#[test]
fn a_call_into_rust_that_is_not_async_spawns_tasks_and_makes_signals() {
use std::rc::Rc;
use crate::element::{RustCall, RustOp, ToJs, signal, spawn};
let mut c = core();
let done = Rc::new(Cell::new(0));
let seen = done.clone();
c.apply(Op::Rust(RustOp {
call: 1,
run: RustCall::Op(Box::new(move |_| {
let count = signal(1);
spawn(async move {
count.update(|n| *n += 1);
seen.set(count.get_untracked());
});
Ok(Box::new(()) as Box<dyn ToJs>)
})),
}))
.unwrap();
for _ in 0..10 {
if done.get() != 0 {
break;
}
c.run_component_tasks();
}
assert_eq!(done.get(), 2);
let replies: Vec<_> = js_events(&mut c)
.into_iter()
.map(|(_, _, payload)| match payload {
EventPayload::Native { data, .. } => data,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(replies, [serde_json::json!({ "c": 1, "v": null })]);
}
#[test]
fn tasks_that_end_leave_no_cleanup_on_their_owner() {
use std::rc::Rc;
use crate::element::{Owner, RustCall, RustOp, ToJs, create_root, spawn};
let mut c = core();
let mut call = 0;
// Runs `f` with the graph entered, as a call into Rust does.
let mut run = |c: &mut Core<FakeEngine>, f: Box<dyn FnOnce()>| {
call += 1;
let f = std::cell::RefCell::new(Some(f));
c.apply(Op::Rust(RustOp {
call,
run: RustCall::Op(Box::new(move |_| {
(f.borrow_mut().take().unwrap())();
Ok(Box::new(()) as Box<dyn ToJs>)
})),
}))
.unwrap();
};
let owner = Rc::new(Cell::new(Owner::detached()));
let count = Rc::new(Cell::new(usize::MAX));
let (made, counted) = (owner.clone(), count.clone());
// A long-lived owner: a thousand tasks that end at once, a thousand
// cancelled.
run(
&mut c,
Box::new(move || {
let (root, ()) = create_root(|| {
for _ in 0..1000 {
spawn(async {});
spawn(std::future::pending::<()>()).cancel();
}
});
made.set(root);
counted.set(crate::element::reactive::cleanup_count(root));
}),
);
assert_eq!(count.get(), 1000, "cancelled tasks keep no cleanup");
c.run_component_tasks();
assert_eq!(c.components.executor.task_count(), 0);
let counted = count.clone();
let root = owner.get();
run(
&mut c,
Box::new(move || counted.set(crate::element::reactive::cleanup_count(root))),
);
assert_eq!(count.get(), 0, "finished tasks keep no cleanup");
// A task still running ends with its owner.
run(
&mut c,
Box::new(move || {
root.run(|| spawn(std::future::pending::<()>()));
}),
);
assert_eq!(c.components.executor.task_count(), 1);
run(&mut c, Box::new(move || root.dispose()));
assert_eq!(c.components.executor.task_count(), 0);
}
#[test]
fn functions_for_the_main_thread_wait_for_the_engine_in_order() {
use std::sync::{Arc, Mutex};
use crate::element::{RustCall, RustOp, ToJs, run_on_main_thread, spawn};
let mut c = core();
let ran = Arc::new(Mutex::new(Vec::new()));
let (op, task) = (ran.clone(), ran.clone());
c.apply(Op::Rust(RustOp {
call: 0,
run: RustCall::Op(Box::new(move |cx| {
let first = op.clone();
drop(cx.run_on_main_thread(move || first.lock().unwrap().push("op")));
spawn(async move {
let _ = run_on_main_thread(move || task.lock().unwrap().push("task")).await;
});
Ok(Box::new(()) as Box<dyn ToJs>)
})),
}))
.unwrap();
c.run_component_tasks();
// Nothing runs in the core: the engine hands them to the platform.
assert!(ran.lock().unwrap().is_empty());
for task in c.take_main_thread_tasks() {
task.run();
}
assert_eq!(*ran.lock().unwrap(), ["op", "task"]);
assert!(c.take_main_thread_tasks().is_empty());
}
#[test]
fn values_of_calls_into_rust_that_panic_as_they_drop_stay_in_the_core() {
use crate::element::{JsHost, JsOwned, JsValue, PropError, RustCall, RustOp, ToJs, TsTypes};
/// Panics as it drops.
struct Grenade;
impl Drop for Grenade {
fn drop(&mut self) {
panic!("grenade");
}
}
impl JsValue for Grenade {
fn ts_type(_: &mut TsTypes) -> String {
"null".into()
}
fn from_js(_: crate::element::JsIn<'_>) -> Result<Self, PropError> {
Ok(Grenade)
}
fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
Ok(JsOwned::new(host, host.null()))
}
}
let mut c = core();
// A result nobody waits for.
c.apply(Op::Rust(RustOp {
call: 0,
run: RustCall::Op(Box::new(|_| Ok(Box::new(Grenade) as Box<dyn ToJs>))),
}))
.unwrap();
// A method's arguments when no component takes them.
let grenade = Grenade;
c.apply(Op::Rust(RustOp {
call: 0,
run: RustCall::Method(
40,
Box::new(move |_| {
let _ = &grenade;
None
}),
),
}))
.unwrap();
// A call's arguments when the script stopped.
let grenade = Grenade;
c.discard_ops(vec![Op::Rust(RustOp {
call: 0,
run: RustCall::Op(Box::new(move |_| {
let _ = &grenade;
Err(String::new().into())
})),
})]);
assert!(js_events(&mut c).is_empty());
}
fn core() -> Core<FakeEngine> {
let mut c = Core::new(FakeEngine::default(), size_pt(320.0, 480.0));
c.set_tokens(crate::element::tokens::sample());
c
}
#[test]
fn pan_permission_filters_native_values_and_events_without_losing_them() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::SetProp {
id: 2,
prop: Prop::PanValues(None, Some(7)),
},
Op::Listen {
id: 2,
event: EventKind::PanEnd,
enabled: true,
},
Op::Listen {
id: 2,
event: EventKind::Press,
enabled: true,
},
Op::SetProp {
id: 2,
prop: Prop::PanEnabled(false),
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|item| matches!(item,
MountItem::Events { id: 2, events } if events.contains(EventKind::Press) && !events.contains(EventKind::PanEnd)
)));
assert!(batch.items.iter().any(|item| matches!(item,
MountItem::Gestures { id: 2, values } if values.pan_y.is_none()
)));
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::PanEnabled(true),
}],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|item| matches!(item,
MountItem::Events { id: 2, events } if events.contains(EventKind::PanEnd) && events.contains(EventKind::Press)
)));
assert!(batch.items.iter().any(|item| matches!(item,
MountItem::Gestures { id: 2, values } if values.pan_y == Some(7)
)));
}
/// The tokens of a theme file of the tests' own format, `{ "key":
/// "#rrggbb", … }` over the sample's (`None`: the sample's): the core reads
/// `uiTheme` with what a UI set brings.
fn test_tokens(json: Option<&str>) -> Result<(crate::element::Tokens, Vec<String>), String> {
let mut tokens = crate::element::tokens::sample();
let Some(json) = json else {
return Ok((tokens, Vec::new()));
};
let value: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
for (key, value) in value.as_object().ok_or("not an object")? {
let color = value.as_str().and_then(Color::parse).ok_or("not a color")?;
tokens.set_color(key, color.into());
}
Ok((tokens, Vec::new()))
}
/// Tokens with just `colors`.
fn tokens_with(colors: &[(&str, crate::element::AdaptiveColor)]) -> crate::element::Tokens {
let mut tokens = crate::element::Tokens::default();
for (key, color) in colors {
tokens.set_color(key, *color);
}
tokens
}
/// Color token `key` of the tokens apps have.
fn token(key: &str) -> crate::element::AdaptiveColor {
crate::element::tokens::sample().color(key).unwrap()
}
fn style(props: &[(&str, StyleValue<'_>)]) -> Box<Style> {
let mut s = Style::default();
for &(k, v) in props {
s.set(k, v).unwrap();
}
Box::new(s)
}
fn style_op(id: NodeId, props: &[(&str, StyleValue<'_>)]) -> Op {
let mut style = Box::<Style>::default();
let mut patch = StylePatch::default();
for &(k, v) in props {
patch.set(&mut style, k, v).unwrap();
}
Op::SetStyle { id, style, patch }
}
fn apply<M: TextEngine>(core: &mut Core<M>, ops: Vec<Op>) {
for op in ops {
core.apply(op).unwrap();
}
}
fn frame_of(batch: &MountBatch, id: NodeId) -> Option<Bounds<Points>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Frame { id: i, frame } if *i == id => Some(*frame),
_ => None,
})
}
/// A text stretched across a column wraps at its content box: its padding
/// and border are not room for its lines. Measured at the width of its
/// border box, it got the height of fewer lines than its content box
/// holds, and the platforms cut the lines left over with an ellipsis.
#[test]
fn a_stretched_text_wraps_at_its_content_box() {
for (padding, border) in [(10.0, 0.0), (0.0, 10.0), (6.0, 4.0)] {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::Text,
},
// 11 characters, 88pt: one line in the column's 100pt, two
// in the text's 80pt content box.
Op::CreateText {
id: 4,
text: "hello world".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
style_op(2, &[("width", StyleValue::Number(100.0))]),
style_op(
3,
&[
("paddingHorizontal", StyleValue::Number(padding)),
("borderWidth", StyleValue::Number(border)),
],
),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let content = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 3, content, .. } => Some(*content),
_ => None,
})
.expect("the text mounted");
let inset = padding + border;
assert_eq!(
content,
Bounds::new(
Point::new(Points(inset), Points(border)),
size_pt(100.0 - 2.0 * inset, 32.0)
),
"padding {padding}, border {border}"
);
assert_eq!(
frame_of(&batch, 3).map(|f| f.size),
Some(size_pt(100.0, 32.0 + 2.0 * border))
);
}
}
#[test]
fn mounts_subtree_built_detached() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::CreateText {
id: 4,
text: "hello".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
style_op(2, &[("padding", StyleValue::Number(10.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let creates: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Create { id, kind } => Some((*id, *kind)),
_ => None,
})
.collect();
// Raw text never becomes a native view.
assert_eq!(creates, vec![(2, ViewKind::View), (3, ViewKind::Text)]);
let text = batch.items.iter().find_map(|i| match i {
MountItem::Text { id: 3, text, .. } => Some(text.clone()),
_ => None,
});
assert_eq!(text.unwrap().text, "hello");
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 320.0, 36.0)));
assert_eq!(frame_of(&batch, 3), Some(rect(10.0, 10.0, 300.0, 16.0)));
assert!(c.commit().is_none(), "second commit is a no-op");
}
#[test]
fn a_spans_test_id_is_in_its_blocks_text() {
let mut c = core();
let text_of = |c: &mut Core<_>| {
c.commit().unwrap().items.into_iter().find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text),
_ => None,
})
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::Listen {
id: 2,
event: EventKind::TextLayout,
enabled: true,
},
Op::CreateText {
id: 3,
text: "see ".into(),
},
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 5,
text: "docs".into(),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(text_of(&mut c).unwrap().test_ids, []);
js_events(&mut c);
let prepares = c.text_engine.prepares.get();
let layouts = c.text_engine.layouts.get();
let measures = c.text_engine.measures.get();
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::TestId(Some("docs".into())),
}],
);
assert_eq!(
text_of(&mut c).unwrap().test_ids,
[crate::SpanTestId {
start: 4,
end: 8,
test_id: "docs".into(),
}]
);
assert_eq!(
c.text_engine.layouts.get(),
layouts,
"test IDs are metadata, not glyphs"
);
assert_eq!(c.text_engine.prepares.get(), prepares);
assert_eq!(c.text_engine.measures.get(), measures);
assert!(js_events(&mut c).is_empty(), "no onTextLayout for test IDs");
for id in [Some("renamed"), None] {
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::TestId(id.map(Into::into)),
}],
);
let text = text_of(&mut c).unwrap();
assert_eq!(text.test_ids.first().map(|s| s.test_id.as_ref()), id);
assert_eq!(c.text_engine.layouts.get(), layouts);
assert_eq!(c.text_engine.prepares.get(), prepares);
assert_eq!(c.text_engine.measures.get(), measures);
assert!(js_events(&mut c).is_empty());
}
// A simultaneous content change still rebuilds the native text.
apply(
&mut c,
vec![
Op::SetText {
id: 5,
text: "updated docs".into(),
},
Op::SetProp {
id: 4,
prop: Prop::TestId(Some("updated".into())),
},
],
);
let text = text_of(&mut c).unwrap();
assert_eq!(text.text, "see updated docs");
assert_eq!(text.test_ids[0].test_id.as_ref(), "updated");
assert!(c.text_engine.layouts.get() > layouts);
assert!(
js_events(&mut c)
.iter()
.any(|e| e.1 == EventKind::TextLayout)
);
}
#[test]
fn an_attachments_copy_text_is_copied_in_its_place() {
let mut c = core();
let text_of = |c: &mut Core<_>| {
c.commit().unwrap().items.into_iter().find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text),
_ => None,
})
};
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::Listen {
id: 2,
event: EventKind::TextLayout,
enabled: true,
},
Op::CreateText {
id: 3,
text: "Area is ".into(),
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(10.0)),
],
),
Op::SetProp {
id: 4,
prop: Prop::CopyText(Some("$x^2$".into())),
},
Op::CreateText {
id: 5,
text: " here.".into(),
},
insert(2, 3),
insert(2, 4),
insert(2, 5),
insert(ROOT_ID, 2),
],
);
let text = text_of(&mut c).unwrap();
assert_eq!(text.text, "Area is \u{FFFC} here.");
assert_eq!(text.copied_text(0..text.len_utf16()), "Area is $x^2$ here.");
js_events(&mut c);
let prepares = c.text_engine.prepares.get();
let layouts = c.text_engine.layouts.get();
let measures = c.text_engine.measures.get();
// A new copy text, or none, is the text's metadata: mounted again
// without typesetting it again.
for (copy, copied) in [
(Some("$y$"), "Area is $y$ here."),
(Some(""), "Area is here."),
(Some("$z$"), "Area is $z$ here."),
(None, "Area is here."),
] {
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::CopyText(copy.map(Into::into)),
}],
);
let text = text_of(&mut c).unwrap();
assert_eq!(text.copied_text(0..text.len_utf16()), copied);
assert_eq!(c.text_engine.layouts.get(), layouts);
assert_eq!(c.text_engine.prepares.get(), prepares);
assert_eq!(c.text_engine.measures.get(), measures);
assert!(js_events(&mut c).is_empty(), "no onTextLayout");
}
// A view outside a text: nothing to rebuild.
apply(
&mut c,
vec![
Op::Create {
id: 6,
tag: Tag::View,
},
insert(ROOT_ID, 6),
],
);
c.commit();
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::CopyText(Some("unused".into())),
}],
);
assert!(c.commit().is_none());
}
#[test]
fn a_fitted_texts_new_copy_text_is_mounted() {
// A text fitted to its box mounts its laid out (scaled) text again for
// new metadata: the new copy texts come with it.
let mut c = core();
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
style_op(
2,
&[
("width", StyleValue::Number(30.0)),
("height", StyleValue::Number(16.0)),
("fontSize", StyleValue::Number(20.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::AdjustsFontSizeToFit(true),
},
Op::CreateText {
id: 3,
text: "long enough to shrink ".into(),
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(10.0)),
],
),
Op::SetProp {
id: 4,
prop: Prop::CopyText(Some("$x$".into())),
},
insert(2, 3),
insert(2, 4),
insert(ROOT_ID, 2),
],
);
let text_of = |c: &mut Core<_>| {
c.commit().unwrap().items.into_iter().find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text),
_ => None,
})
};
let text = text_of(&mut c).unwrap();
assert!(
text.spans[0].style.font_size < Points(20.0),
"the text is fitted"
);
assert_eq!(
text.copied_text(0..text.len_utf16()),
"long enough to shrink $x$"
);
let layouts = c.text_engine.layouts.get();
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::CopyText(Some("$y$".into())),
}],
);
let text = text_of(&mut c).expect("mounted again");
assert_eq!(
text.copied_text(0..text.len_utf16()),
"long enough to shrink $y$"
);
assert!(text.spans[0].style.font_size < Points(20.0));
assert_eq!(c.text_engine.layouts.get(), layouts);
}
#[test]
fn text_update_emits_only_text_and_frames() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "a".into(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
c.apply(Op::SetText {
id: 3,
text: "abc".into(),
})
.unwrap();
let batch = c.commit().unwrap();
assert!(matches!(&batch.items[0], MountItem::Text { id: 2, text, .. } if text.text == "abc"));
// Text blocks stretch to the column width, so only the content changes.
assert_eq!(batch.items.len(), 1);
}
#[test]
fn text_out_of_the_layout_shows_no_glyphs() {
// `display: none` leaves a text no box, and a platform that does not
// clip text to its box (a browser) would draw what was laid out in it:
// a checkbox's hidden check over its shown dash.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 5,
text: "✓".into(),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
class_op(4, "hidden"),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
// The text and how many of its characters are laid out.
let text_of = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::Text {
id: 4,
text,
layout,
..
} => Some((
text.text.clone(),
layout.downcast::<FakeLayout>().unwrap().chars,
)),
_ => None,
})
};
// The text stays what it is (tests and screen readers read it); none of
// it is laid out.
let hidden = Some(("✓".to_owned(), 0));
let shown = Some(("✓".to_owned(), 1));
assert_eq!(text_of(&c.commit().unwrap()), hidden);
let mut toggle = |id, classes, expected: &Option<(String, usize)>| {
c.apply(class_op(id, classes)).unwrap();
assert_eq!(&text_of(&c.commit().unwrap()), expected, "{id}: {classes}");
};
toggle(4, "flex", &shown);
// Hidden by its own class, then by its parent's.
toggle(4, "hidden", &hidden);
toggle(4, "flex", &shown);
toggle(2, "hidden", &hidden);
toggle(2, "flex", &shown);
// New text while hidden: sent, still laid out empty.
apply(
&mut c,
vec![
class_op(2, "hidden"),
Op::SetText {
id: 5,
text: "–".into(),
},
],
);
assert_eq!(text_of(&c.commit().unwrap()), Some(("–".to_owned(), 0)));
}
/// A column styled `column` whose width comes from its content, in a parent
/// that does not stretch it, around a row or column with text: the frames of
/// the column and of the text.
fn max_width_column(
column: &[(&str, StyleValue<'_>)],
row: bool,
chars: usize,
) -> (Option<Bounds<Points>>, Option<Bounds<Points>>) {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 7,
tag: Tag::View,
},
style_op(7, &[("alignItems", StyleValue::Str("flex-start"))]),
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, column),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[(
"flexDirection",
StyleValue::Str(if row { "row" } else { "column" }),
)],
),
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(
6,
&[("width", StyleValue::Number(if row { 40.0 } else { 0.0 }))],
),
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 5,
text: "x".repeat(chars),
},
];
if row {
ops.push(style_op(4, &[("flex", StyleValue::Number(1.0))]));
}
for (parent, child) in [(4, 5), (3, 6), (3, 4), (2, 3), (7, 2), (ROOT_ID, 7)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
(frame_of(&batch, 2), frame_of(&batch, 4))
}
#[test]
fn a_clamped_column_is_as_tall_as_its_wrapped_text() {
let max = [("maxWidth", StyleValue::Number(200.0))];
// `flex: 1` text beside 40pt: 400pt in 160pt is three lines.
let (column, text) = max_width_column(&max, true, 50);
assert_eq!(
column.map(|f| (f.size.width.0, f.size.height.0)),
Some((200.0, 48.0))
);
assert_eq!(
text.map(|f| (f.size.width.0, f.size.height.0)),
Some((160.0, 48.0))
);
// The same when the `flex: 1` item is in a slot holder laid out through.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 7,
tag: Tag::View,
},
style_op(7, &[("alignItems", StyleValue::Str("flex-start"))]),
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &max),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("flexDirection", StyleValue::Str("row"))]),
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(6, &[("width", StyleValue::Number(40.0))]),
Op::Create {
id: 8,
tag: Tag::View,
},
Op::SetProp {
id: 8,
prop: Prop::ComponentSlot("default".into()),
},
Op::Create {
id: 4,
tag: Tag::Text,
},
style_op(4, &[("flex", StyleValue::Number(1.0))]),
Op::CreateText {
id: 5,
text: "x".repeat(50),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 8,
child: 4,
before: None,
},
Op::Insert {
parent: 3,
child: 6,
before: None,
},
Op::Insert {
parent: 3,
child: 8,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 7,
child: 2,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 7,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 2).map(|f| (f.size.width.0, f.size.height.0)),
Some((200.0, 48.0))
);
assert_eq!(
frame_of(&batch, 4).map(|f| (f.size.width.0, f.size.height.0)),
Some((160.0, 48.0))
);
// Text alone: 400pt in 200pt is two lines.
let (column, _) = max_width_column(&max, false, 50);
assert_eq!(
column.map(|f| (f.size.width.0, f.size.height.0)),
Some((200.0, 32.0))
);
// With a minimum, and padding inside the limit: 400pt in 140pt.
let (column, _) = max_width_column(
&[
("minWidth", StyleValue::Number(100.0)),
("maxWidth", StyleValue::Number(200.0)),
("padding", StyleValue::Number(10.0)),
],
true,
50,
);
assert_eq!(
column.map(|f| (f.size.width.0, f.size.height.0)),
Some((200.0, 68.0))
);
// Out of flow, where nothing clamps the space it is measured in.
let (column, _) = max_width_column(
&[
("position", StyleValue::Str("absolute")),
("maxWidth", StyleValue::Number(200.0)),
],
true,
50,
);
assert_eq!(
column.map(|f| (f.size.width.0, f.size.height.0)),
Some((200.0, 48.0))
);
// A limit nothing reaches changes nothing.
let (column, _) = max_width_column(&max, false, 10);
assert_eq!(
column.map(|f| (f.size.width.0, f.size.height.0)),
Some((80.0, 16.0))
);
}
#[test]
fn flex_text_in_a_row_shrinks_and_wraps() {
// Yoga has no automatic minimum size: `flex: 1` text takes the space
// left in the row and wraps, however long its natural width.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("flexDirection", StyleValue::Str("row"))]),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[
("width", StyleValue::Number(120.0)),
("height", StyleValue::Number(10.0)),
],
),
Op::Create {
id: 4,
tag: Tag::Text,
},
style_op(4, &[("flex", StyleValue::Number(1.0))]),
Op::CreateText {
id: 5,
text: "x".repeat(50),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
// 400pt of text in 200pt: two lines.
assert_eq!(frame_of(&batch, 4), Some(rect(120.0, 0.0, 200.0, 32.0)));
}
#[test]
fn nested_spans_merge_with_styles() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "Count: ".into(),
},
Op::Create {
id: 4,
tag: Tag::Text,
},
style_op(4, &[("fontWeight", StyleValue::Str("bold"))]),
Op::CreateText {
id: 5,
text: "1".into(),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { text, .. } => Some(text.clone()),
_ => None,
})
.unwrap();
assert_eq!(text.text, "Count: 1");
assert_eq!(text.spans.len(), 2);
assert_eq!(text.spans[1].style.font_weight, 700);
// The span has no native view.
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { id: 4, .. }))
);
}
/// The attributed text of the first `Text` item in `batch`.
fn text_item(batch: &MountBatch) -> Option<Arc<AttributedText>> {
batch.items.iter().find_map(|i| match i {
MountItem::Text { text, .. } => Some(text.clone()),
_ => None,
})
}
#[test]
fn span_backgrounds_style_their_characters() {
// <Text>a <Text bg r=4>b<Text bold>c</Text></Text> d</Text>
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
style_op(2, &[("backgroundColor", StyleValue::Str("#00ff00"))]),
Op::CreateText {
id: 3,
text: "a ".into(),
},
Op::Create {
id: 4,
tag: Tag::Text,
},
style_op(
4,
&[
("backgroundColor", StyleValue::Str("#ff0000")),
("borderRadius", StyleValue::Number(4.0)),
],
),
Op::CreateText {
id: 5,
text: "b".into(),
},
Op::Create {
id: 6,
tag: Tag::Text,
},
style_op(6, &[("fontWeight", StyleValue::Str("bold"))]),
Op::CreateText {
id: 7,
text: "c".into(),
},
Op::CreateText {
id: 8,
text: " d".into(),
},
Op::Insert {
parent: 6,
child: 7,
before: None,
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 8,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let text = text_item(&batch).unwrap();
assert_eq!(text.text, "a bc d");
let backgrounds: Vec<_> = text.spans.iter().map(|s| s.style.background).collect();
let red = Some(crate::text::TextBackground {
color: Color(0xff00_00ff),
radius: Points(4.0),
node: 4,
top: Default::default(),
bottom: Default::default(),
});
// The block's own background is its view's; the bold span inside the
// red one keeps the red one's.
assert_eq!(backgrounds, [None, red, red, None]);
assert!(text.has_backgrounds());
// The view draws the block's background.
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0x00ff_00ff)
);
// A new color draws again without measuring again.
apply(
&mut c,
vec![style_op(
4,
&[("backgroundColor", StyleValue::Str("#0000ff"))],
)],
);
let batch = c.commit().unwrap();
let text = text_item(&batch).unwrap();
assert_eq!(
text.spans[1].style.background.map(|b| (b.color, b.radius)),
Some((Color(0x0000_ffff), Points(0.0)))
);
assert!(frame_of(&batch, 2).is_none());
// Transparent is none.
apply(
&mut c,
vec![style_op(
4,
&[("backgroundColor", StyleValue::Str("transparent"))],
)],
);
let text = text_item(&c.commit().unwrap()).unwrap();
assert!(!text.has_backgrounds());
}
/// `<Text>a <Text visibility={hidden} red pressable>b<Text bold>c</Text></Text> d</Text>`.
fn hidden_span_ops(hidden: bool) -> Vec<Op> {
let visibility = if hidden { "hidden" } else { "visible" };
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "a ".into(),
},
Op::Create {
id: 4,
tag: Tag::Text,
},
style_op(
4,
&[
("visibility", StyleValue::Str(visibility)),
("color", StyleValue::Str("#ff0000")),
("backgroundColor", StyleValue::Str("#00ff00")),
],
),
Op::Listen {
id: 4,
event: EventKind::Press,
enabled: true,
},
Op::CreateText {
id: 5,
text: "b".into(),
},
Op::Create {
id: 6,
tag: Tag::Text,
},
style_op(6, &[("fontWeight", StyleValue::Str("bold"))]),
Op::CreateText {
id: 7,
text: "c".into(),
},
Op::CreateText {
id: 8,
text: " d".into(),
},
Op::Insert {
parent: 6,
child: 7,
before: None,
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 8,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
]
}
#[test]
fn hidden_spans_keep_their_place_and_stay_out_of_copies() {
let mut shown = core();
apply(&mut shown, hidden_span_ops(false));
let batch = shown.commit().unwrap();
let visible = text_item(&batch).unwrap();
let visible_frame = frame_of(&batch, 2).unwrap();
assert!(!visible.has_hidden());
let mut c = core();
apply(&mut c, hidden_span_ops(true));
let batch = c.commit().unwrap();
let text = text_item(&batch).unwrap();
// The characters stay in the text and lay out as visible ones.
assert_eq!(text.text, "a bc d");
assert!(text.layout_eq(&visible));
assert_eq!(frame_of(&batch, 2), Some(visible_frame));
// The span and the one inside it are hidden: nothing of them is drawn.
let hidden: Vec<_> = text.spans.iter().map(|s| s.style.hidden).collect();
assert_eq!(hidden, [false, true, true, false]);
for s in &text.spans[1..3] {
assert_eq!(s.style.color, Color::TRANSPARENT);
assert_eq!(s.style.background, None);
}
assert_eq!(text.spans[2].style.font_weight, 700);
// No press for hidden characters, nor a color transition over them.
assert!(text.links.is_empty());
assert_eq!(visible.links.len(), 1);
assert_eq!(text.uniform_color(), None);
// Copies and screen readers leave them out.
assert_eq!(text.visible_text(), "a d");
assert_eq!(text.copied_text(0..6), "a d");
assert_eq!(text.copied_text(2..4), "");
assert_eq!(text.copied_text(1..5), " ");
assert_eq!(visible.copied_text(1..5), " bc ");
assert_eq!(visible.visible_text(), "a bc d");
// Shown again: drawn again, without measuring or moving anything.
apply(
&mut c,
vec![style_op(
4,
&[
("visibility", StyleValue::Str("visible")),
("color", StyleValue::Str("#ff0000")),
("backgroundColor", StyleValue::Str("#00ff00")),
],
)],
);
let batch = c.commit().unwrap();
let text = text_item(&batch).unwrap();
assert!(!text.has_hidden());
assert_eq!(text.spans[1].style.color, Color(0xff00_00ff));
assert_eq!(text.links.len(), 1);
assert!(frame_of(&batch, 2).is_none());
}
#[test]
fn attachments_of_hidden_spans_are_hidden_with_them() {
let mut c = core();
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let size = |id| {
style_op(
id,
&[
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(10.0)),
],
)
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "ab".into(),
},
// A hidden span holding a view, and a span inside it holding
// an image.
Op::Create {
id: 4,
tag: Tag::Text,
},
style_op(4, &[("visibility", StyleValue::Str("hidden"))]),
Op::Create {
id: 6,
tag: Tag::View,
},
size(6),
Op::Listen {
id: 6,
event: EventKind::Press,
enabled: true,
},
Op::Create {
id: 8,
tag: Tag::Text,
},
Op::Create {
id: 10,
tag: Tag::Image,
},
size(10),
// A view of the block itself stays.
Op::Create {
id: 12,
tag: Tag::View,
},
size(12),
insert(8, 10),
insert(4, 6),
insert(4, 8),
insert(2, 3),
insert(2, 4),
insert(2, 12),
insert(ROOT_ID, 2),
],
);
let batch = c.commit().unwrap();
assert_eq!(hidden_in(&batch, 6), (Some(true), Some(true)));
assert_eq!(hidden_in(&batch, 10), (Some(true), Some(true)));
assert_eq!(hidden_in(&batch, 12), (None, None));
// They keep their place (laid out as when shown); a hidden view takes
// no presses.
assert!(frame_of(&batch, 6).is_some());
assert!(frame_of(&batch, 10).is_some());
// Shown again with the span.
apply(
&mut c,
vec![style_op(4, &[("visibility", StyleValue::Str("visible"))])],
);
let batch = c.commit().unwrap();
assert_eq!(hidden_in(&batch, 6), (Some(false), Some(false)));
assert_eq!(hidden_in(&batch, 10), (Some(false), Some(false)));
// Hidden again, then moved out of the text into a plain view: shown
// there.
apply(
&mut c,
vec![style_op(4, &[("visibility", StyleValue::Str("hidden"))])],
);
let batch = c.commit().unwrap();
assert_eq!(hidden_in(&batch, 6), (Some(true), Some(true)));
apply(
&mut c,
vec![
Op::Create {
id: 14,
tag: Tag::View,
},
insert(ROOT_ID, 14),
Op::Remove {
parent: 4,
child: 6,
},
insert(14, 6),
],
);
let batch = c.commit().unwrap();
assert_eq!(hidden_in(&batch, 6), (Some(false), Some(false)));
}
#[test]
fn visible_ranges_leave_hidden_runs_out() {
let plain = ResolvedTextStyle::default();
let mut t = AttributedText::default();
t.push("ab", plain);
t.push("cd", plain.hide());
t.push("ef", plain);
t.push("g", plain.hide());
assert_eq!(t.visible_ranges(0..7), vec![0..2, 4..6]);
assert_eq!(t.visible_ranges(1..5), vec![1..2, 4..5]);
assert_eq!(t.visible_ranges(2..4), Vec::<std::ops::Range<u32>>::new());
assert!(t.hidden_at(2) && t.hidden_at(6) && !t.hidden_at(4));
let mut shown = AttributedText::default();
shown.push("abc", plain);
assert_eq!(shown.visible_ranges(1..3), vec![1..3]);
}
#[test]
fn copied_text_puts_attachments_copy_texts_in_their_place() {
let plain = ResolvedTextStyle::default();
let mut t = AttributedText::default();
t.push("Area is ", plain);
t.copy_texts
.push(crate::AttachmentCopyText::new(t.len_utf16(), "$x^2$"));
t.push_attachment(crate::geometry::size_pt(20.0, 10.0), plain);
t.push(" and ", plain);
// No copy text: left out, as before.
t.push_attachment(crate::geometry::size_pt(8.0, 8.0), plain);
t.push("\u{1F600}", plain);
t.copy_texts
.push(crate::AttachmentCopyText::new(t.len_utf16(), "\u{2764}"));
t.push_attachment(crate::geometry::size_pt(8.0, 8.0), plain.hide());
t.push(" here.", plain);
let len = t.len_utf16();
assert_eq!(t.copied_text(0..len), "Area is $x^2$ and \u{1F600} here.");
// Only an attachment inside the range is copied.
assert_eq!(t.copied_text(8..9), "$x^2$");
assert_eq!(t.copied_text(0..8), "Area is ");
assert_eq!(t.copied_text(9..len), " and \u{1F600} here.");
// What accessibility reads of the text itself leaves them all out.
assert_eq!(
t.text_without_attachments(0..len),
"Area is and \u{1F600} here."
);
}
#[test]
fn copied_text_skips_hidden_runs_and_attachments() {
let plain = ResolvedTextStyle::default();
let mut t = AttributedText::default();
t.push("a\u{1F600}", plain);
t.push("bc", plain.hide());
t.push_attachment(crate::geometry::size_pt(4.0, 4.0), plain);
t.push("d\u{1F600}e", plain);
// a 😀(2) b c  d 😀(2) e: 10 UTF-16 units.
assert_eq!(t.len_utf16(), 10);
assert_eq!(t.copied_text(0..10), "a\u{1F600}d\u{1F600}e");
assert_eq!(t.visible_text(), "a\u{1F600}\u{FFFC}d\u{1F600}e");
assert_eq!(t.copied_text(1..4), "\u{1F600}");
assert_eq!(t.copied_text(3..7), "d");
// A range past the end is clamped; one inside a surrogate pair starts
// at the pair.
assert_eq!(t.copied_text(8..99), "\u{1F600}e");
assert_eq!(t.copied_text(12..20), "");
}
#[test]
fn background_boxes_join_pieces_of_one_span() {
let mut t = AttributedText::default();
let plain = ResolvedTextStyle::default();
let bg = |node| crate::text::TextBackground {
color: Color(0xff00_00ff),
radius: Points(3.0),
node,
top: Points::ZERO,
bottom: Points::ZERO,
};
let code = ResolvedTextStyle {
background: Some(bg(4)),
..plain
};
let bold = ResolvedTextStyle {
font_weight: 700,
..code
};
// "a " "bc" (one background, two runs) "d" " e" (a span of its own,
// looking the same) " "
t.push("a ", plain);
t.push("b", code);
t.push("c", bold);
t.push(
"d",
ResolvedTextStyle {
background: Some(bg(6)),
..plain
},
);
t.push(" e ", plain);
let piece = |i: u32, ascent: f32| crate::text::LinePiece {
x: Points(i as f32 * 10.0),
width: Points(10.0),
background: t.background_at(i),
ascent: Points(ascent),
descent: Points(2.0),
};
let pieces = (0..7).map(|i| piece(i, if i == 3 { 12.0 } else { 10.0 }));
let mut boxes = Vec::new();
crate::text::BackgroundBox::join(pieces, (Points(0.0), Points(70.0)), |b| boxes.push(b));
assert_eq!(boxes.len(), 2);
assert_eq!((boxes[0].x.0, boxes[0].width.0), (20.0, 20.0));
assert_eq!((boxes[0].ascent.0, boxes[0].descent.0), (12.0, 2.0));
assert_eq!(boxes[0].background.node, 4);
assert_eq!((boxes[1].x.0, boxes[1].width.0), (40.0, 10.0));
assert_eq!(boxes[1].background.node, 6);
// At most half its height.
assert_eq!(boxes[0].radius(), Points(3.0));
assert_eq!(
crate::text::BackgroundBox {
ascent: Points(2.0),
descent: Points(1.0),
..boxes[0]
}
.radius(),
Points(1.5)
);
// Cut to the line.
let mut boxes = Vec::new();
crate::text::BackgroundBox::join(
(0..7).map(|i| piece(i, 10.0)),
(Points(0.0), Points(25.0)),
|b| boxes.push(b),
);
assert_eq!(boxes.len(), 1);
assert_eq!((boxes[0].x.0, boxes[0].width.0), (20.0, 5.0));
// A background's top and bottom room (its span's vertical padding)
// grows the box past the font's ascent and descent.
let padded = |i: u32| crate::text::LinePiece {
background: t.background_at(i).map(|b| crate::text::TextBackground {
top: Points(3.0),
bottom: Points(1.0),
..b
}),
..piece(i, 10.0)
};
let mut boxes = Vec::new();
crate::text::BackgroundBox::join((0..7).map(padded), (Points(0.0), Points(70.0)), |b| {
boxes.push(b)
});
assert_eq!((boxes[0].ascent.0, boxes[0].descent.0), (13.0, 3.0));
}
#[test]
fn placeholder_text_outside_text_is_ignored() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::CreateText {
id: 3,
text: String::new(),
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: Some(2),
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
let batch = c.commit().unwrap();
let inserts: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert { child, before, .. } => Some((*child, *before)),
_ => None,
})
.collect();
assert_eq!(inserts, vec![(2, None), (4, None)]);
}
#[test]
fn remove_reinsert_and_release() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
c.commit().unwrap();
// Move 3 before 2: a single insert, no remove.
c.apply(Op::Insert {
parent: ROOT_ID,
child: 3,
before: Some(2),
})
.unwrap();
let batch = c.commit().unwrap();
assert!(matches!(
batch.items[0],
MountItem::Insert {
child: 3,
before: Some(2),
..
}
));
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { .. }))
);
c.apply(Op::Remove {
parent: ROOT_ID,
child: 2,
})
.unwrap();
let batch = c.commit().unwrap();
assert!(matches!(batch.items[0], MountItem::Remove { id: 2 }));
// Reinserting a detached, already-created view does not recreate it.
c.apply(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
})
.unwrap();
let batch = c.commit().unwrap();
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { .. }))
);
c.apply(Op::Release { id: 2 }).unwrap();
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id: 2 }))
);
assert_eq!(c.node_count(), 2);
assert_eq!(
c.apply(Op::SetText {
id: 2,
text: String::new()
}),
Err(ApplyError::UnknownNode(2))
);
}
#[test]
fn events_and_errors() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Listen {
id: 2,
event: EventKind::Press,
enabled: true,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(
|i| matches!(i, MountItem::Events { id: 2, events } if events.contains(EventKind::Press))
));
assert_eq!(
c.apply(Op::Create {
id: 2,
tag: Tag::View
}),
Err(ApplyError::DuplicateNode(2))
);
assert_eq!(
c.apply(Op::Insert {
parent: 2,
child: ROOT_ID,
before: None
}),
Err(ApplyError::Cycle(1))
);
}
#[test]
fn color_change_skips_layout_and_identical_texts_share_measurements() {
let mut c = core();
let mut ops = Vec::new();
for i in 0..3u32 {
let (block, raw) = (10 + i * 2, 11 + i * 2);
ops.extend([
Op::Create {
id: block,
tag: Tag::Text,
},
Op::CreateText {
id: raw,
text: "same".into(),
},
Op::Insert {
parent: block,
child: raw,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: block,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
// Three identical texts: measured once per distinct constraint.
let first_measures = c.text_engine.measures.get();
assert!(first_measures <= 2, "measured {first_measures} times");
assert_eq!(c.text_engine.layouts.get(), 3);
let content = batch.items.iter().find_map(|i| match i {
MountItem::Text {
id: 10, content, ..
} => Some(*content),
_ => None,
});
assert_eq!(content, Some(rect(0.0, 0.0, 320.0, 16.0)));
c.apply(style_op(10, &[("color", StyleValue::Str("red"))]))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(
batch.items.len(),
1,
"only the new text layout: {:?}",
batch.items
);
assert!(matches!(&batch.items[0], MountItem::Text { id: 10, .. }));
assert_eq!(
c.text_engine.measures.get(),
first_measures,
"no re-measure"
);
assert_eq!(c.text_engine.layouts.get(), 4);
}
/// A text block (10) of three words, each a span of its own (12, 14, 16;
/// their raw texts 13, 15, 17), on an engine that draws colors from the
/// text or not; `ops` run before the block's first commit.
fn three_words(colors_at_draw: bool, ops: Vec<Op>) -> Core<FakeEngine> {
let mut c = Core::new(
FakeEngine {
colors_at_draw,
..FakeEngine::default()
},
size_pt(320.0, 480.0),
);
let mut block = vec![Op::Create {
id: 10,
tag: Tag::Text,
}];
for (i, word) in ["fade ", "in ", "words"].into_iter().enumerate() {
let (span, raw) = (12 + i as u32 * 2, 13 + i as u32 * 2);
block.extend([
Op::Create {
id: span,
tag: Tag::Text,
},
Op::CreateText {
id: raw,
text: word.into(),
},
Op::Insert {
parent: span,
child: raw,
before: None,
},
Op::Insert {
parent: 10,
child: span,
before: None,
},
]);
}
block.push(Op::Insert {
parent: ROOT_ID,
child: 10,
before: None,
});
block.extend(ops);
apply(&mut c, block);
c
}
/// The text block 10 mounted in `batch`: its text, layout and content box.
fn mounted_words(batch: &MountBatch) -> Option<(Arc<AttributedText>, TextLayout, Bounds<Points>)> {
batch.items.iter().find_map(|i| match i {
MountItem::Text {
id: 10,
text,
layout,
content,
} => Some((text.clone(), layout.clone(), *content)),
_ => None,
})
}
/// How many times the engine typeset, measured and laid out a text.
fn engine_counts(c: &Core<FakeEngine>) -> (u32, u32, u32) {
let e = &c.text_engine;
(e.prepares.get(), e.measures.get(), e.layouts.get())
}
#[test]
fn colors_drawn_from_the_text_keep_its_typesetting() {
let mut c = three_words(true, Vec::new());
let mounted = mounted_words;
let counts = engine_counts;
let (_, first, content) = mounted(&c.commit().unwrap()).expect("mounted");
let before = counts(&c);
let color = |c: &mut Core<FakeEngine>, id, color| {
c.apply(style_op(id, &[("color", StyleValue::Str(color))]))
.unwrap();
c.commit().unwrap()
};
// A word fading in: a new color, the same span boundaries.
let batch = color(&mut c, 14, "rgba(255, 0, 0, 0.5)");
assert_eq!(batch.items.len(), 1, "only the text: {:?}", batch.items);
let (text, layout, moved) = mounted(&batch).expect("the new text mounted");
assert_eq!(text.spans[1].style.color, Color(0xff00_0080));
assert!(Arc::ptr_eq(&layout.0, &first.0), "the layout drawn before");
assert_eq!(moved, content);
assert_eq!(counts(&c), before, "no typesetting, measuring or layout");
// Its neighbors take its color: the three spans merge into one.
color(&mut c, 12, "rgba(255, 0, 0, 0.5)");
let batch = color(&mut c, 16, "rgba(255, 0, 0, 0.5)");
let (text, layout, _) = mounted(&batch).expect("the new text mounted");
assert_eq!(text.spans.len(), 1);
assert!(Arc::ptr_eq(&layout.0, &first.0));
assert_eq!(counts(&c), before);
// A change of size is typeset again.
c.apply(style_op(14, &[("fontSize", StyleValue::Number(20.0))]))
.unwrap();
let (_, layout, _) = mounted(&c.commit().unwrap()).expect("the new text mounted");
assert!(!Arc::ptr_eq(&layout.0, &first.0));
assert!(c.text_engine.prepares.get() > before.0);
}
#[test]
fn hidden_words_drawn_from_the_text_keep_its_typesetting() {
let visibility = |id, v| style_op(id, &[("visibility", StyleValue::Str(v))]);
// The last two words are queued: hidden, in their place in the lines.
let mut c = three_words(
true,
vec![visibility(14, "hidden"), visibility(16, "hidden")],
);
let (text, first, content) = mounted_words(&c.commit().unwrap()).expect("mounted");
assert_eq!(text.visible_text(), "fade ");
let before = engine_counts(&c);
let show = |c: &mut Core<FakeEngine>, ops: Vec<Op>| {
apply(c, ops);
let batch = c.commit().unwrap();
assert_eq!(batch.items.len(), 1, "only the text: {:?}", batch.items);
mounted_words(&batch).expect("the new text mounted")
};
// A word starts: shown, as a color would change, with the layout
// already drawn and nothing typeset, measured or laid out again.
let (text, layout, moved) = show(&mut c, vec![visibility(14, "visible")]);
assert_eq!(text.visible_text(), "fade in ");
assert!(Arc::ptr_eq(&layout.0, &first.0), "the layout drawn before");
assert_eq!(moved, content);
assert_eq!(engine_counts(&c), before);
// The next one starts in a color of its own, and is hidden again.
let fading = vec![
visibility(16, "visible"),
style_op(16, &[("color", StyleValue::Str("rgba(255, 0, 0, 0.5)"))]),
];
let (text, layout, _) = show(&mut c, fading);
assert_eq!(text.visible_text(), "fade in words");
assert!(Arc::ptr_eq(&layout.0, &first.0));
let (text, layout, _) = show(&mut c, vec![visibility(16, "hidden")]);
assert_eq!(text.visible_text(), "fade in ");
assert!(Arc::ptr_eq(&layout.0, &first.0));
assert_eq!(engine_counts(&c), before);
// New characters, or a new size, are typeset again.
c.apply(Op::SetText {
id: 17,
text: "word".into(),
})
.unwrap();
let (_, layout, _) = mounted_words(&c.commit().unwrap()).expect("the new text mounted");
assert!(!Arc::ptr_eq(&layout.0, &first.0));
let typeset = engine_counts(&c).0;
assert!(typeset > before.0);
apply(
&mut c,
vec![style_op(16, &[("fontSize", StyleValue::Number(20.0))])],
);
mounted_words(&c.commit().unwrap()).expect("the new text mounted");
assert!(engine_counts(&c).0 > typeset);
}
#[test]
fn hidden_words_are_typeset_again_where_colors_are_typeset() {
let mut c = three_words(
false,
vec![style_op(14, &[("visibility", StyleValue::Str("hidden"))])],
);
let (_, first, _) = mounted_words(&c.commit().unwrap()).expect("mounted");
let before = engine_counts(&c);
apply(
&mut c,
vec![style_op(14, &[("visibility", StyleValue::Str("visible"))])],
);
let (text, layout, _) = mounted_words(&c.commit().unwrap()).expect("the new text mounted");
assert!(!text.has_hidden());
assert!(!Arc::ptr_eq(&layout.0, &first.0));
assert!(engine_counts(&c).0 > before.0, "typeset again");
}
#[test]
fn spans_differing_only_in_colors_are_told_apart_from_other_changes() {
let style = ResolvedTextStyle::default();
let red = ResolvedTextStyle {
color: Color(0xff00_00ff),
..style
};
let text = |words: &[(&str, ResolvedTextStyle)]| {
let mut t = AttributedText::default();
for &(w, s) in words {
t.push(w, s);
}
t
};
let plain = text(&[("ab", style), ("cd", style)]);
let split = text(&[("ab", style), ("cd", red)]);
assert_eq!((plain.spans.len(), split.spans.len()), (1, 2));
assert!(plain.same_but_colors(&split) && split.same_but_colors(&plain));
let bold = ResolvedTextStyle {
font_weight: 700,
..red
};
assert!(!plain.same_but_colors(&text(&[("ab", style), ("cd", bold)])));
assert!(!plain.same_but_colors(&text(&[("ab", style), ("ce", red)])));
let underlined = ResolvedTextStyle {
decoration: crate::TextDecoration {
underline: true,
..Default::default()
},
..style
};
assert!(!plain.same_but_colors(&text(&[("abcd", underlined)])));
let lined = |color| ResolvedTextStyle {
decoration_color: color,
..underlined
};
let green = Some(Color(0x00ff_00ff));
assert!(text(&[("ab", lined(None))]).same_but_colors(&text(&[("ab", lined(green))])));
// Hidden characters keep their place: a run hidden or shown again is
// only drawn differently, as one recolored.
let hidden = text(&[("ab", style), ("cd", red.hide())]);
assert!(plain.same_but_colors(&hidden) && hidden.same_but_colors(&split));
assert!(!hidden.same_but_colors(&text(&[("ab", style), ("cd", bold.hide())])));
}
#[test]
fn recolored_ranges_are_the_characters_drawn_otherwise() {
let style = ResolvedTextStyle::default();
let red = ResolvedTextStyle {
color: Color(0xff00_00ff),
..style
};
let bold = ResolvedTextStyle {
font_weight: 700,
..style
};
let text = |words: &[(&str, ResolvedTextStyle)]| {
let mut t = AttributedText::default();
for &(w, s) in words {
t.push(w, s);
}
t
};
let words = |styles: [ResolvedTextStyle; 5]| {
text(&[
("one ", styles[0]),
("two ", styles[1]),
("three ", styles[2]),
("four ", styles[3]),
("five", styles[4]),
])
};
// The ranges, written as pairs.
let ranges = |pairs: &[(u32, u32)]| Some(pairs.iter().map(|&(a, b)| a..b).collect::<Vec<_>>());
let plain = words([style; 5]);
// Nothing drawn otherwise, however the spans split.
assert_eq!(plain.recolored_ranges(&plain), ranges(&[]));
let same = text(&[("one two ", style), ("three four five", style)]);
assert_eq!(plain.recolored_ranges(&same), ranges(&[]));
// A word shown: its characters; neighbors join into one range.
let fading = words([style, style, style, red.hide(), red.hide()]);
assert_eq!(fading.recolored_ranges(&plain), ranges(&[(14, 23)]));
let started = words([style, style, style, red, red.hide()]);
assert_eq!(fading.recolored_ranges(&started), ranges(&[(14, 19)]));
// Apart: two ranges, either way round.
let apart = words([red, style, style, red, style]);
assert_eq!(plain.recolored_ranges(&apart), ranges(&[(0, 4), (14, 19)]));
assert_eq!(apart.recolored_ranges(&plain), ranges(&[(0, 4), (14, 19)]));
// Spans that start and end elsewhere in the two texts.
let halves = text(&[("one two th", red), ("ree four five", style)]);
assert_eq!(plain.recolored_ranges(&halves), ranges(&[(0, 10)]));
// Anything else changed: not a recoloring.
assert_eq!(
plain.recolored_ranges(&words([style, bold, style, style, style])),
None
);
assert_eq!(plain.recolored_ranges(&text(&[("one", style)])), None);
}
#[test]
fn image_uses_natural_size_and_aspect_ratio() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Image,
},
Op::SetProp {
id: 2,
prop: Prop::Source(Some(ImageSource {
uri: "asset:/logo.png".into(),
size: Some(size_pt(200.0, 100.0)),
scales: ImageScales::NONE,
data: None,
})),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::Image,
},
style_op(
3,
&[
("width", StyleValue::Number(50.0)),
("alignSelf", StyleValue::Str("flex-start")),
],
),
Op::SetProp {
id: 3,
prop: Prop::Source(Some(ImageSource {
uri: "asset:/logo.png".into(),
size: Some(size_pt(200.0, 100.0)),
scales: ImageScales::NONE,
data: None,
})),
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Create {
id: 2,
kind: ViewKind::Image
}
)));
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Image {
id: 2,
source: Some(_),
..
}
)));
// Stretched to the column width, height from the aspect ratio.
assert_eq!(
frame_of(&batch, 2).map(|f| (f.size.width.0, f.size.height.0)),
Some((320.0, 160.0))
);
assert_eq!(
frame_of(&batch, 3).map(|f| (f.size.width.0, f.size.height.0)),
Some((50.0, 25.0))
);
}
mod rgba_image_sizes {
use super::*;
use crate::{
element::{ImageSrc, Root},
prelude::*,
};
#[component]
fn Images() -> impl IntoElement {
let src = ImageSrc::rgba(200, 100, vec![7u8; 200 * 100 * 4]);
let sized = src.clone().size(size_pt(100.0, 50.0));
view()
.items_start()
.child(image(src))
.child(image(sized.clone()))
.child(image(sized.clone()).w(px(60.0)))
.child(image(sized.clone()).h(px(20.0)))
.child(image(sized).w(px(60.0)).h(px(20.0)))
}
#[test]
fn declared_size_lays_out_in_points_at_each_pixel_ratio() {
for ratio in [1.0, 2.0] {
let mut c = core();
at_ratio(&mut c, ratio);
c.mount_root(&Root::new::<Images>(|| ()));
let batch = c.commit().unwrap();
let sizes: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Image {
id,
source: Some(source),
..
} => Some((source.size.unwrap(), frame_of(&batch, *id).unwrap().size)),
_ => None,
})
.collect();
let natural = size_pt(100.0, 50.0);
assert_eq!(
sizes,
[
(size_pt(200.0, 100.0), size_pt(200.0, 100.0)),
(natural, natural),
(natural, size_pt(60.0, 30.0)),
(natural, size_pt(40.0, 20.0)),
(natural, size_pt(60.0, 20.0)),
],
"at pixel ratio {ratio}"
);
}
}
#[component]
fn ResizableImage() -> impl IntoElement {
let natural = signal(size_pt(100.0, 50.0));
let src = ImageSrc::rgba(200, 100, vec![7u8; 200 * 100 * 4]);
view().items_start().child(
image(move || src.clone().size(natural.get()))
.on_press(move || natural.set(size_pt(80.0, 20.0))),
)
}
#[test]
fn changing_only_the_size_relayouts_the_same_source() {
let shown = |batch: &MountBatch| {
batch
.items
.iter()
.find_map(|item| match item {
MountItem::Image {
id,
source: Some(source),
..
} => Some((*id, source.clone())),
_ => None,
})
.unwrap()
};
let mut c = core();
at_ratio(&mut c, 2.0);
c.mount_root(&Root::new::<ResizableImage>(|| ()));
let first = c.commit().unwrap();
let (id, before) = shown(&first);
assert_eq!(frame_of(&first, id).unwrap().size, size_pt(100.0, 50.0));
assert!(c.component_event(id, EventKind::Press, &EventPayload::None));
let next = c.commit().unwrap();
let (next_id, after) = shown(&next);
assert_eq!(next_id, id);
assert_eq!(after.uri, before.uri);
assert_eq!(after.data, before.data);
assert_eq!(after.size, Some(size_pt(80.0, 20.0)));
assert_eq!(frame_of(&next, id).unwrap().size, size_pt(80.0, 20.0));
}
}
#[test]
fn object_position_reaches_the_image_item_only() {
let mut c = core();
let mut ops = image_ops(2, asset("asset:/a.png", &[]), None);
ops.push(style_op(2, &[("objectPosition", StyleValue::Str("top"))]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
let position = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Image { id: 2, options, .. } => Some(options.position),
_ => None,
})
};
let top = crate::style::ObjectPosition::parse("top").unwrap();
assert_eq!(position(&batch), Some(top));
// A change sends the image again, and no view style.
apply(
&mut c,
vec![style_op(
2,
&[("objectPosition", StyleValue::Str("right 10px bottom 0"))],
)],
);
let batch = c.commit().unwrap();
assert_eq!(
position(&batch),
crate::style::ObjectPosition::parse("right 10px bottom 0")
);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::ViewStyle { .. })),
"{:?}",
batch.items
);
// An invalid value is rejected, not misread.
let mut style = crate::Style::default();
assert!(
style
.set("objectPosition", StyleValue::Str("left 10px top"))
.is_err()
);
}
#[test]
fn object_fit_is_a_style_classes_and_styles_share() {
let mut c = core();
let mut ops = image_ops(2, asset("asset:/a.png", &[]), None);
ops.push(class_op(2, "object-contain"));
apply(&mut c, ops);
let fit = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Image {
id: 2, resize_mode, ..
} => Some(*resize_mode),
_ => None,
})
};
assert_eq!(fit(&c.commit().unwrap()), Some(ResizeMode::Contain));
// The style wins over the class, as in CSS; CSS's `fill` stretches.
apply(
&mut c,
vec![style_op(2, &[("objectFit", StyleValue::Str("fill"))])],
);
assert_eq!(fit(&c.commit().unwrap()), Some(ResizeMode::Stretch));
// Unset, the class's again; without it the image's default.
apply(&mut c, vec![style_op(2, &[])]);
assert_eq!(fit(&c.commit().unwrap()), Some(ResizeMode::Contain));
apply(&mut c, vec![class_op(2, "")]);
assert_eq!(fit(&c.commit().unwrap()), Some(ResizeMode::Cover));
let mut style = crate::Style::default();
assert!(style.set("objectFit", StyleValue::Str("stretch")).is_err());
}
#[test]
fn resize_modes_fit_at_their_position() {
use crate::{ResizeMode, geometry::size_pt, style::ObjectPosition};
let tall = size_pt(100.0, 300.0);
let square = size_pt(100.0, 100.0);
let at = |mode: ResizeMode, p: &str| {
let b = mode.fit(tall, square, ObjectPosition::parse(p).unwrap());
(b.origin.x.0, b.origin.y.0, b.size.width.0, b.size.height.0)
};
assert_eq!(at(ResizeMode::Cover, "center"), (0.0, -100.0, 100.0, 300.0));
assert_eq!(at(ResizeMode::Cover, "top"), (0.0, 0.0, 100.0, 300.0));
assert_eq!(at(ResizeMode::Cover, "bottom"), (0.0, -200.0, 100.0, 300.0));
let half = |p: &str| {
let b = ResizeMode::Contain.fit(
size_pt(50.0, 100.0),
square,
ObjectPosition::parse(p).unwrap(),
);
(b.origin.x.0, b.origin.y.0, b.size.width.0, b.size.height.0)
};
assert_eq!(half("left"), (0.0, 0.0, 50.0, 100.0));
assert_eq!(half("right"), (50.0, 0.0, 50.0, 100.0));
assert_eq!(half("25%"), (12.5, 0.0, 50.0, 100.0));
assert_eq!(
at(ResizeMode::Stretch, "left top"),
(0.0, 0.0, 100.0, 100.0)
);
// CSS's `object-fit: none` keeps the natural size, cropped where
// larger; `scale-down` shrinks what does not fit. Both keep the
// natural size of what fits, at the position.
assert_eq!(
at(ResizeMode::Center, "center"),
(0.0, -100.0, 100.0, 300.0)
);
assert_eq!(at(ResizeMode::Center, "top"), (0.0, 0.0, 100.0, 300.0));
let shrunk = ResizeMode::ScaleDown.fit(size_pt(200.0, 400.0), square, ObjectPosition::CENTER);
assert_eq!(
(
shrunk.origin.x.0,
shrunk.origin.y.0,
shrunk.size.width.0,
shrunk.size.height.0
),
(25.0, 0.0, 50.0, 100.0)
);
for mode in [ResizeMode::Center, ResizeMode::ScaleDown] {
let small = mode.fit(size_pt(20.0, 10.0), square, ObjectPosition::CENTER);
assert_eq!(
(small.origin.x.0, small.origin.y.0, small.size.width.0),
(40.0, 45.0, 20.0)
);
let corner = mode.fit(
size_pt(20.0, 10.0),
square,
ObjectPosition::parse("right bottom").unwrap(),
);
assert_eq!((corner.origin.x.0, corner.origin.y.0), (80.0, 90.0));
}
}
#[test]
fn native_components_get_their_name_props_and_size() {
let mut c = core();
let prop = |name: &str, value: Option<crate::JsonValue>| Op::SetProp {
id: 2,
prop: Prop::ComponentProp(name.into(), value),
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Native,
},
Op::SetProp {
id: 2,
prop: Prop::Component("com.example.map".into()),
},
prop("zoom", Some(serde_json::json!(3))),
prop("center", Some(serde_json::json!({ "lat": 1.5, "lng": 2 }))),
style_op(2, &[("alignSelf", StyleValue::Str("flex-start"))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let at = |pred: &dyn Fn(&MountItem) -> bool| batch.items.iter().position(pred);
let create = at(&|i| {
matches!(
i,
MountItem::Create {
id: 2,
kind: ViewKind::Native
}
)
})
.unwrap();
let component =
at(&|i| matches!(i, MountItem::Component { id: 2, name } if &**name == "com.example.map"))
.unwrap();
let props = batch
.items
.iter()
.position(|i| matches!(i, MountItem::ComponentProps { id: 2, .. }))
.unwrap();
assert!(create < component && component < props);
let MountItem::ComponentProps { props: all, .. } = &batch.items[props] else {
unreachable!()
};
assert_eq!(all.len(), 2);
assert!(all.contains(&(
"center".into(),
Some(serde_json::json!({ "lat": 1.5, "lng": 2 }))
)));
// No size of its own yet.
assert_eq!(
frame_of(&batch, 2).map(|f| (f.size.width.0, f.size.height.0)),
Some((0.0, 0.0))
);
// Only what changed; removals as `None`.
apply(
&mut c,
vec![
prop("zoom", Some(serde_json::json!(4))),
prop("center", None),
],
);
let batch = c.commit().unwrap();
let changed: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ComponentProps { id: 2, props } => Some(props.clone()),
_ => None,
})
.collect();
assert_eq!(
changed,
[vec![
("zoom".into(), Some(serde_json::json!(4))),
("center".into(), None)
]]
);
// The size it reports lays it out.
c.set_component_size(2, size_pt(120.0, 40.0));
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 2).map(|f| (f.size.width.0, f.size.height.0)),
Some((120.0, 40.0))
);
}
/// A GPU view named from JS gets its registered renderer's source with its
/// creation, and its props as a native component's.
#[test]
fn a_gpu_view_gets_its_registered_renderer_and_props() {
let mut c = core();
let source = crate::gpu::GpuSource::new(1_u8);
let mut registry = crate::element::Registry::new();
registry.gpu_renderer_source("test/scene", source.clone());
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::GpuView,
},
Op::SetProp {
id: 2,
prop: Prop::Component("test/scene".into()),
},
Op::SetProp {
id: 2,
prop: Prop::ComponentProp("exposure".into(), Some(serde_json::json!(1.5))),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let at = |pred: &dyn Fn(&MountItem) -> bool| batch.items.iter().position(pred);
let create = at(&|i| {
matches!(
i,
MountItem::Create {
id: 2,
kind: ViewKind::View
}
)
})
.unwrap();
let gpu = at(&|i| matches!(i, MountItem::GpuView { id: 2, source: Some(s) } if *s == source))
.expect("the renderer reaches the platform");
let props = at(&|i| matches!(i, MountItem::ComponentProps { id: 2, .. })).unwrap();
assert!(create < gpu && gpu < props);
// Not a native component: no component name is sent.
assert!(at(&|i| matches!(i, MountItem::Component { .. })).is_none());
// Another renderer: the view's props are sent again, for it.
let other = crate::gpu::GpuSource::new(2_u8);
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::GpuRenderer(Some(other.clone())),
}],
);
let batch = c.commit().unwrap();
let gpu = batch
.items
.iter()
.position(|i| matches!(i, MountItem::GpuView { id: 2, source: Some(s) } if *s == other))
.expect("the new renderer");
let props = batch
.items
.iter()
.position(|i| {
matches!(i, MountItem::ComponentProps { id: 2, props }
if props.iter().any(|(k, _)| &**k == "exposure"))
})
.expect("its props again");
assert!(gpu < props);
}
/// A GPU view naming no registered renderer is a plain view: nothing tells
/// the platform of a renderer.
#[test]
fn a_gpu_view_of_an_unknown_renderer_draws_nothing() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::GpuView,
},
Op::SetProp {
id: 2,
prop: Prop::Component("test/missing".into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::GpuView {
source: Some(_),
..
}
)));
}
#[test]
fn a_native_component_gets_its_accent_color_as_a_prop() {
// `accentColor` (or `accent-*`) on a native component reaches it as its
// `accentColor` prop, `#RRGGBBAA`; a style it no longer has removes it.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Native,
},
Op::SetProp {
id: 2,
prop: Prop::Component("com.example.switch".into()),
},
style_op(2, &[("accentColor", StyleValue::Str("#34c759"))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let accent = |c: &mut Core<FakeEngine>| {
let batch = c.commit().unwrap();
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ComponentProps { id: 2, props } => {
props.iter().find(|(k, _)| &**k == "accentColor").cloned()
}
_ => None,
})
.map(|(_, v)| v)
.collect::<Vec<_>>()
};
assert_eq!(accent(&mut c), [Some(serde_json::json!("#34C759FF"))]);
// The class, once the style no longer sets it.
c.apply(class_op(2, "accent-[#ff0000]")).unwrap();
c.apply(style_op(2, &[])).unwrap();
assert_eq!(accent(&mut c), [Some(serde_json::json!("#FF0000FF"))]);
// Unchanged: not sent again.
c.apply(style_op(2, &[("opacity", StyleValue::Number(0.5))]))
.unwrap();
assert_eq!(accent(&mut c), Vec::<Option<serde_json::Value>>::new());
c.apply(class_op(2, "")).unwrap();
assert_eq!(accent(&mut c), [None]);
}
#[test]
fn scroll_reports_content_size() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(200.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for i in 0..5u32 {
ops.push(Op::Create {
id: 10 + i,
tag: Tag::View,
});
ops.push(style_op(10 + i, &[("height", StyleValue::Number(100.0))]));
ops.push(Op::Insert {
parent: 2,
child: 10 + i,
before: None,
});
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let content = batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(*size),
_ => None,
});
assert_eq!(content, Some(size_pt(320.0, 500.0)));
// Children are not shrunk to the scroll view's height (the last one,
// beyond a viewport below it, is laid out but not mounted yet).
assert_eq!(
frame_of(&batch, 13).map(|f| (f.origin.y.0, f.size.height.0)),
Some((300.0, 100.0))
);
assert_eq!(frame_of(&batch, 14), None);
assert_eq!(
c.measure(14)
.map(|m| (m.frame.origin.y.0, m.frame.size.height.0)),
Some((400.0, 100.0))
);
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::ScrollConfig {
id: 2,
horizontal: false,
..
}
)));
}
/// A scroll view's content extent is its content's own, even below the
/// viewport (#2901): the frame floor made a short list under an iOS large
/// title scroll by the insets UIKit adds around the viewport.
#[test]
fn scroll_content_below_the_viewport_is_the_content() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(200.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let content = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(*size),
_ => None,
})
};
let batch = c.commit().unwrap();
// The row is the content, not the 200-point viewport it lies in.
assert_eq!(content(&batch), Some(size_pt(320.0, 100.0)));
// Growing past the viewport reports the grown content.
apply(
&mut c,
vec![style_op(3, &[("height", StyleValue::Number(500.0))])],
);
let batch = c.commit().unwrap();
assert_eq!(content(&batch), Some(size_pt(320.0, 500.0)));
}
/// A horizontal scroll view's main axis is its width: content narrower
/// than the viewport is its own extent there too, while the height it
/// spans stays the viewport's.
#[test]
fn horizontal_scroll_content_below_the_viewport_is_the_content() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(
2,
&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(100.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("width", StyleValue::Number(50.0))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
let content = batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(*size),
_ => None,
});
assert_eq!(content, Some(size_pt(50.0, 100.0)));
}
/// A scroll view 236 points long on its axis with 8 points of padding
/// around one child `child` long, and `extra` ops after.
fn padded_scroll(horizontal: bool, child: f32, extra: Vec<Op>) -> Core<FakeEngine> {
let (main, cross) = if horizontal {
("width", "height")
} else {
("height", "width")
};
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(
2,
&[
(main, StyleValue::Number(236.0)),
(cross, StyleValue::Number(100.0)),
("padding", StyleValue::Number(8.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::Horizontal(horizontal),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[
(main, StyleValue::Number(child)),
("flexShrink", StyleValue::Number(0.0)),
],
),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
];
ops.extend(extra);
apply(&mut c, ops);
c
}
fn scroll_content_size(batch: &MountBatch, id: NodeId) -> Option<Size<Points>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollContent { id: i, size } if *i == id => Some(*size),
_ => None,
})
}
/// A scroll view's content extent holds its padding once on each side:
/// content that fits with its padding is as long as the view, so it does
/// not scroll, and content past it scrolls to its end padding and no
/// further.
#[test]
fn scroll_content_holds_its_trailing_padding_once() {
let mut c = padded_scroll(false, 220.0, Vec::new());
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(100.0, 236.0)));
apply(
&mut c,
vec![style_op(3, &[("height", StyleValue::Number(500.0))])],
);
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(100.0, 516.0)));
}
/// So does a horizontal one's, along its width (its trailing padding the
/// right one).
#[test]
fn horizontal_scroll_content_holds_its_trailing_padding_once() {
let mut c = padded_scroll(true, 220.0, Vec::new());
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(236.0, 100.0)));
apply(
&mut c,
vec![style_op(3, &[("width", StyleValue::Number(500.0))])],
);
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(516.0, 100.0)));
}
/// Right to left, a horizontal scroll view's trailing padding is its left
/// one: each side's padding is still held once.
#[test]
fn right_to_left_scroll_content_holds_its_trailing_padding_once() {
// A style replaces the one before it: the view's size again, with
// uneven side padding.
let rtl = vec![style_op(
2,
&[
("width", StyleValue::Number(236.0)),
("height", StyleValue::Number(100.0)),
("direction", StyleValue::Str("rtl")),
("paddingVertical", StyleValue::Number(8.0)),
("paddingLeft", StyleValue::Number(12.0)),
("paddingRight", StyleValue::Number(4.0)),
],
)];
let mut c = padded_scroll(true, 220.0, rtl);
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(236.0, 100.0)));
apply(
&mut c,
vec![style_op(3, &[("width", StyleValue::Number(500.0))])],
);
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(516.0, 100.0)));
}
/// An absolutely positioned child reaches the extent with its own box,
/// without the end padding that follows the content in flow, as in CSS: a
/// child 50 points long 300 points into the padding box ends the content
/// at 350.
#[test]
fn scroll_content_ends_at_an_absolute_child_without_padding() {
let absolute = vec![
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("position", StyleValue::Str("absolute")),
("top", StyleValue::Number(300.0)),
("height", StyleValue::Number(50.0)),
("width", StyleValue::Number(50.0)),
],
),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
];
let mut c = padded_scroll(false, 20.0, absolute);
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(100.0, 350.0)));
}
/// A scroll view with nothing in it is its padding: an empty content box
/// between its leading and trailing padding, as a CSS scroll container's.
#[test]
fn an_empty_scroll_view_is_its_padding() {
let mut c = padded_scroll(
false,
20.0,
vec![Op::Remove {
parent: 2,
child: 3,
}],
);
let batch = c.commit().unwrap();
assert_eq!(scroll_content_size(&batch, 2), Some(size_pt(100.0, 16.0)));
}
/// `scrollsToTop` reaches the scroll view's mounted behavior (iOS sets
/// `UIScrollView.scrollsToTop` from it): on by default, off when the app
/// says so, and on again.
#[test]
fn scrolls_to_top_reaches_the_scroll_behavior() {
fn behavior(batch: &MountBatch) -> Option<ScrollBehavior> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollBehavior { id: 2, behavior } => Some((**behavior).clone()),
_ => None,
})
}
assert!(ScrollBehavior::default().scrolls_to_top);
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::ScrollsToTop(false)),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(behavior(&batch).map(|b| b.scrolls_to_top), Some(false));
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::ScrollsToTop(true)),
}],
);
let batch = c.commit().unwrap();
assert_eq!(behavior(&batch).map(|b| b.scrolls_to_top), Some(true));
}
/// `smoothWheel` and `wheelLineHeight` reach the scroll view's mounted
/// behavior (the desktops scroll mouse wheels from it): off and the
/// platform's line by default, set when the app says so (a negative height
/// as none), and back to the defaults once the app drops them (the reset
/// the runtime sets for a removed prop).
#[test]
fn smooth_wheel_and_wheel_line_height_reach_the_scroll_behavior() {
use crate::js::host::{HostCx, HostProps};
fn behavior(batch: &MountBatch) -> Option<ScrollBehavior> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollBehavior { id: 2, behavior } => Some((**behavior).clone()),
_ => None,
})
}
let b = ScrollBehavior::default();
assert!(!b.smooth_wheel);
assert_eq!(b.wheel_line_height, Points::ZERO);
// Props of every platform: their own names decode.
let mut cx = HostCx::for_element(Tag::Scroll);
let smooth = <Prop as HostProps>::decode("smoothWheel", &HostTestValue::Bool(true), &mut cx)
.expect("a scroll prop")
.expect("a value");
assert_eq!(smooth, Prop::Scroll(ScrollProp::SmoothWheel(true)));
let line =
<Prop as HostProps>::decode("wheelLineHeight", &HostTestValue::Number(40.0), &mut cx)
.expect("a scroll prop")
.expect("a value");
assert_eq!(
line,
Prop::Scroll(ScrollProp::WheelLineHeight(Points(40.0)))
);
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: smooth.clone(),
},
Op::SetProp {
id: 2,
prop: line.clone(),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let b = behavior(&c.commit().unwrap()).unwrap();
assert!(b.smooth_wheel);
assert_eq!(b.wheel_line_height, Points(40.0));
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::WheelLineHeight(Points(-5.0))),
}],
);
let b = behavior(&c.commit().unwrap()).unwrap();
assert_eq!(
b.wheel_line_height,
Points::ZERO,
"a negative height is none"
);
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: <Prop as HostProps>::reset(&smooth).unwrap(),
},
Op::SetProp {
id: 2,
prop: <Prop as HostProps>::reset(&line).unwrap(),
},
],
);
let b = behavior(&c.commit().unwrap()).unwrap();
assert!(!b.smooth_wheel);
assert_eq!(b.wheel_line_height, Points::ZERO);
}
/// `scrollbarInset` reaches the scroll view's mounted behavior (the platforms
/// keep their indicators within it), negative edges as none, and leaves the
/// content inset alone.
#[test]
fn scrollbar_inset_reaches_the_scroll_behavior() {
fn behavior(batch: &MountBatch) -> Option<ScrollBehavior> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollBehavior { id: 2, behavior } => Some((**behavior).clone()),
_ => None,
})
}
assert_eq!(
ScrollBehavior::default().scrollbar_inset,
EdgeInsets::default()
);
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::ScrollbarInset(EdgeInsets {
top: px(8.0),
bottom: px(72.0),
left: px(-4.0),
..EdgeInsets::default()
})),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let sent = behavior(&batch).expect("the behavior is mounted");
assert_eq!(
sent.scrollbar_inset,
EdgeInsets {
top: px(8.0),
bottom: px(72.0),
..EdgeInsets::default()
}
);
assert_eq!(sent.content_inset, EdgeInsets::default());
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::ScrollbarInset(EdgeInsets::default())),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
behavior(&batch).map(|b| b.scrollbar_inset),
Some(EdgeInsets::default())
);
}
/// `overflow: "hidden"` clips in layout as well as in paint: what a box
/// clips away must not grow an ancestor scroll view's content size. A
/// preview laid out at its design width and scaled down by a transform
/// (transforms do not affect layout) otherwise leaves a vertical scroll
/// view scrollable sideways.
#[test]
fn clipped_overflow_does_not_grow_scroll_content() {
/// The content width of a 320pt-wide vertical scroll view holding a
/// 300pt box, itself holding a 400pt-wide absolute child.
fn content_width(clips: bool) -> f32 {
let mut c = core();
let mut boxed = vec![
("width", StyleValue::Number(300.0)),
("height", StyleValue::Number(100.0)),
];
if clips {
boxed.push(("overflow", StyleValue::Str("hidden")));
}
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(200.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &boxed),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("position", StyleValue::Str("absolute")),
("left", StyleValue::Number(0.0)),
("top", StyleValue::Number(0.0)),
("width", StyleValue::Number(400.0)),
("height", StyleValue::Number(50.0)),
],
),
Op::Insert {
parent: 3,
child: 4,
before: None,
},
],
);
let batch = c.commit().unwrap();
batch
.items
.iter()
.find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(size.width.0),
_ => None,
})
.expect("scroll content size")
}
// Visible: the 400pt child reaches the scroll view, which scrolls to it.
assert_eq!(content_width(false), 400.0);
// Clipped: the scroll view keeps its own width, so it does not scroll
// sideways at all.
assert_eq!(content_width(true), 320.0);
}
/// An image smaller than its natural size is drawn inside its box, so it
/// adds nothing to the scrollable extent of a scroll view around it: a
/// 24 point icon in a 14 point box at the end of a fitting menu left the
/// menu 3 points to scroll.
#[test]
fn a_sized_image_does_not_overflow_its_scroll_view() {
let extent = |natural: Size<Points>, boxed: (f32, f32), fit: Option<&'static str>| {
let mut c = core();
let mut image = vec![
("width", StyleValue::Number(boxed.0)),
("height", StyleValue::Number(boxed.1)),
("alignSelf", StyleValue::Str("flex-start")),
];
if let Some(fit) = fit {
image.push(("objectFit", StyleValue::Str(fit)));
}
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(
2,
&[
("width", StyleValue::Number(boxed.0)),
("height", StyleValue::Number(boxed.1)),
("alignSelf", StyleValue::Str("flex-start")),
],
),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::Image,
},
style_op(3, &image),
Op::SetProp {
id: 3,
prop: Prop::Source(Some(ImageSource {
uri: "asset:/icon.svg".into(),
size: Some(natural),
scales: ImageScales::NONE,
data: None,
})),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
batch
.items
.iter()
.rev()
.find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some((size.width.0, size.height.0)),
_ => None,
})
.expect("the scroll view's content size")
};
assert_eq!(
extent(size_pt(24.0, 24.0), (14.0, 14.0), None),
(14.0, 14.0)
);
assert_eq!(
extent(size_pt(48.0, 24.0), (20.0, 10.0), None),
(20.0, 10.0)
);
// Cropped fits draw inside the box too.
for fit in ["cover", "none"] {
assert_eq!(
extent(size_pt(200.0, 100.0), (30.0, 40.0), Some(fit)),
(30.0, 40.0),
"{fit}"
);
}
// A box larger than the image is the extent itself.
assert_eq!(
extent(size_pt(24.0, 24.0), (60.0, 50.0), None),
(60.0, 50.0)
);
}
/// A scroll view's content size set twice in one batch (a row relaid in
/// two passes) reaches the platform once, with the last size: a transient
/// smaller size would clamp the offset before the content grows back.
#[test]
fn scroll_content_is_sent_once_per_batch() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(200.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let key = c.key(2).unwrap();
c.set_scroll_content(key, size_pt(320.0, 277.0));
c.set_scroll_content(key, size_pt(320.0, 909.0));
let sizes: Vec<_> = c
.mount
.iter()
.filter_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(size.height.0),
_ => None,
})
.collect();
assert_eq!(sizes, [909.0]);
// The next batch sends its own.
c.mount.clear();
c.batches += 1;
c.set_scroll_content(key, size_pt(320.0, 300.0));
assert!(matches!(
c.mount[..],
[MountItem::ScrollContent { id: 2, .. }]
));
}
/// Native scroll commands see the old extent before a shrink and the new
/// extent before growth. A change of cross size must not override that.
#[test]
fn scroll_content_preserves_the_extent_each_scroll_command_needs() {
for horizontal in [false, true] {
for absolute in [false, true] {
for (next_length, shrinking) in [(500.0, true), (900.0, false), (1200.0, false)] {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Horizontal(horizontal),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let key = c.key(2).unwrap();
let dimensions = |length, cross| {
if horizontal {
size_pt(length, cross)
} else {
size_pt(cross, length)
}
};
let old = dimensions(900.0, 320.0);
let new = dimensions(next_length, 200.0);
c.set_scroll_content(key, old);
c.mount.push(if absolute {
MountItem::Command {
id: 2,
command: Command::ScrollTo {
x: px(50.0),
y: px(50.0),
animated: false,
},
}
} else {
MountItem::ScrollBy {
id: 2,
dx: px(50.0),
dy: px(50.0),
}
});
c.set_scroll_content(key, new);
let sizes: Vec<_> = c
.mount
.iter()
.enumerate()
.filter_map(|(at, item)| match item {
MountItem::ScrollContent { id: 2, size } => Some((at, *size)),
_ => None,
})
.collect();
if shrinking {
assert_eq!(c.mount.len(), 3);
assert_eq!(sizes, [(0, old), (2, new)]);
} else {
assert_eq!(c.mount.len(), 2);
assert_eq!(sizes, [(0, new)]);
}
}
}
}
}
/// Plays JS: creates a cell per new slot, renders a fixed-height
/// row for each bind and confirms the index; the overscan too, as an
/// engine with time to spare does.
fn render_binds(
c: &mut Core<FakeEngine>,
next_id: &mut u32,
cells: &mut Vec<u32>,
row_height: f32,
) -> usize {
render_list_binds(c, next_id, cells, row_height, usize::MAX)
}
/// [`render_binds`] with at most `paced` of the overscan's waiting binds,
/// as an engine short of time.
fn render_list_binds(
c: &mut Core<FakeEngine>,
next_id: &mut u32,
cells: &mut Vec<u32>,
row_height: f32,
paced: usize,
) -> usize {
render_sized_binds(c, next_id, cells, &|_| row_height, paced)
}
/// [`render_list_binds`] with row `index` `row_height(index)` points
/// tall.
fn render_sized_binds(
c: &mut Core<FakeEngine>,
next_id: &mut u32,
cells: &mut Vec<u32>,
row_height: &dyn Fn(u32) -> f32,
paced: usize,
) -> usize {
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
c.take_paced_list_binds(paced, &mut binds);
let mut count = 0;
for bind in binds {
for (slot, index) in bind.binds {
count += 1;
while cells.len() <= slot as usize {
let id = *next_id;
*next_id += 1;
apply(
c,
vec![
Op::Create { id, tag: Tag::Cell },
Op::SetProp {
id,
prop: Prop::Slot(CellSlot::Item(cells.len() as u32)),
},
Op::Insert {
parent: bind.list,
child: id,
before: None,
},
],
);
cells.push(id);
}
// New content for the item, then the confirmation, as the
// runtime does.
let cell = cells[slot as usize];
c.apply(style_op(
cell,
&[("height", StyleValue::Number(row_height(index)))],
))
.unwrap();
c.apply(Op::SetProp {
id: cell,
prop: Prop::CellIndex(index),
})
.unwrap();
}
}
count
}
/// The node id of the cell list `id` has showing item `index`.
fn cell_showing(c: &Core<FakeEngine>, id: NodeId, index: u32) -> NodeId {
let list = c.nodes[c.key(id).unwrap() as usize].list.as_ref().unwrap();
let slot = list
.slots
.iter()
.find(|slot| slot.index == Some(index))
.expect("the item is bound");
assert_ne!(slot.cell, u32::MAX, "the cell is made");
c.nodes[slot.cell as usize].id
}
#[test]
fn list_renders_window_and_recycles_cells() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(1000),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
// Estimated 50 pt rows: the viewport, its screen of overscan and the
// one the start leaves empty above it = 25 rows.
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 100.0), 25);
let batch = c.commit().unwrap();
// Rows are really 100 pt: positioned by measured sizes.
assert_eq!(
frame_of(&batch, cells[3]),
Some(rect(0.0, 300.0, 320.0, 100.0))
);
let content = batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(size.height.0),
_ => None,
});
assert_eq!(content, Some(25.0 * 100.0 + 975.0 * 50.0));
// Scroll far down into unmeasured (50 pt estimated) rows: the window
// needs 25 rows; the 25 existing cells are reused, none are added.
c.set_scroll_offset(2, point(px(0.0), px(10_000.0)), u32::MAX);
c.commit();
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 25);
assert_eq!(cells.len(), 25);
c.commit();
// Scrolling on reuses cells only.
c.set_scroll_offset(2, point(px(0.0), px(20_000.0)), u32::MAX);
c.commit();
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 25);
assert_eq!(cells.len(), 25);
c.commit();
assert_eq!(c.node_count(), 2 + cells.len());
}
#[test]
fn list_content_aligns_cells_on_the_cross_axis() {
for horizontal in [false, true] {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(
2,
&[
(
"width",
StyleValue::Number(if horizontal { 120.0 } else { 200.0 }),
),
("height", StyleValue::Number(100.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::Horizontal(horizontal),
},
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(20.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(2),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 20.0), 2);
for (i, &cell) in cells.iter().enumerate() {
if horizontal {
c.apply(style_op(cell, &[("height", StyleValue::Null)]))
.unwrap();
}
let card = 200 + i as u32;
apply(
&mut c,
vec![
Op::Create {
id: card,
tag: Tag::View,
},
style_op(
card,
&[
("width", StyleValue::Number(40.0)),
("height", StyleValue::Number(20.0)),
],
),
Op::Insert {
parent: cell,
child: card,
before: None,
},
],
);
}
let batch = c.commit().unwrap();
let expected = if horizontal {
[rect(0.0, 0.0, 40.0, 100.0), rect(40.0, 0.0, 40.0, 100.0)]
} else {
[rect(0.0, 0.0, 200.0, 20.0), rect(0.0, 20.0, 200.0, 20.0)]
};
for (&cell, expected) in cells.iter().zip(expected) {
assert_eq!(frame_of(&batch, cell), Some(expected), "{horizontal}");
}
for (align, cell_at, cell_cross) in [
(
taffy::AlignItems::FLEX_START,
0.0,
if horizontal { 20.0 } else { 40.0 },
),
(
taffy::AlignItems::CENTER,
if horizontal { 40.0 } else { 80.0 },
if horizontal { 20.0 } else { 40.0 },
),
(
taffy::AlignItems::FLEX_END,
if horizontal { 80.0 } else { 160.0 },
if horizontal { 20.0 } else { 40.0 },
),
(
taffy::AlignItems::STRETCH,
0.0,
if horizontal { 100.0 } else { 200.0 },
),
] {
c.apply(Op::SetProp {
id: 2,
prop: Prop::ListContent(crate::ListContentStyle {
align_items: Some(align),
..Default::default()
}),
})
.unwrap();
c.commit();
let expected = if horizontal {
[
rect(0.0, cell_at, 40.0, cell_cross),
rect(40.0, cell_at, 40.0, cell_cross),
]
} else {
[
rect(cell_at, 0.0, cell_cross, 20.0),
rect(cell_at, 20.0, cell_cross, 20.0),
]
};
for (&cell, expected) in cells.iter().zip(expected) {
let frame = c.nodes[c.key(cell).unwrap() as usize].frame;
assert_eq!(frame, expected, "{horizontal}: {align:?}");
}
}
}
}
/// A list whose columns or content padding change with nothing else in
/// the turn (columns worked out from a width an `onLayout` measured) lays
/// its cells out again at the new column width, not only at the new
/// column positions.
#[test]
fn a_lists_cells_take_a_new_column_width_with_nothing_else_changed() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Columns(2),
},
Op::SetProp {
id: 2,
prop: Prop::Count(4),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 4);
// A card filling each cell.
for (i, &cell) in cells.iter().enumerate() {
let card = 200 + i as u32;
apply(
&mut c,
vec![
Op::Create {
id: card,
tag: Tag::View,
},
style_op(card, &[("height", StyleValue::Number(50.0))]),
Op::Insert {
parent: cell,
child: card,
before: None,
},
],
);
}
let batch = c.commit().unwrap();
for (i, &cell) in cells.iter().enumerate() {
let (x, y) = ((i % 2) as f32 * 160.0, (i / 2) as f32 * 50.0);
assert_eq!(frame_of(&batch, cell), Some(rect(x, y, 160.0, 50.0)));
assert_eq!(
frame_of(&batch, 200 + i as u32),
Some(rect(0.0, 0.0, 160.0, 50.0))
);
}
// Four columns, and nothing else.
c.apply(Op::SetProp {
id: 2,
prop: Prop::Columns(4),
})
.unwrap();
let batch = c.commit().unwrap();
for (i, &cell) in cells.iter().enumerate() {
assert_eq!(
frame_of(&batch, cell),
Some(rect(i as f32 * 80.0, 0.0, 80.0, 50.0)),
"cell {i}"
);
// The card laid out at the new column width, not the old one.
assert_eq!(
frame_of(&batch, 200 + i as u32),
Some(rect(0.0, 0.0, 80.0, 50.0)),
"card {i}"
);
}
// The same columns again change nothing.
c.apply(Op::SetProp {
id: 2,
prop: Prop::Columns(4),
})
.unwrap();
assert!(c.commit().is_none());
// Padding across the content, and nothing else: the columns narrow.
c.apply(Op::SetProp {
id: 2,
prop: Prop::ListContent(crate::ListContentStyle {
padding: crate::props::EdgeInsets {
left: px(20.0),
right: px(20.0),
..Default::default()
},
..Default::default()
}),
})
.unwrap();
let batch = c.commit().unwrap();
for i in 0..cells.len() {
assert_eq!(
frame_of(&batch, 200 + i as u32),
Some(rect(0.0, 0.0, 70.0, 50.0)),
"card {i}"
);
}
}
/// With tree order tracked (a platform's focus traversal), a list's
/// recycled cells come in the order they are on screen, not in the order
/// they were made, and their moves send the order again.
#[test]
fn tracked_tree_order_puts_a_lists_cells_in_screen_order() {
let mut c = core();
c.set_tree_order_tracking(true);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(1000),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let mut order = Vec::new();
let mut take = |batch: Option<MountBatch>| {
for item in batch.into_iter().flat_map(|b| b.items) {
if let MountItem::TreeOrder(nodes) = item {
order = nodes;
}
}
};
take(c.commit());
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
take(c.commit());
for y in [600.0, 300.0, 1500.0, 900.0, 2400.0, 1700.0] {
c.set_scroll_offset(2, point(px(0.0), px(y)), u32::MAX);
take(c.commit());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
take(c.commit());
}
let shown: Vec<u32> = order
.iter()
.copied()
.filter(|id| cells.contains(id))
.collect();
assert_eq!(shown.len(), cells.len());
let y = |id: &u32| c.nodes[c.key(*id).unwrap() as usize].frame.origin.y.0;
assert!(shown.windows(2).all(|w| y(&w[0]) <= y(&w[1])), "{shown:?}");
// The cells were recycled out of the order they were made in.
assert_ne!(shown, cells);
}
/// Plays a list's scroll view on the platform: applies the scrolls the
/// core sends it, clamped to its content, counting them as a platform
/// does.
#[derive(Default)]
struct ScrollingPlatform {
y: f32,
applied: u32,
content: f32,
}
impl ScrollingPlatform {
/// Applies what `batch` sends list `id` of `viewport` points;
/// whether it scrolled.
fn apply(&mut self, batch: &MountBatch, id: NodeId, viewport: f32) -> bool {
let mut scrolled = false;
for item in &batch.items {
match item {
MountItem::ScrollContent { id: i, size } if *i == id => {
self.content = size.height.0;
}
MountItem::ScrollBy { id: i, dy, .. } if *i == id => {
self.y += dy.0;
self.applied += 1;
scrolled = true;
}
MountItem::Command {
id: i,
command: Command::ScrollTo { y, .. },
} if *i == id => {
self.y = y.0;
self.applied += 1;
scrolled = true;
}
_ => {}
}
self.y = self.y.clamp(0.0, (self.content - viewport).max(0.0));
}
scrolled
}
/// Commits and renders the rows list 2 binds, row `index`
/// `row_height(index)` tall, reporting the scrolls it applies, until
/// nothing changes.
fn settle(
&mut self,
c: &mut Core<FakeEngine>,
next_id: &mut u32,
cells: &mut Vec<u32>,
row_height: &dyn Fn(u32) -> f32,
) {
for _ in 0..50 {
let batch = c.commit();
let scrolled = batch.as_ref().is_some_and(|b| self.apply(b, 2, 400.0));
if scrolled {
c.set_scroll_offset(2, point(px(0.0), px(self.y)), self.applied);
}
let bound = render_sized_binds(c, next_id, cells, row_height, usize::MAX);
if batch.is_none() && !scrolled && bound == 0 {
return;
}
}
panic!("the list never settled");
}
}
/// A `scrollToIndex` clamped to the list's start, in the commit where rows
/// above the viewport changed size: the platform applies the anchoring
/// `ScrollBy` (a mount item) before the `ScrollTo` (a command after them)
/// and may report in between. The core counts its scrolls in that order,
/// so the report does not make it think the list is still away from the
/// start, and it sends no `ScrollBy` that would push the view past it
/// (#3235).
#[test]
fn a_report_between_the_anchoring_scroll_and_a_clamped_scroll_to_index_keeps_the_start() {
let mut c = core();
thousand_rows(&mut c);
let (mut next_id, mut cells) = (100, Vec::new());
let mut platform = ScrollingPlatform::default();
let short = |_: u32| 50.0;
platform.settle(&mut c, &mut next_id, &mut cells, &short);
// Far down, then back up over rows not measured yet.
platform.y = 2000.0;
c.set_scroll_offset(2, point(px(0.0), px(platform.y)), platform.applied);
platform.settle(&mut c, &mut next_id, &mut cells, &short);
platform.y = 1200.0;
c.set_scroll_offset(2, point(px(0.0), px(platform.y)), platform.applied);
c.commit();
// Rows above the viewport turn out taller, and the app scrolls to a
// row whose bottom would sit above the start: clamped to 0.
render_sized_binds(&mut c, &mut next_id, &mut cells, &|_| 80.0, usize::MAX);
c.apply(Op::Command {
id: 2,
command: Command::ScrollToIndex {
index: 1,
animated: false,
view_position: crate::geometry::Percentage(1.0),
view_offset: px(-36.0),
},
})
.unwrap();
let batch = c.commit().unwrap();
let scrolls = page_scrolls(&batch);
let by = match scrolls.as_slice() {
[(false, by), (true, to)] => {
assert_eq!(*to, 0.0);
*by
}
other => panic!("an anchoring ScrollBy, then the ScrollTo: {other:?}"),
};
// The platform applied the `ScrollBy` and reports before the
// `ScrollTo`.
platform.y += by;
platform.applied += 1;
c.set_scroll_offset(2, point(px(0.0), px(platform.y)), platform.applied);
let list = c.nodes[c.key(2).unwrap() as usize].list.as_ref().unwrap();
assert_eq!(list.offset, 0.0, "the ScrollTo is still on its way");
// The next commit does not chase the start with a relative scroll.
let batch = c.commit();
let scrolls = batch.as_ref().map(page_scrolls).unwrap_or_default();
assert!(scrolls.is_empty(), "{scrolls:?}");
// The `ScrollTo` lands at the start.
platform.y = 0.0;
platform.applied += 1;
c.set_scroll_offset(2, point(px(0.0), px(platform.y)), platform.applied);
platform.settle(&mut c, &mut next_id, &mut cells, &|_| 80.0);
assert_eq!(platform.y, 0.0);
let list = c.nodes[c.key(2).unwrap() as usize].list.as_ref().unwrap();
assert_eq!(list.offset, 0.0);
}
/// What `ref.measureScrollPosition()` of node `id` answers.
fn scroll_position(c: &mut Core<FakeEngine>, id: NodeId) -> crate::JsonValue {
c.apply(Op::Command {
id,
command: Command::MeasureScrollPosition { call: 7 },
})
.unwrap();
c.commit();
js_events(c)
.into_iter()
.find_map(|(_, _, payload)| match payload {
EventPayload::Native { name, data } if &*name == "$return" && data["c"] == 7 => {
Some(data["v"].clone())
}
_ => None,
})
.expect("an answer")
}
/// The row list 2 lays out at content offset `y`, and how far into it
/// `y` is, from the frames of its cells.
fn row_laid_out_at(c: &Core<FakeEngine>, y: f32) -> (u32, f32) {
let list = c.nodes[c.key(2).unwrap() as usize].list.as_ref().unwrap();
list.slots
.iter()
.filter_map(|s| s.ready().map(|index| (index, s.cell)))
.find_map(|(index, cell)| {
let frame = c.nodes[cell as usize].frame;
let (top, height) = (frame.origin.y.0, frame.size.height.0);
(top <= y && y < top + height).then_some((index, y - top))
})
.expect("a row at the offset")
}
/// After a jump far into rows laid out by their estimate and corrected
/// as they are measured, and a scroll, the list says which row the
/// viewport starts in and how far into it, as its cells are laid out
/// (rows above measured and estimated alike); scrolling a list made anew
/// to that row, that far, puts the viewport's start back there.
#[test]
fn a_list_measures_where_its_viewport_starts_among_its_rows() {
let row_height = |index: u32| 30.0 + (index * 37 % 7) as f32 * 15.0;
let open = |c: &mut Core<FakeEngine>| {
thousand_rows(c);
let (mut next_id, mut cells) = (100, Vec::new());
let mut platform = ScrollingPlatform::default();
platform.settle(c, &mut next_id, &mut cells, &row_height);
(next_id, cells, platform)
};
let mut c = core();
let (mut next_id, mut cells, mut platform) = open(&mut c);
assert_eq!(
scroll_position(&mut c, 2),
serde_json::json!({ "index": 0, "offset": 0.0 })
);
assert_eq!(scroll_position(&mut c, ROOT_ID), serde_json::Value::Null);
c.apply(Op::Command {
id: 2,
command: Command::ScrollToIndex {
index: 400,
animated: false,
view_position: crate::geometry::Percentage(0.0),
view_offset: px(0.0),
},
})
.unwrap();
platform.settle(&mut c, &mut next_id, &mut cells, &row_height);
assert_eq!(row_laid_out_at(&c, platform.y), (400, 0.0));
// Measured rows replaced their estimates on the way.
assert_ne!(platform.y, 400.0 * 50.0);
platform.y += 70.0;
c.set_scroll_offset(2, point(px(0.0), px(platform.y)), platform.applied);
platform.settle(&mut c, &mut next_id, &mut cells, &row_height);
let (index, offset) = row_laid_out_at(&c, platform.y);
assert!(offset > 0.0, "{index} {offset}");
let at = scroll_position(&mut c, 2);
assert_eq!(at, serde_json::json!({ "index": index, "offset": offset }));
// A list made anew restores it with `scrollToIndex`.
let mut c = core();
let (mut next_id, mut cells, mut platform) = open(&mut c);
c.apply(Op::Command {
id: 2,
command: Command::ScrollToIndex {
index,
animated: false,
view_position: crate::geometry::Percentage(0.0),
view_offset: px(-offset),
},
})
.unwrap();
platform.settle(&mut c, &mut next_id, &mut cells, &row_height);
assert_eq!(row_laid_out_at(&c, platform.y), (index, offset));
assert_eq!(scroll_position(&mut c, 2), at);
}
#[test]
fn list_keeps_visible_content_anchored() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(100),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
// Jump into the middle before anything above was measured.
c.set_scroll_offset(2, point(px(0.0), px(2000.0)), u32::MAX);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
// Scroll back up so rows above the old position get rendered at 80 pt.
c.set_scroll_offset(2, point(px(0.0), px(1200.0)), u32::MAX);
c.commit();
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
let batch = c.commit().unwrap();
let shift: f32 = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ScrollBy { id: 2, dy, .. } => Some(dy.0),
_ => None,
})
.sum();
assert!(
shift > 0.0,
"rows above the viewport grew; content must be shifted down"
);
}
/// Whether `batch` last hid view `id` from sight (`visibility: hidden`)
/// and from screen readers, if it sent either.
fn hidden_in(batch: &MountBatch, id: NodeId) -> (Option<bool>, Option<bool>) {
let style = batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewStyle { id: i, style } if *i == id => Some(style.hidden),
_ => None,
});
let props = batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: i, props } if *i == id => Some(props.accessibility.hidden),
_ => None,
});
(style, props)
}
/// A list of 1000 rows estimated at 50 pt in a 400 pt viewport.
fn thousand_rows(c: &mut Core<FakeEngine>) {
apply(
c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(1000),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
}
#[test]
fn spare_list_cells_are_hidden_until_placed_again() {
let mut c = core();
thousand_rows(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 25);
let batch = c.commit().unwrap();
for &cell in &cells {
assert_eq!(
hidden_in(&batch, cell),
(None, None),
"cell {cell} shows its row"
);
}
// The data shrinks: the cells left without a row still show their
// last one, so they are hidden as well as moved out of sight.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Count(3),
}],
);
let batch = c.commit().unwrap();
for &cell in &cells[..3] {
assert_eq!(
hidden_in(&batch, cell),
(None, None),
"cell {cell} keeps its row"
);
}
for (row, &cell) in cells.iter().enumerate().skip(3) {
assert_eq!(
hidden_in(&batch, cell),
(Some(true), Some(true)),
"spare cell {cell}"
);
// Those in the render window (to 800 pt) move out of sight too.
let moved = (row < 16).then_some(-1.0e6);
assert_eq!(
frame_of(&batch, cell).map(|f| f.origin.y.0),
moved,
"spare cell {cell}"
);
}
// It grows again: the cells come back with their new rows.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Count(1000),
}],
);
c.commit();
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 22);
let batch = c.commit().unwrap();
let mut rows: Vec<f32> = cells[3..]
.iter()
.map(|&cell| {
assert_eq!(
hidden_in(&batch, cell),
(Some(false), Some(false)),
"cell {cell}"
);
frame_of(&batch, cell).expect("placed").origin.y.0
})
.collect();
rows.sort_by(f32::total_cmp);
assert_eq!(
rows,
(3..25).map(|row| 50.0 * row as f32).collect::<Vec<_>>()
);
// Far down, the rows are 30 pt: the window takes all 25 cells and
// more; back at the top, the ones it no longer needs stay where the
// window left them, showing their own rows there, out of sight. Screen
// readers skip the cells the window left behind (the rows there may
// have moved since they were laid out) until their new rows are bound:
// nothing else is mounted before.
c.set_scroll_offset(2, point(px(0.0), px(10_000.0)), u32::MAX);
c.commit();
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 30.0), 25);
c.commit();
while render_binds(&mut c, &mut next_id, &mut cells, 30.0) > 0 {
c.commit();
}
let made = cells.len();
assert!(made > 25, "{made}");
c.set_scroll_offset(2, point(px(0.0), px(0.0)), u32::MAX);
let left = c.commit().expect("the cells left behind");
for &cell in &cells {
assert_eq!(hidden_in(&left, cell), (None, Some(true)), "cell {cell}");
assert_eq!(frame_of(&left, cell), None, "cell {cell}");
}
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 25);
let placed = c.commit().unwrap();
let mut spare = Vec::new();
for &cell in &cells {
match frame_of(&placed, cell) {
Some(frame) => {
assert!(frame.origin.y.0 <= 1200.0, "cell {cell} at {frame:?}");
assert_eq!(hidden_in(&placed, cell), (None, Some(false)), "cell {cell}");
}
None => {
assert_eq!(hidden_in(&placed, cell), (None, None), "cell {cell}");
spare.push(cell);
}
}
}
assert_eq!(spare.len(), made - 25);
// Once the items change, the rows they show may be gone: hidden.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Count(999),
}],
);
let batch = c.commit().unwrap();
for &cell in &cells {
let hidden = if spare.contains(&cell) {
Some(true)
} else {
None
};
assert_eq!(hidden_in(&batch, cell), (hidden, hidden), "cell {cell}");
assert_eq!(frame_of(&batch, cell), None, "cell {cell}");
}
}
#[test]
fn scrolling_on_hides_no_cells() {
let mut c = core();
thousand_rows(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
// 70 pt rows estimated at 50: the cells made for the rows that do
// not fit after all are hidden.
let mut hidden = Vec::new();
for _ in 0..2 {
render_binds(&mut c, &mut next_id, &mut cells, 70.0);
let Some(batch) = c.commit() else { continue };
for &cell in &cells {
match hidden_in(&batch, cell).0 {
Some(true) => hidden.push(cell),
Some(false) => hidden.retain(|&h| h != cell),
None => {}
}
}
}
assert!(!hidden.is_empty());
// Then the window loses a row at one end before it gains one at the
// other (1200 pt is no multiple of 70), which takes the cell left
// behind: no cell is hidden, those hidden are shown once reused.
let mut at = 0.0;
while at < 3000.0 {
at += 10.0;
c.set_scroll_offset(2, point(px(0.0), px(at)), u32::MAX);
let mut batches: Vec<MountBatch> = c.commit().into_iter().collect();
render_binds(&mut c, &mut next_id, &mut cells, 70.0);
batches.extend(c.commit());
for batch in &batches {
for &cell in &cells {
match hidden_in(batch, cell).0 {
None => {}
Some(false) if hidden.contains(&cell) => hidden.retain(|&h| h != cell),
other => panic!("cell {cell} at {at}: {other:?}"),
}
}
}
}
assert!(hidden.is_empty(), "{hidden:?}");
}
#[test]
fn a_list_under_display_none_keeps_its_window_and_cells() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
thousand_rows(&mut c);
apply(
&mut c,
vec![Op::Insert {
parent: 3,
child: 2,
before: None,
}],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 25);
c.commit();
// A page kept alive under `display: none`: its list has no size, which
// is no viewport to empty its window by. Only the page's style goes.
apply(
&mut c,
vec![style_op(3, &[("display", StyleValue::Str("none"))])],
);
let hidden = c.commit().unwrap();
eprintln!("HIDE items {}", hidden.items.len());
for &cell in &cells {
assert_eq!(hidden_in(&hidden, cell), (None, None), "cell {cell}");
}
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 0);
// Shown again, its cells still show their rows where they were.
apply(
&mut c,
vec![style_op(3, &[("display", StyleValue::Str("flex"))])],
);
let shown = c.commit().unwrap();
eprintln!("SHOW items {}", shown.items.len());
let mut rows: Vec<f32> = cells
.iter()
.map(|&cell| {
assert_eq!(hidden_in(&shown, cell), (None, None), "cell {cell}");
frame_of(&shown, cell).expect("placed").origin.y.0
})
.collect();
rows.sort_by(f32::total_cmp);
assert_eq!(
rows,
(0..25).map(|row| 50.0 * row as f32).collect::<Vec<_>>()
);
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 0);
}
#[test]
fn list_cells_unbound_before_they_are_placed_are_hidden() {
let mut c = core();
thousand_rows(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 25);
// The data shrinks before the new cells were placed: those without a
// row show the content made for it, with no frame to move them away.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Count(3),
}],
);
let batch = c.commit().unwrap();
for (row, &cell) in cells.iter().enumerate() {
if row < 3 {
assert_eq!(hidden_in(&batch, cell), (None, None), "cell {cell}");
assert!(frame_of(&batch, cell).is_some());
} else {
assert_eq!(
hidden_in(&batch, cell),
(Some(true), Some(true)),
"cell {cell}"
);
assert_eq!(frame_of(&batch, cell), None, "cell {cell} was never placed");
}
}
}
#[test]
fn spare_list_cells_waiting_for_a_paced_bind_show_when_it_lands() {
let mut c = core();
thousand_rows(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 25);
c.commit();
// Shrunk to 3 rows, the other 22 cells are hidden; grown back, the
// viewport's rows bind at once and the overscan's wait.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Count(3),
}],
);
c.commit();
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Count(1000),
}],
);
c.commit();
assert_eq!(
render_list_binds(&mut c, &mut next_id, &mut cells, 50.0, 0),
5
);
assert!(c.has_paced_list_binds());
let batch = c.commit().unwrap();
let mut waiting = Vec::new();
for &cell in &cells[3..] {
match hidden_in(&batch, cell) {
(Some(false), Some(false)) => {
assert!(frame_of(&batch, cell).is_some(), "cell {cell}")
}
// Still hidden, out of sight, until its bind lands.
(None, None) => {
assert_eq!(frame_of(&batch, cell), None, "cell {cell}");
waiting.push(cell);
}
other => panic!("cell {cell}: {other:?}"),
}
}
assert_eq!(waiting.len(), 17);
// The paced binds land: those cells show, at their rows.
assert_eq!(render_binds(&mut c, &mut next_id, &mut cells, 50.0), 17);
assert!(!c.has_paced_list_binds());
let batch = c.commit().unwrap();
let mut rows: Vec<f32> = waiting
.iter()
.map(|&cell| {
assert_eq!(
hidden_in(&batch, cell),
(Some(false), Some(false)),
"cell {cell}"
);
frame_of(&batch, cell).expect("placed").origin.y.0
})
.collect();
rows.sort_by(f32::total_cmp);
assert_eq!(
rows,
(8..25).map(|row| 50.0 * row as f32).collect::<Vec<_>>()
);
}
/// A list of 100 rows estimated at 50 pt in a 400 pt viewport.
fn estimated_list(c: &mut Core<FakeEngine>) {
apply(
c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(100),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
}
/// Where list 2 is after `batch`: from `start`, its `ScrollTo` commands
/// and `ScrollBy` items in order.
fn scrolled(batch: &MountBatch, start: f32) -> f32 {
batch.items.iter().fold(start, |at, item| match item {
MountItem::Command {
id: 2,
command: Command::ScrollTo { y, .. },
} => y.0,
MountItem::ScrollBy { id: 2, dy, .. } => at + dy.0,
_ => at,
})
}
#[test]
fn bottom_aligned_list_does_not_mount_scrolls_during_native_bounce() {
let mut c = core();
estimated_list(&mut c);
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::ListAlignment(crate::ListAlignment::Bottom),
},
Op::SetProp {
id: 2,
prop: Prop::FollowEnd(Some(px(80.0)), false),
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
for _ in 0..3 {
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
}
for offset in [4610.0, 4630.0, 4660.0, 4630.0, 4610.0, 4600.0] {
c.set_scroll_offset(2, point(px(0.0), px(offset)), u32::MAX);
if let Some(batch) = c.commit() {
assert_eq!(scrolled(&batch, offset), offset, "native offset {offset}");
}
}
}
/// An empty list following its end gets its rows in the commit that also
/// grows its viewport (a chat's history arriving as a placeholder beside
/// it goes away): the platform must learn the grown content before the
/// scroll to the new end, or the frame's growth clamps that scroll to the
/// old, empty content and the list shows its first rows.
#[test]
fn rows_arriving_as_the_viewport_grows_keep_the_list_at_its_end() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(200.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::FollowEnd(Some(px(48.0)), false),
},
Op::SetProp {
id: 2,
prop: Prop::Count(0),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
apply(
&mut c,
vec![
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::Count(100),
},
],
);
let batch = c.commit().expect("a batch");
let at = |wanted: &dyn Fn(&MountItem) -> bool| batch.items.iter().position(wanted);
let scroll =
at(&|i| matches!(i, MountItem::ScrollBy { id: 2, .. })).expect("the list follows its end");
let content =
at(&|i| matches!(i, MountItem::ScrollContent { id: 2, size } if size.height.0 > 400.0))
.expect("the grown content");
let frame = at(&|i| matches!(i, MountItem::Frame { id: 2, .. })).expect("the grown frame");
assert!(
content < scroll && scroll < frame,
"content {content}, scroll {scroll}, frame {frame}: the content grows first, \
the scroll lands before the viewport grows"
);
}
/// List 2 (follow_end 80 pt) at its end, then its last row grows by
/// 300 pt, under its own layout animation when `revealing`: where the list
/// is after that commit, and the end it could follow to.
fn last_row_grows_at_end(revealing: bool) -> (f32, f32) {
let mut c = core();
estimated_list(&mut c);
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::FollowEnd(Some(px(80.0)), false),
}],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
let mut at = scrolled(&c.commit().unwrap(), 0.0);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
c.set_scroll_offset(2, point(px(0.0), px(at)), u32::MAX);
c.commit();
assert_eq!(at, 100.0 * 50.0 - 400.0, "at the end");
// The cell placed last shows the last row.
let last = *cells
.iter()
.max_by(|&&a, &&b| {
let y = |id| c.nodes[c.key(id).unwrap() as usize].frame.origin.y.0;
y(a).total_cmp(&y(b))
})
.unwrap();
let mut ops = vec![style_op(last, &[("height", StyleValue::Number(350.0))])];
if revealing {
ops.push(Op::Command {
id: last,
command: Command::LayoutAnimation(crate::LayoutAnimation {
update: Some(crate::LayoutTransition::new(
crate::LayoutCurve::FittedSpring { damping_ratio: 1.0 },
265.0,
)),
..Default::default()
}),
});
}
apply(&mut c, ops);
let after = c.commit().map_or(at, |b| scrolled(&b, at));
(after, 100.0 * 50.0 + 300.0 - 400.0)
}
#[test]
fn follow_end_keeps_its_place_while_the_last_row_reveals() {
// #2218: a scroll to the new end lands at once while the row slides
// open, so the content above jumps by the row's growth.
let (after, _) = last_row_grows_at_end(true);
assert_eq!(after, 100.0 * 50.0 - 400.0);
// Without its own animation, the row grows and the list follows.
let (after, end) = last_row_grows_at_end(false);
assert_eq!(after, end);
}
/// List 2 (follow_end 80 pt, `animated` as given) at its end with 100
/// rows of 50 pt; returns the core and the cell showing the last row.
fn list_following_its_end(animated: bool) -> (Core<FakeEngine>, u32) {
let mut c = core();
estimated_list(&mut c);
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::FollowEnd(Some(px(80.0)), animated),
}],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
let mut at = scrolled(&c.commit().unwrap(), 0.0);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
c.set_scroll_offset(2, point(px(0.0), px(at)), u32::MAX);
c.commit();
assert_eq!(at, 100.0 * 50.0 - 400.0, "at the end");
let last = *cells
.iter()
.max_by(|&&a, &&b| {
let y = |id| c.nodes[c.key(id).unwrap() as usize].frame.origin.y.0;
y(a).total_cmp(&y(b))
})
.unwrap();
(c, last)
}
/// List 2's scrolls in the commit after the last row (`cell`) becomes
/// `height` tall: its `ScrollTo` commands (offset, animated) and its
/// `ScrollBy` items.
fn last_row_resized(
c: &mut Core<FakeEngine>,
cell: u32,
height: f32,
) -> (Vec<(f32, bool)>, Vec<f32>) {
apply(
c,
vec![style_op(cell, &[("height", StyleValue::Number(height))])],
);
let (mut to, mut by) = (Vec::new(), Vec::new());
for item in c.commit().map(|b| b.items).unwrap_or_default() {
match item {
MountItem::Command {
id: 2,
command: Command::ScrollTo { y, animated, .. },
} => to.push((y.0, animated)),
MountItem::ScrollBy { id: 2, dy, .. } => by.push(dy.0),
_ => {}
}
}
(to, by)
}
#[test]
fn follow_end_animated_animates_a_large_step_of_the_end() {
// A chart appears in the last row: 300 pt at once.
let (mut c, last) = list_following_its_end(true);
let end = 100.0 * 50.0 + 300.0 - 400.0;
assert_eq!(
last_row_resized(&mut c, last, 350.0),
(vec![(end, true)], vec![]),
"an animated scroll to the new end, no jump"
);
// Without `animated`, the list jumps there as before.
let (mut c, last) = list_following_its_end(false);
assert_eq!(last_row_resized(&mut c, last, 350.0), (vec![], vec![300.0]));
}
#[test]
fn follow_end_animated_follows_small_steps_at_once() {
// A line of text streaming in: an animation restarted on every
// commit would lag behind it.
let (mut c, last) = list_following_its_end(true);
assert_eq!(last_row_resized(&mut c, last, 70.0), (vec![], vec![20.0]));
}
#[test]
fn follow_end_animated_retargets_while_the_content_grows() {
let (mut c, last) = list_following_its_end(true);
let end = 100.0 * 50.0 - 400.0;
assert_eq!(
last_row_resized(&mut c, last, 350.0),
(vec![(end + 300.0, true)], vec![])
);
// Halfway there, the reported offset is not the user leaving the end.
c.set_scroll_offset(2, point(px(0.0), px(end + 150.0)), u32::MAX);
let batch = c.commit();
assert_eq!(
batch.map_or(end + 150.0, |b| scrolled(&b, end + 150.0)),
end + 150.0
);
// The row grows on: the animation's target moves to the new end.
assert_eq!(
last_row_resized(&mut c, last, 450.0),
(vec![(end + 400.0, true)], vec![])
);
// Landed, the list follows small steps at once again.
c.set_scroll_offset(2, point(px(0.0), px(end + 400.0)), u32::MAX);
c.commit();
assert_eq!(last_row_resized(&mut c, last, 470.0), (vec![], vec![20.0]));
}
#[test]
fn follow_end_animated_stops_when_the_user_scrolls_away() {
let (mut c, last) = list_following_its_end(true);
let end = 100.0 * 50.0 - 400.0;
assert_eq!(
last_row_resized(&mut c, last, 350.0),
(vec![(end + 300.0, true)], vec![])
);
c.set_scroll_offset(2, point(px(0.0), px(end + 150.0)), u32::MAX);
c.commit();
// A drag back up, away from where the animation goes.
c.set_scroll_offset(2, point(px(0.0), px(end - 200.0)), u32::MAX);
c.commit();
assert_eq!(last_row_resized(&mut c, last, 450.0), (vec![], vec![]));
}
/// A resize that moves the end of a list following it moves the rows on
/// screen with the same commit. Measurement and anchored overlays read the
/// coordinates of that commit, not the offset the platform had before the
/// anchoring scroll it applies with the batch.
#[test]
fn measuring_a_list_row_follows_its_resize_anchor() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("flexGrow", StyleValue::Number(1.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::FollowEnd(Some(px(80.0)), false),
},
Op::SetProp {
id: 2,
prop: Prop::Count(100),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
let mut at = scrolled(&c.commit().unwrap(), 0.0);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
c.set_scroll_offset(2, point(px(0.0), px(at)), u32::MAX);
c.commit();
assert_eq!(at, 100.0 * 50.0 - 480.0, "at the end");
let last = *cells
.iter()
.max_by(|&&a, &&b| {
let y = |id| c.nodes[c.key(id).unwrap() as usize].frame.origin.y.0;
y(a).total_cmp(&y(b))
})
.unwrap();
let before = c.measure(last).unwrap().page.y.0;
// An overlay anchored to the row reads the same coordinates.
add(&mut c, 900, Tag::Overlay, last, &[]);
add(
&mut c,
901,
Tag::View,
900,
&[
("width", StyleValue::Number(120.0)),
("height", StyleValue::Number(60.0)),
],
);
apply(
&mut c,
vec![
overlay_prop(
900,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(last)),
),
overlay_prop(
900,
crate::OverlayProp::Placement(crate::overlay::Placement::Top),
),
overlay_prop(900, crate::OverlayProp::Offset(px(4.0))),
],
);
let batch = c.commit().expect("the overlay");
let overlay_before = frame_of(&batch, 900).unwrap().origin.y.0;
assert_eq!(overlay_before, before - 60.0 - 4.0);
c.apply(Op::Command {
id: last,
command: Command::Measure { call: 7 },
})
.unwrap();
c.set_viewport(size_pt(320.0, 300.0));
let batch = c.commit().expect("the resize");
let scroll_by: f32 = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::ScrollBy { id: 2, dy, .. } => Some(dy.0),
_ => None,
})
.sum();
assert_eq!(scroll_by, 180.0, "the shorter viewport moves the end");
let frame_y = c.nodes[c.key(last).unwrap() as usize].frame.origin.y.0;
// The batch grows the scroll offset by 180 before the platform reports
// it: the row is 180 points higher in the coordinates the commit mounts.
assert_eq!(
c.measure(last).unwrap().page.y.0,
frame_y - (at + scroll_by)
);
assert_eq!(c.measure(last).unwrap().page.y.0, before - scroll_by);
let answered = js_events(&mut c)
.into_iter()
.find_map(|(_, _, payload)| match payload {
EventPayload::Native { name, data } if &*name == "$return" && data["c"] == 7 => {
Some(data["v"].clone())
}
_ => None,
})
.expect("the measure answer");
assert_eq!(
answered["pagePosition"]["y"],
serde_json::json!(before - scroll_by),
"ref.measure() answers with the batch's coordinates"
);
assert_eq!(
frame_of(&batch, 900).unwrap().origin.y.0,
overlay_before - scroll_by,
"the anchored overlay follows the row in the same batch"
);
// A report made before the batch reaches the core after it: the
// instant anchoring scroll it does not count still applies.
c.set_scroll_offset(2, point(px(0.0), px(at)), 0);
c.commit();
assert_eq!(c.measure(last).unwrap().page.y.0, before - scroll_by);
// Once the platform's report arrives the answer is unchanged.
c.set_scroll_offset(2, point(px(0.0), px(at + scroll_by)), u32::MAX);
assert_eq!(c.measure(last).unwrap().page.y.0, before - scroll_by);
}
/// An animated scroll's target is where the list's window goes, not
/// where the rows show. Measurement and anchored overlays follow the
/// offset the platform reports until the animation moves it.
#[test]
fn measuring_a_list_row_does_not_jump_to_an_animated_scrolls_target() {
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
let end = 100.0 * 50.0 - 400.0;
c.apply(Op::Command {
id: 2,
command: Command::ScrollTo {
x: Points::ZERO,
y: Points(end - 120.0),
animated: false,
},
})
.unwrap();
let mut at = scrolled(&c.commit().unwrap(), 0.0);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
c.set_scroll_offset(2, point(px(0.0), px(at)), u32::MAX);
c.commit();
assert_eq!(at, end - 120.0, "near the end");
let row = cell_showing(&c, 2, 95);
let before = c.measure(row).unwrap().page.y.0;
assert_eq!(before, 95.0 * 50.0 - at);
add(&mut c, 900, Tag::Overlay, row, &[]);
add(
&mut c,
901,
Tag::View,
900,
&[
("width", StyleValue::Number(120.0)),
("height", StyleValue::Number(60.0)),
],
);
apply(
&mut c,
vec![
overlay_prop(
900,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(row)),
),
overlay_prop(
900,
crate::OverlayProp::Placement(crate::overlay::Placement::Top),
),
overlay_prop(900, crate::OverlayProp::Offset(px(4.0))),
],
);
let batch = c.commit().expect("the overlay");
let overlay_before = frame_of(&batch, 900).unwrap().origin.y.0;
assert_eq!(overlay_before, before - 60.0 - 4.0);
// 120 pt on to the end, animated. Until the platform reports the
// animation moving, the row and the overlay are where they were.
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: true },
})
.unwrap();
let batch = c.commit().expect("the scroll");
assert!(batch.items.iter().any(|item| matches!(
item,
MountItem::Command {
id: 2,
command: Command::ScrollTo { animated: true, .. }
}
)));
assert_eq!(c.measure(row).unwrap().page.y.0, before);
// A report made before the command reaches the core after it. It does
// not count the animated scroll, whose target the list's window already
// goes to; what shows has not jumped there.
c.set_scroll_offset(2, point(px(0.0), px(at)), 0);
if let Some(batch) = c.commit() {
assert_eq!(frame_of(&batch, 900), None);
}
assert_eq!(c.measure(row).unwrap().page.y.0, before);
assert_eq!(
c.nodes[c.key(900).unwrap() as usize].frame.origin.y.0,
overlay_before
);
// The animation reports its progress: measurement follows that.
c.set_scroll_offset(2, point(px(0.0), px(at + 40.0)), u32::MAX);
let batch = c.commit().expect("the animation's progress");
assert_eq!(c.measure(row).unwrap().page.y.0, before - 40.0);
assert_eq!(
frame_of(&batch, 900).unwrap().origin.y.0,
overlay_before - 40.0
);
}
/// Hit testing uses the same committed scroll position as measurement:
/// an instant list scroll is inverted at once, including when a report
/// made before it arrives afterwards.
#[test]
fn hit_testing_a_list_row_follows_its_instant_scroll() {
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
let row = cell_showing(&c, 2, 2);
apply(
&mut c,
vec![Op::Listen {
id: row,
event: EventKind::Press,
enabled: true,
}],
);
c.apply(Op::Command {
id: 2,
command: Command::ScrollTo {
x: Points::ZERO,
y: px(100.0),
animated: false,
},
})
.unwrap();
c.commit();
assert_eq!(c.measure(row).unwrap().page.y.0, 0.0);
assert_eq!(
c.press_target(2, point(px(10.0), px(25.0))),
Some((row, point(px(10.0), px(25.0))))
);
c.set_scroll_offset(2, point(px(0.0), px(0.0)), 0);
c.commit();
assert_eq!(
c.press_target(2, point(px(10.0), px(25.0))),
Some((row, point(px(10.0), px(25.0))))
);
}
#[test]
fn scroll_commands_follow_their_target_as_rows_are_measured() {
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
// The rows are really 80 pt: the end of the estimated content is too
// early, and the list follows the end once the last rows measure.
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
let mut at = scrolled(&c.commit().unwrap(), 0.0);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
let key = c.key(2).unwrap();
let content = c.nodes[key as usize]
.scroll
.as_ref()
.unwrap()
.content
.unwrap();
assert_eq!(at, (content.height - Points(400.0)).0);
// Item 50 in the middle of the viewport.
c.apply(Op::Command {
id: 2,
command: Command::ScrollToIndex {
index: 50,
animated: false,
view_position: crate::geometry::Percentage(0.5),
view_offset: px(0.0),
},
})
.unwrap();
at = scrolled(&c.commit().unwrap(), at);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
let list = c.nodes[key as usize].list.as_ref().unwrap();
assert_eq!(list.item_at(50) + 40.0 - at, 200.0);
assert!(!list.pinned(), "settled");
// Scrolled by the user, the list stays where it is put.
c.set_scroll_offset(2, point(px(0.0), px(at - 600.0)), u32::MAX);
c.commit();
assert!(render_binds(&mut c, &mut next_id, &mut cells, 120.0) > 0);
let batch = c.commit().unwrap();
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Command { id: 2, .. })),
"no scroll command after the user scrolled"
);
}
#[test]
fn animated_scroll_commands_retarget_while_rows_are_measured() {
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
c.commit();
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: true },
})
.unwrap();
let first = scrolled(&c.commit().unwrap(), 0.0);
let mut target = first;
// The platform starts the animation; the window follows it to the
// end, whose rows are measured: the animation is retargeted.
c.set_scroll_offset(2, point(px(0.0), px(1000.0)), 1);
c.commit();
c.set_scroll_offset(2, point(px(0.0), px(first - 10.0)), 1);
c.commit();
let mut issued = 1;
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
if let Some(batch) = c.commit() {
for item in &batch.items {
if let MountItem::Command {
id: 2,
command: Command::ScrollTo { y, animated, .. },
} = item
{
assert!(animated);
target = y.0;
issued += 1;
}
}
}
}
assert!(issued > 1 && target > first, "retargeted");
let key = c.key(2).unwrap();
let content = c.nodes[key as usize]
.scroll
.as_ref()
.unwrap()
.content
.unwrap();
assert_eq!(target, (content.height - Points(400.0)).0);
}
/// The animated `ScrollTo`s for list 2 in `batch`.
fn scroll_tos(batch: &MountBatch) -> Vec<f32> {
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
id: 2,
command: Command::ScrollTo { y, animated, .. },
} => {
assert!(animated);
Some(y.0)
}
_ => None,
})
.collect()
}
#[test]
fn the_end_key_follows_a_lists_end_as_rows_are_measured() {
use crate::scroll::KeyMove;
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
c.commit();
// End: the platform animates to the end it knows, estimated rows
// included, and tells the core, which follows the real end.
c.key_scrolled(2, KeyMove::End);
let first = scroll_tos(&c.commit().unwrap());
assert_eq!(first.len(), 1, "one scroll to the end");
let mut target = first[0];
// The platform's own animation, before it applied the core's scroll.
c.set_scroll_offset(2, point(px(0.0), px(1000.0)), 0);
c.commit();
// Then the core's; the key repeats, which changes nothing.
c.set_scroll_offset(2, point(px(0.0), px(target - 10.0)), 1);
c.key_scrolled(2, KeyMove::End);
assert!(!c.commands.iter().any(|(to, _)| *to == 2), "no new scroll");
let mut issued = 1;
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
if let Some(batch) = c.commit() {
for y in scroll_tos(&batch) {
target = y;
issued += 1;
}
}
}
assert!(issued > 1 && target > first[0], "retargeted");
let key = c.key(2).unwrap();
let content = c.nodes[key as usize]
.scroll
.as_ref()
.unwrap()
.content
.unwrap();
assert_eq!(target, (content.height - Points(400.0)).0);
}
#[test]
fn other_scroll_keys_leave_the_end_the_end_key_followed() {
use crate::scroll::KeyMove;
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
c.commit();
c.key_scrolled(2, KeyMove::End);
let target = scroll_tos(&c.commit().unwrap())[0];
// On its way, Page Up: the platform turns back from where the
// animation is.
c.set_scroll_offset(2, point(px(0.0), px(target - 200.0)), 1);
c.key_scrolled(2, KeyMove::Pages(-1.0));
c.set_scroll_offset(2, point(px(0.0), px(target - 550.0)), 1);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
if let Some(batch) = c.commit() {
assert_eq!(scroll_tos(&batch), [0.0; 0], "no scroll back to the end");
}
}
// End and Home in one turn: Home wins.
c.key_scrolled(2, KeyMove::End);
c.key_scrolled(2, KeyMove::Start);
if let Some(batch) = c.commit() {
assert_eq!(scroll_tos(&batch), [0.0; 0]);
}
}
#[test]
fn a_wheel_during_the_end_keys_scroll_leaves_the_end() {
use crate::scroll::KeyMove;
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
c.commit();
c.key_scrolled(2, KeyMove::End);
let target = scroll_tos(&c.commit().unwrap())[0];
// The animation comes nearer, then the wheel turns it back up.
c.set_scroll_offset(2, point(px(0.0), px(target - 900.0)), 1);
c.commit();
c.set_scroll_offset(2, point(px(0.0), px(target - 600.0)), 1);
c.commit();
c.set_scroll_offset(2, point(px(0.0), px(target - 700.0)), 1);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
if let Some(batch) = c.commit() {
assert_eq!(scroll_tos(&batch), [0.0; 0], "no scroll back to the end");
}
}
}
#[test]
fn an_app_scroll_after_the_end_key_in_one_turn_wins() {
use crate::scroll::KeyMove;
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
c.commit();
c.key_scrolled(2, KeyMove::End);
c.apply(Op::Command {
id: 2,
command: Command::ScrollTo {
x: px(0.0),
y: px(0.0),
animated: true,
},
})
.unwrap();
let tos = scroll_tos(&c.commit().unwrap());
assert_eq!(
tos.last(),
Some(&0.0),
"the app's scroll comes last: {tos:?}"
);
let key = c.key(2).unwrap();
assert!(!c.nodes[key as usize].list.as_ref().unwrap().pinned());
}
#[test]
fn the_end_keys_take_their_place_among_the_apps_scroll_commands() {
use crate::scroll::KeyMove;
let to_top = || Op::Command {
id: 2,
command: Command::ScrollTo {
x: px(0.0),
y: px(0.0),
animated: true,
},
};
let mut c = core();
estimated_list(&mut c);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
c.commit();
// End, the app's scroll to the top, End again: the end.
c.key_scrolled(2, KeyMove::End);
c.apply(to_top()).unwrap();
c.key_scrolled(2, KeyMove::End);
let tos = scroll_tos(&c.commit().unwrap());
assert!(tos.len() == 3 && tos[2] > 0.0, "{tos:?}");
// End, the app's scroll to the top and then to the end, Home: Home
// takes back the key's End only (from the top, where Home took the
// list).
c.key_scrolled(2, KeyMove::Start);
c.set_scroll_offset(2, point(px(0.0), px(0.0)), u32::MAX);
c.commit();
c.key_scrolled(2, KeyMove::End);
c.apply(to_top()).unwrap();
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: true },
})
.unwrap();
c.key_scrolled(2, KeyMove::Start);
let tos = scroll_tos(&c.commit().unwrap());
assert!(tos.len() == 2 && tos[0] == 0.0 && tos[1] > 0.0, "{tos:?}");
}
#[test]
fn the_end_key_leaves_inverted_lists_to_the_platform() {
use crate::scroll::KeyMove;
let mut c = core();
estimated_list(&mut c);
c.apply(Op::SetProp {
id: 2,
prop: Prop::Inverted(true),
})
.unwrap();
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
c.commit();
c.key_scrolled(2, KeyMove::End);
if let Some(batch) = c.commit() {
assert_eq!(scroll_tos(&batch), [0.0; 0]);
}
}
#[test]
fn animated_background_colors_replace_gradients() {
let mut c = core();
let mut s = Style::default();
s.set_background_images(vec![crate::effects::Gradient {
kind: crate::effects::GradientKind::Linear {
angle: crate::geometry::deg(180.0),
},
stops: Vec::new(),
repeating: false,
}]);
s.animated.push((AnimationProp::BackgroundColor, 7));
apply(
&mut c,
vec![
Op::Animation(AnimationOp::CreateValue {
node: 7,
value: 1.0,
}),
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetStyle {
id: 2,
style: Box::new(s),
patch: StylePatch::default(),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(view_style_of(&batch, 2).is_none_or(|s| s.effects.is_none()));
}
#[test]
fn animation_ops_and_bindings_are_forwarded_in_order() {
let mut c = core();
let mut s = Style::default();
s.animated.push((AnimationProp::Opacity, 7));
apply(
&mut c,
vec![
Op::Animation(AnimationOp::CreateValue {
node: 7,
value: 1.0,
}),
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetStyle {
id: 2,
style: Box::new(s),
patch: StylePatch::default(),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let animation = batch.items.iter().position(|i| {
matches!(
i,
MountItem::Animation(AnimationOp::CreateValue { node: 7, .. })
)
});
let bind = batch
.items
.iter()
.position(|i| matches!(i, MountItem::AnimationBindings { id: 2, .. }));
assert!(
animation.unwrap() < bind.unwrap(),
"values exist before views bind them"
);
}
#[test]
fn leaf_styles_are_resolved() {
let mut c = core();
apply(
&mut c,
vec![
// Text with padding: the frame wraps the measured text.
Op::Create {
id: 2,
tag: Tag::Text,
},
style_op(2, &[("padding", StyleValue::Number(10.0))]),
Op::CreateText {
id: 3,
text: "abc".into(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
// Empty leaf view: min size and aspect ratio still apply.
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("width", StyleValue::Number(100.0)),
("aspectRatio", StyleValue::Number(2.0)),
("alignSelf", StyleValue::Str("flex-start")),
],
),
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(5, &[("minHeight", StyleValue::Number(80.0))]),
Op::Insert {
parent: ROOT_ID,
child: 5,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.height.0),
Some(16.0 + 20.0)
);
let content = batch.items.iter().find_map(|i| match i {
MountItem::Text { id: 2, content, .. } => Some(*content),
_ => None,
});
assert_eq!(content, Some(rect(10.0, 10.0, 300.0, 16.0)));
assert_eq!(
frame_of(&batch, 4).map(|f| (f.size.width.0, f.size.height.0)),
Some((100.0, 50.0))
);
assert_eq!(frame_of(&batch, 5).map(|f| f.size.height.0), Some(80.0));
}
/// `cargo test --release -p nsh-core bench_row_relayout -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_row_relayout() {
let mut c = core();
// A gallery-like row: [image] [title / author] in a list cell.
let row = |s: &[(&str, StyleValue<'_>)]| style(s);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetStyle {
id: 2,
style: row(&[
("flexDirection", StyleValue::Str("row")),
("alignItems", StyleValue::Str("center")),
("gap", StyleValue::Number(12.0)),
("padding", StyleValue::Number(8.0)),
]),
patch: StylePatch::default(),
},
Op::Create {
id: 3,
tag: Tag::Image,
},
Op::SetStyle {
id: 3,
style: row(&[
("width", StyleValue::Number(48.0)),
("height", StyleValue::Number(48.0)),
]),
patch: StylePatch::default(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetStyle {
id: 4,
style: row(&[("flex", StyleValue::Number(1.0))]),
patch: StylePatch::default(),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Create {
id: 5,
tag: Tag::Text,
},
Op::CreateText {
id: 6,
text: "Photo #1".into(),
},
Op::Insert {
parent: 5,
child: 6,
before: None,
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Create {
id: 7,
tag: Tag::Text,
},
Op::CreateText {
id: 8,
text: "by Ada".into(),
},
Op::Insert {
parent: 7,
child: 8,
before: None,
},
Op::Insert {
parent: 4,
child: 7,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let n = 2000;
let start = std::time::Instant::now();
for i in 0..n {
c.apply(Op::SetText {
id: 6,
text: format!("Photo #{i}"),
})
.unwrap();
c.apply(Op::SetText {
id: 8,
text: format!("by {}", ["Ada", "Ken"][i % 2]),
})
.unwrap();
c.commit();
}
eprintln!("row relayout: {:?} per commit", start.elapsed() / n as u32);
}
/// `cargo test --release -p nsh-core bench_cell_relayout -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_cell_relayout() {
let mut c = Core::new(crate::ApproxTextEngine, size_pt(390.0, 800.0));
let s = |p: &[(&str, StyleValue<'_>)]| style(p);
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::List,
},
Op::SetStyle {
id: 2,
style: s(&[("flex", StyleValue::Number(1.0))]),
patch: StylePatch::default(),
},
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(64.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(1000),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for op in std::mem::take(&mut ops) {
c.apply(op).unwrap();
}
c.commit();
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
// One cell with a gallery row.
for op in [
Op::Create {
id: 10,
tag: Tag::Cell,
},
Op::SetProp {
id: 10,
prop: Prop::Slot(CellSlot::Item(0)),
},
Op::Insert {
parent: 2,
child: 10,
before: None,
},
Op::Create {
id: 11,
tag: Tag::View,
},
Op::SetStyle {
id: 11,
style: s(&[
("flexDirection", StyleValue::Str("row")),
("alignItems", StyleValue::Str("center")),
("gap", StyleValue::Number(12.0)),
("paddingHorizontal", StyleValue::Number(16.0)),
("paddingVertical", StyleValue::Number(8.0)),
]),
patch: StylePatch::default(),
},
Op::Insert {
parent: 10,
child: 11,
before: None,
},
Op::Create {
id: 12,
tag: Tag::Image,
},
Op::SetStyle {
id: 12,
style: s(&[
("width", StyleValue::Number(48.0)),
("height", StyleValue::Number(48.0)),
]),
patch: StylePatch::default(),
},
Op::Insert {
parent: 11,
child: 12,
before: None,
},
Op::Create {
id: 13,
tag: Tag::View,
},
Op::SetStyle {
id: 13,
style: s(&[
("flex", StyleValue::Number(1.0)),
("gap", StyleValue::Number(2.0)),
]),
patch: StylePatch::default(),
},
Op::Insert {
parent: 11,
child: 13,
before: None,
},
Op::Create {
id: 14,
tag: Tag::Text,
},
Op::CreateText {
id: 15,
text: "Photo #1".into(),
},
Op::Insert {
parent: 14,
child: 15,
before: None,
},
Op::Insert {
parent: 13,
child: 14,
before: None,
},
Op::Create {
id: 16,
tag: Tag::Text,
},
Op::CreateText {
id: 17,
text: "by Ada".into(),
},
Op::Insert {
parent: 16,
child: 17,
before: None,
},
Op::Insert {
parent: 13,
child: 16,
before: None,
},
Op::SetProp {
id: 10,
prop: Prop::CellIndex(0),
},
] {
c.apply(op).unwrap();
}
c.commit();
for idle in [0u64, 10] {
let n = if idle == 0 { 2000 } else { 100 };
let mut total = std::time::Duration::ZERO;
for i in 0..n {
std::thread::sleep(std::time::Duration::from_millis(idle));
let start = std::time::Instant::now();
c.apply(Op::SetText {
id: 15,
text: format!("Photo #{i}"),
})
.unwrap();
c.apply(Op::SetText {
id: 17,
text: format!("by {}", ["Ada", "Ken"][i % 2]),
})
.unwrap();
c.commit();
total += start.elapsed();
}
eprintln!(
"cell relayout ({idle} ms idle between frames): {:?} per commit",
total / n as u32
);
}
}
fn input_core() -> Core<FakeEngine> {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::SetProp {
id: 2,
prop: Prop::Placeholder("Name".into()),
},
style_op(2, &[("padding", StyleValue::Number(6.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c
}
#[test]
fn an_input_takes_its_caret_and_selection_colors_apart() {
// `caretColor` (or `caret-*`) is the caret's, `selectionColor` the
// selection highlight's: neither stands in for the other.
let colors = |classes: &str, style: &[(&str, StyleValue<'_>)]| {
let mut c = input_core();
c.apply(class_op(2, classes)).unwrap();
c.apply(style_op(2, style)).unwrap();
let batch = c.commit().unwrap();
batch.items.iter().rev().find_map(|i| match i {
MountItem::Input { id: 2, config } => {
Some((config.caret_color, config.selection_color))
}
_ => None,
})
};
let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
assert_eq!(
colors(
"",
&[
("caretColor", StyleValue::Str("red")),
("selectionColor", StyleValue::Str("blue"))
]
),
Some((Some(red), Some(blue)))
);
assert_eq!(colors("caret-[#ff0000]", &[]), Some((Some(red), None)));
// The style wins over the class.
assert_eq!(
colors(
"caret-[#ff0000]",
&[("caretColor", StyleValue::Str("blue"))]
),
Some((Some(blue), None))
);
}
#[test]
fn input_measures_its_placeholder_and_reports_its_content_box() {
let mut c = input_core();
let batch = c.commit().unwrap();
// One line of text (16pt) plus padding, stretched across the root.
assert_eq!(frame_of(&batch, 2).map(|f| f.size.height.0), Some(28.0));
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::Input { id: 2, config } if config.placeholder == "Name" && !config.multiline)));
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::InputContent { id: 2, content } if *content == rect(6.0, 6.0, 308.0, 16.0))));
// No text yet: nothing to send.
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::InputValue { .. }))
);
}
#[test]
fn input_out_of_the_layout_has_no_content_box() {
// `display: none` around an input leaves it no box, and a platform that
// does not clip a view's children to it (a browser) would draw its
// field, placeholder and all, at the content box it had before.
let mut c = input_core();
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Insert {
parent: 3,
child: 2,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
let content_of = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::InputContent { id: 2, content } => Some(*content),
_ => None,
})
};
let shown = Some(rect(6.0, 6.0, 308.0, 16.0));
assert_eq!(content_of(&c.commit().unwrap()), shown);
let mut toggle = |id, classes, expected: Option<Bounds<Points>>| {
c.apply(class_op(id, classes)).unwrap();
assert_eq!(
content_of(&c.commit().unwrap()),
expected,
"{id}: {classes}"
);
};
// Hidden by its parent's class, then by its own.
toggle(3, "hidden", Some(Bounds::default()));
toggle(3, "flex flex-col", shown);
toggle(2, "hidden", Some(Bounds::default()));
toggle(2, "flex", shown);
}
#[test]
fn inputs_resolve_what_return_does() {
use crate::{SubmitBehavior as S, mount::InputConfig};
let config = |multiline, blur_on_submit, submit_behavior| InputConfig {
multiline,
blur_on_submit,
submit_behavior,
..InputConfig::default()
};
// React Native's defaults: one line submits and unfocuses, several
// lines take line breaks; `blur_on_submit` false keeps the focus.
assert_eq!(config(false, true, None).submit(), S::BlurAndSubmit);
assert_eq!(config(false, false, None).submit(), S::Submit);
assert_eq!(config(true, true, None).submit(), S::Newline);
// `submitBehavior` wins; one line never takes line breaks.
assert_eq!(config(true, true, Some(S::Submit)).submit(), S::Submit);
assert_eq!(
config(false, false, Some(S::BlurAndSubmit)).submit(),
S::BlurAndSubmit
);
assert_eq!(
config(false, true, Some(S::Newline)).submit(),
S::BlurAndSubmit
);
}
#[test]
fn inputs_take_their_submit_behavior() {
let mut c = input_core();
c.commit().unwrap();
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
},
Op::SetProp {
id: 2,
prop: Prop::SubmitBehavior(Some(crate::SubmitBehavior::Submit)),
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::Input { id: 2, config } if config.submit() == crate::SubmitBehavior::Submit)));
}
#[test]
fn input_values_from_js_and_native_edits() {
let mut c = input_core();
c.commit();
// The user types; JS echoes the same text: nothing goes back.
c.input_changed(2, "ab", 2);
c.apply(Op::SetProp {
id: 2,
prop: Prop::Value("ab".into()),
})
.unwrap();
assert!(c.commit().is_none());
// JS transforms the text: it is sent with the edit count it is based on.
c.apply(Op::SetProp {
id: 2,
prop: Prop::Value("AB".into()),
})
.unwrap();
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::InputValue { id: 2, text, count: 2 } if text == "AB")));
// `defaultValue` no longer applies once a value was set.
c.apply(Op::SetProp {
id: 2,
prop: Prop::DefaultValue("x".into()),
})
.unwrap();
assert!(c.commit().is_none());
}
/// An input with `style`, in a row with `flex: 1` when `flex`, or alone, in a
/// view its content sizes.
fn hugged_input(style: &[(&str, StyleValue<'_>)], flex: bool) -> Core<FakeEngine> {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 7,
tag: Tag::View,
},
style_op(7, &[("alignItems", StyleValue::Str("flex-start"))]),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("flexDirection", StyleValue::Str("row"))]),
Op::Create {
id: 2,
tag: Tag::Input,
},
style_op(2, style),
];
if flex {
ops.push(style_op(2, &[("flex", StyleValue::Number(1.0))]));
}
for (parent, child) in [(3, 2), (7, 3), (ROOT_ID, 7)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
apply(&mut c, ops);
c
}
#[test]
fn an_inputs_width_does_not_come_from_its_text() {
for flex in [false, true] {
let mut c = hugged_input(&[], flex);
// Twenty digits at 8pt, whatever it holds.
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).map(|f| f.size.width.0), Some(160.0));
c.input_changed(2, "x", 1);
// Typing does not move it, if its frame is sent at all.
let width = |batch: Option<MountBatch>| {
batch
.and_then(|b| frame_of(&b, 3))
.map_or(160.0, |f| f.size.width.0)
};
assert_eq!(width(c.commit()), 160.0);
c.input_changed(2, &"x".repeat(30), 2);
assert_eq!(width(c.commit()), 160.0);
}
// A multiline one wraps at that width: 30
// characters at 8pt in 160pt is two lines.
let mut c = hugged_input(&[], false);
c.apply(Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
})
.unwrap();
c.commit();
c.input_changed(2, &"x".repeat(30), 1);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 2).map(|f| (f.size.width.0, f.size.height.0)),
Some((160.0, 32.0))
);
// A width of its own stays.
let batch = hugged_input(&[("width", StyleValue::Number(90.0))], false)
.commit()
.unwrap();
assert_eq!(frame_of(&batch, 2).map(|f| f.size.width.0), Some(90.0));
}
#[test]
fn multiline_inputs_grow_with_their_text() {
let mut c = input_core();
c.apply(Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
})
.unwrap();
c.commit();
// 50 characters at 8pt in 308pt: two lines.
c.input_changed(2, &"x".repeat(50), 1);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).map(|f| f.size.height.0), Some(44.0));
// A trailing line break starts an empty line that still takes space.
c.input_changed(2, "x\n", 2);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).map(|f| f.size.height.0), Some(28.0));
}
#[test]
fn multiline_inputs_grow_with_what_an_input_method_composes() {
let mut c = input_core();
c.apply(Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
})
.unwrap();
c.commit();
// 30 characters at 8pt in 308pt: one line, as the placeholder.
c.input_changed(2, &"x".repeat(30), 1);
assert_eq!(c.commit().and_then(|b| frame_of(&b, 2)), None);
// Composing 20 more wraps the line: the input grows before it commits.
c.input_composing(2, Some(&"x".repeat(50)));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).map(|f| f.size.height.0), Some(44.0));
// Its value is still what was committed.
let node = &c.nodes[c.key(2).unwrap() as usize];
assert_eq!(node.input.as_ref().unwrap().value, "x".repeat(30));
// Cancelled, it goes back to its value's height.
c.input_composing(2, None);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).map(|f| f.size.height.0), Some(28.0));
// Committed, it keeps the height the composition gave it.
c.input_composing(2, Some(&"x".repeat(50)));
c.commit();
c.input_changed(2, &"x".repeat(50), 2);
c.input_composing(2, None);
let batch = c.commit();
assert_eq!(batch.and_then(|b| frame_of(&b, 2)), None);
}
#[test]
fn multiline_inputs_stop_at_their_max_height_and_so_do_their_parents() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("width", StyleValue::Number(200.0))]),
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Insert {
parent: 4,
child: 3,
before: None,
},
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
},
style_op(
2,
&[
("padding", StyleValue::Number(6.0)),
("maxHeight", StyleValue::Number(100.0)),
],
),
Op::Insert {
parent: 3,
child: 2,
before: None,
},
],
);
c.commit();
let height = |batch: &MountBatch, id| frame_of(batch, id).map(|f| f.size.height.0);
// Two lines: under the maximum, the parent around it as tall.
c.input_changed(2, &"x".repeat(30), 1);
let batch = c.commit().unwrap();
assert_eq!(
(height(&batch, 2), height(&batch, 3)),
(Some(44.0), Some(44.0))
);
// Far more than fits: the input stops at its maximum (its text scrolls
// in it), and so does the column around it, sized from its content.
c.input_changed(2, &"x".repeat(1000), 2);
let batch = c.commit().unwrap();
assert_eq!(
(height(&batch, 2), height(&batch, 3)),
(Some(100.0), Some(100.0))
);
let content = batch.items.iter().rev().find_map(|i| match i {
MountItem::InputContent { id: 2, content } => Some(content.size.height.0),
_ => None,
});
assert_eq!(content, Some(88.0));
}
/// An input scrolls its own text: text taller than a fixed height stays in
/// it and must not grow the content size of a scroll view around it, or
/// that scroll view scrolls on into a blank below its last child.
#[test]
fn a_fixed_height_inputs_text_does_not_grow_the_scroll_content_around_it() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::Scroll,
},
style_op(
4,
&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(150.0)),
],
),
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Insert {
parent: 4,
child: 3,
before: None,
},
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: 3,
child: 2,
before: None,
},
],
);
c.commit();
// Far more text than its 100pt show.
c.input_changed(2, &"x".repeat(1000), 1);
// Nothing of the layout may change at all: no batch is as good as one
// without these items.
let batch = c.commit();
let items = batch.as_ref().map_or(&[][..], |b| &b.items[..]);
// It keeps its height (its frame unchanged, if sent at all).
let frame = items.iter().rev().find_map(|i| match i {
MountItem::Frame { id: 2, frame } => Some(frame.size.height.0),
_ => None,
});
assert!(frame.is_none_or(|h| h == 100.0), "input height {frame:?}");
let content = items.iter().rev().find_map(|i| match i {
MountItem::ScrollContent { id: 4, size } => Some(size.height.0),
_ => None,
});
// The scroll view's content is its child's 100pt, or unchanged (not sent).
assert!(
content.is_none_or(|h| h == 150.0),
"scroll content height {content:?}"
);
}
/// The space around an input can be narrower than its own padding (a
/// column squeezed while it resizes): the input then has no room for its
/// text, not a negative one.
/// A negative content width made the overflow Taffy computes from it
/// negative, which its debug assertions reject.
#[test]
fn an_input_narrower_than_its_padding_measures_no_room_for_its_text() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[
("alignItems", StyleValue::Str("flex-start")),
("width", StyleValue::Number(10.0)),
],
),
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
Op::Create {
id: 2,
tag: Tag::Input,
},
style_op(2, &[("paddingHorizontal", StyleValue::Number(15.0))]),
Op::Insert {
parent: 3,
child: 2,
before: None,
},
],
);
let batch = c.commit().expect("the first layout");
let width = batch.items.iter().rev().find_map(|i| match i {
MountItem::Frame { id: 2, frame } => Some(frame.size.width.0),
_ => None,
});
// Its padding and no text: the column's 10 points cannot make it
// narrower than its padding.
assert_eq!(width, Some(30.0));
}
#[test]
fn multiline_inputs_measure_long_runs_in_pieces() {
let mut c = input_core();
c.apply(Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
})
.unwrap();
c.commit();
let key = c.key(2).unwrap();
let measured = |c: &Core<FakeEngine>, content: &str| c.input_text(key, content).text;
// A run without white space as long as minified JSON or Base64 is
// measured with a line break after every 1024 characters (platform
// line breakers take quadratic time on one long run)...
let run = "é".repeat(2500);
let pieces: Vec<String> = measured(&c, &run).split('\n').map(String::from).collect();
assert_eq!(
pieces,
["é".repeat(1024), "é".repeat(1024), "é".repeat(452)]
);
// ... counted from the last white space, never ending the text with one.
let words = format!("{} {}", "a".repeat(1500), "b".repeat(1024));
assert_eq!(
measured(&c, &words),
format!(
"{}\n{} {}",
"a".repeat(1024),
"a".repeat(476),
"b".repeat(1024)
)
);
// Existing breaks are not duplicated, and non-breaking spaces do not
// let a long unbreakable run evade the limit.
let ending = format!("{}\n", "a".repeat(1024));
assert_eq!(measured(&c, &ending), format!("{ending}\u{200b}"));
let nbsp = "a\u{a0}".repeat(1200);
assert!(measured(&c,  ).contains('\n'));
let cjk = "漢".repeat(2500);
assert_eq!(measured(&c, &cjk), cjk);
// Text without such runs, and a single line, measure as they are.
let prose = "lorem ipsum ".repeat(500);
assert_eq!(measured(&c, &prose), prose);
c.apply(Op::SetProp {
id: 2,
prop: Prop::Multiline(false),
})
.unwrap();
assert_eq!(measured(&c, &run), run);
// The input itself keeps its value.
c.apply(Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
})
.unwrap();
c.input_changed(2, &run, 1);
c.commit();
assert_eq!(
c.nodes[key as usize]
.input
.as_ref()
.map(|i| i.value.as_str()),
Some(run.as_str())
);
}
#[test]
fn commands_reach_created_views_only() {
let mut c = input_core();
c.apply(Op::Command {
id: 2,
command: crate::Command::Focus,
})
.unwrap();
let batch = c.commit().unwrap();
assert!(matches!(
batch.items.last(),
Some(MountItem::Command {
id: 2,
command: crate::Command::Focus
})
));
c.apply(Op::Create {
id: 3,
tag: Tag::Input,
})
.unwrap();
c.apply(Op::Command {
id: 3,
command: crate::Command::Focus,
})
.unwrap();
assert!(c.commit().is_none());
}
fn insert_items(batch: &MountBatch) -> Vec<(NodeId, NodeId, Option<NodeId>)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert {
parent,
child,
before,
} => Some((*parent, *child, *before)),
_ => None,
})
.collect()
}
#[test]
fn z_index_orders_native_views() {
let mut c = core();
let z = |v: f32| style(&[("zIndex", StyleValue::Number(v))]);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetStyle {
id: 2,
style: z(5.0),
patch: StylePatch::default(),
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
Op::Insert {
parent: 1,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
// 3 (z 0) goes below 2 (z 5) although it comes later in the tree.
assert_eq!(insert_items(&batch), vec![(1, 2, None), (1, 3, Some(2))]);
// Raising 3 above 2 moves it to the top.
apply(
&mut c,
vec![Op::SetStyle {
id: 3,
style: z(9.0),
patch: StylePatch::default(),
}],
);
let batch = c.commit().unwrap();
assert_eq!(insert_items(&batch), vec![(1, 3, None)]);
// A new child with the default z index goes below both.
apply(
&mut c,
vec![Op::Insert {
parent: 1,
child: 4,
before: None,
}],
);
let batch = c.commit().unwrap();
assert_eq!(insert_items(&batch), vec![(1, 4, Some(2))]);
}
#[test]
fn tracked_tree_order_follows_logical_moves_without_following_stacking() {
let mut c = core();
c.set_tree_order_tracking(true);
let order = |batch: &MountBatch| {
batch.items.iter().find_map(|item| match item {
MountItem::TreeOrder(nodes) => Some(nodes.clone()),
_ => None,
})
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetStyle {
id: 2,
style: style(&[("zIndex", StyleValue::Number(5.0))]),
patch: StylePatch::default(),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(insert_items(&batch).contains(&(ROOT_ID, 3, Some(2))));
assert_eq!(order(&batch), Some(vec![ROOT_ID, 2, 4, 3]));
c.apply(Op::SetStyle {
id: 3,
style: style(&[("zIndex", StyleValue::Number(9.0))]),
patch: StylePatch::default(),
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(insert_items(&batch), vec![(ROOT_ID, 3, None)]);
assert_eq!(order(&batch), None, "restacking preserves logical order");
for (op, expected) in [
(
Op::Insert {
parent: ROOT_ID,
child: 3,
before: Some(2),
},
vec![ROOT_ID, 3, 2, 4],
),
(
Op::Insert {
parent: 3,
child: 4,
before: None,
},
vec![ROOT_ID, 3, 4, 2],
),
(
Op::Remove {
parent: ROOT_ID,
child: 3,
},
vec![ROOT_ID, 2],
),
] {
c.apply(op).unwrap();
assert_eq!(order(&c.commit().unwrap()), Some(expected));
}
assert!(c.commit().is_none());
c.set_tree_order_tracking(false);
c.apply(Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
})
.unwrap();
assert_eq!(order(&c.commit().unwrap()), None);
}
#[test]
fn layout_events_carry_frames_and_late_listeners_get_one() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("height", StyleValue::Number(40.0))]),
Op::Listen {
id: 2,
event: EventKind::Layout,
enabled: true,
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
let events = js_events(&mut c);
assert_eq!(
events,
vec![(
2,
EventKind::Layout,
EventPayload::Layout(rect(0.0, 0.0, 320.0, 40.0))
)]
);
// Unchanged frames report nothing; a listener added later learns the
// current frame.
apply(
&mut c,
vec![
Op::Listen {
id: 2,
event: EventKind::Layout,
enabled: false,
},
Op::Listen {
id: 2,
event: EventKind::Layout,
enabled: true,
},
],
);
c.commit();
let events = js_events(&mut c);
assert_eq!(events.len(), 1);
}
#[test]
fn font_scale_scales_text_that_allows_it() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "abc".into(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 5,
text: "abc".into(),
},
Op::SetProp {
id: 4,
prop: Prop::AllowFontScaling(false),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 1,
child: 4,
before: None,
},
],
);
c.commit().unwrap();
c.set_font_scale(2.0);
let batch = c.commit().unwrap();
let size = |id| {
batch.items.iter().find_map(|i| match i {
MountItem::Text { id: i, text, .. } if *i == id => {
Some(text.spans[0].style.font_size.0)
}
_ => None,
})
};
assert_eq!(size(2), Some(28.0));
assert_eq!(size(4), None, "text without font scaling is unchanged");
}
#[test]
fn layout_animation_leads_the_batch() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
Op::Command {
id: 1,
command: Command::LayoutAnimation(crate::LayoutAnimation {
create: None,
update: None,
delete: None,
}),
},
],
);
let batch = c.commit().unwrap();
assert!(
matches!(batch.items[0], MountItem::LayoutAnimation(_)),
"{:?}",
batch.items
);
}
/// A region (2) over a view after it (4) and a fixed board (6) whose row
/// (8) changes too: what each frame item of `batch` animates with.
fn scoped_layout_commit(root_too: bool) -> Vec<(NodeId, Option<crate::LayoutTransition>)> {
let mut c = core();
let mut ops = Vec::new();
for (id, parent, height) in [(2, 1, 10.0), (4, 1, 10.0), (6, 1, 40.0), (8, 6, 10.0)] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(id, &[("height", StyleValue::Number(height))]));
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
apply(&mut c, ops);
c.commit().unwrap();
let spring = crate::LayoutTransition::new(
crate::LayoutCurve::FittedSpring { damping_ratio: 1.0 },
265.0,
);
let mut ops = vec![
style_op(2, &[("height", StyleValue::Number(30.0))]),
style_op(8, &[("height", StyleValue::Number(20.0))]),
Op::Command {
id: 2,
command: Command::LayoutAnimation(crate::LayoutAnimation {
update: Some(spring),
..Default::default()
}),
},
];
if root_too {
ops.push(Op::Command {
id: 1,
command: Command::LayoutAnimation(crate::LayoutAnimation::EASE_IN_EASE_OUT),
});
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let mut current = None;
let mut frames = Vec::new();
for item in &batch.items {
match item {
MountItem::LayoutAnimation(a) => current = a.update,
MountItem::Frame { id, .. } => frames.push((*id, current)),
_ => {}
}
}
frames
}
#[test]
fn a_layout_animation_on_a_node_animates_the_frames_it_moves() {
let frames = scoped_layout_commit(false);
let animated = |id| {
frames
.iter()
.find(|f| f.0 == id)
.unwrap_or_else(|| panic!("no frame of {id}: {frames:?}"))
.1
.is_some()
};
assert!(animated(2), "the region grows: {frames:?}");
assert!(animated(4), "what follows it moves along");
assert!(animated(6), "and the board after it");
assert!(
!animated(8),
"the board's row changed in the same commit, at once: {frames:?}"
);
}
/// A header (2) that collapses with a scoped layout animation over a
/// `flex-1` list (4) that gains a row (12) at its top in the same commit:
/// the list grows along with the header, but its rows move because of the
/// new row, so they change at once (#1952).
#[test]
fn a_layout_animation_does_not_carry_into_a_list_that_updates() {
let mut c = core();
let mut ops = Vec::new();
for (id, parent, style) in [
(2, 1, ("height", StyleValue::Number(100.0))),
(4, 1, ("flexGrow", StyleValue::Number(1.0))),
(8, 4, ("height", StyleValue::Number(20.0))),
(10, 4, ("height", StyleValue::Number(20.0))),
] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(id, &[style]));
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
apply(&mut c, ops);
c.commit().unwrap();
let spring = crate::LayoutTransition::new(
crate::LayoutCurve::FittedSpring { damping_ratio: 1.0 },
265.0,
);
apply(
&mut c,
vec![
style_op(2, &[("height", StyleValue::Number(56.0))]),
Op::Command {
id: 2,
command: Command::LayoutAnimation(crate::LayoutAnimation {
update: Some(spring),
..Default::default()
}),
},
Op::Create {
id: 12,
tag: Tag::View,
},
style_op(12, &[("height", StyleValue::Number(20.0))]),
Op::Insert {
parent: 4,
child: 12,
before: Some(8),
},
],
);
let batch = c.commit().unwrap();
let mut current = None;
let mut frames = Vec::new();
for item in &batch.items {
match item {
MountItem::LayoutAnimation(a) => current = a.update,
MountItem::Frame { id, .. } => frames.push((*id, current)),
_ => {}
}
}
let animated = |id| frames.iter().find(|f| f.0 == id).map(|f| f.1.is_some());
assert_eq!(animated(2), Some(true), "the header collapses: {frames:?}");
assert_eq!(
animated(4),
Some(true),
"the list grows with it: {frames:?}"
);
for row in [8, 10, 12] {
assert_ne!(
animated(row),
Some(true),
"row {row} changes at once: {frames:?}"
);
}
}
#[test]
fn a_layout_animation_on_the_root_still_animates_every_frame() {
let frames = scoped_layout_commit(true);
assert!(
frames
.iter()
.all(|f| f.1 == crate::LayoutAnimation::EASE_IN_EASE_OUT.update),
"{frames:?}"
);
}
#[test]
fn a_scoped_layout_animation_closes_before_the_batch_ends() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("height", StyleValue::Number(10.0))]),
Op::Insert {
parent: 1,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("height", StyleValue::Number(10.0))]),
Op::Insert {
parent: 1,
child: 4,
before: None,
},
],
);
c.commit().unwrap();
let spring = crate::LayoutTransition::new(
crate::LayoutCurve::FittedSpring {
damping_ratio: 0.85,
},
280.0,
);
apply(
&mut c,
vec![
style_op(2, &[("height", StyleValue::Number(24.0))]),
Op::Command {
id: 2,
command: Command::LayoutAnimation(crate::LayoutAnimation {
update: Some(spring),
..Default::default()
}),
},
],
);
let batch1 = c.commit().unwrap();
// Simulate a second commit in the same engine mount turn (e.g. recycled
// list cells placed after a Tabs indicator's follow_transition commit).
apply(
&mut c,
vec![style_op(4, &[("height", StyleValue::Number(36.0))])],
);
let batch2 = c.commit().unwrap();
let mut current = None;
let mut frames = Vec::new();
for item in batch1.items.iter().chain(&batch2.items) {
match item {
MountItem::LayoutAnimation(a) => current = a.update,
MountItem::Frame { id, .. } => frames.push((*id, current)),
_ => {}
}
}
assert!(
frames
.iter()
.any(|&(id, anim)| id == 2 && anim == Some(spring)),
"scoped node animates in commit 1: {frames:?}"
);
assert_eq!(
frames
.iter()
.rev()
.find(|&&(id, _)| id == 4)
.map(|&(_, anim)| anim),
Some(None),
"commit 2 frames must not inherit commit 1's scoped layout animation: {frames:?}"
);
}
#[test]
fn view_props_and_gestures_reach_the_platform() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::HitSlop(crate::EdgeInsets::all(px(10.0))),
},
Op::SetProp {
id: 2,
prop: Prop::PinchValue(Some(7)),
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(
|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.hit_slop.top == px(10.0))
));
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Gestures { id: 2, values } if values.pinch == Some(7)))
);
}
/// A label that follows app state goes alone, not with all the view's
/// props; any other change (or the first props) sends them all.
#[test]
fn a_changing_label_is_sent_alone() {
use crate::props::AccessibilityProp;
let label = |v: &str| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::Label(Some(v.into()))),
};
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
label("0 items"),
Op::Insert {
parent: 1,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.accessibility.label.as_deref() == Some("0 items"))));
apply(&mut c, vec![label("1 item")]);
let batch = c.commit().unwrap();
assert_eq!(batch.items.len(), 1, "{:?}", batch.items);
assert!(
matches!(&batch.items[0], MountItem::AccessibilityLabel { id: 2, label: Some(l) } if &**l == "1 item")
);
// With another prop in the same commit, everything goes once.
apply(
&mut c,
vec![
label("2 items"),
Op::SetProp {
id: 2,
prop: Prop::TestId(Some("counter".into())),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(batch.items.len(), 1, "{:?}", batch.items);
assert!(
matches!(&batch.items[0], MountItem::ViewProps { id: 2, props } if props.accessibility.label.as_deref() == Some("2 items"))
);
}
/// `nativeID` names any view for the embedding app (a scroll view it
/// watches, `watchScroll`): it reaches the platforms apart from `testID`.
#[test]
fn native_id_reaches_the_platform() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::NativeId(Some("page".into())),
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.native_id.as_deref() == Some("page") && props.test_id.is_none())));
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::NativeId(None),
}],
);
let batch = c.commit().unwrap();
assert!(
batch.items.iter().any(
|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.native_id.is_none())
)
);
}
/// The relations of one view's last `ViewProps` in `batch`: its active
/// descendant and what it controls.
fn relations_in(batch: &MountBatch, id: NodeId) -> Option<(Option<NodeId>, Option<NodeId>)> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: at, props } if *at == id => Some((
props.accessibility.active_descendant,
props.accessibility.controls,
)),
_ => None,
})
}
/// `accessibilityActiveDescendant` and `accessibilityControls` name other
/// views: the platform gets their ids, as the views named change, come
/// after the one naming them or go.
#[test]
fn accessibility_relations_name_other_views() {
use crate::element::ElementTarget;
let mut c = core();
let view = |id| Op::Create { id, tag: Tag::View };
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let active = |target: Option<NodeId>| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::ActiveDescendant(
target.map(ElementTarget::of_node),
)),
};
// A field naming its list and the list's first option.
apply(
&mut c,
vec![
view(2),
view(4),
view(6),
view(8),
insert(1, 2),
insert(1, 4),
insert(4, 6),
insert(4, 8),
active(Some(6)),
Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::Controls(Some(
ElementTarget::of_node(4),
))),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(relations_in(&batch, 2), Some((Some(6), Some(4))));
// The highlight moves: only the field's props go again.
apply(&mut c, vec![active(Some(8))]);
let batch = c.commit().unwrap();
assert_eq!(relations_in(&batch, 2), Some((Some(8), Some(4))));
// Something else changes: the field's props do not go again.
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::TestId(Some("first".into())),
}],
);
let batch = c.commit().unwrap();
assert_eq!(relations_in(&batch, 2), None);
// The option named goes: the field names none.
apply(
&mut c,
vec![
Op::Remove {
parent: 4,
child: 8,
},
Op::Release { id: 8 },
],
);
let batch = c.commit().unwrap();
assert_eq!(relations_in(&batch, 2), Some((None, Some(4))));
// A view named before it is made is named once it is.
apply(&mut c, vec![active(Some(10))]);
assert_eq!(c.commit().and_then(|b| relations_in(&b, 2)), None);
apply(&mut c, vec![view(10), insert(4, 10)]);
let batch = c.commit().unwrap();
assert_eq!(relations_in(&batch, 2), Some((Some(10), Some(4))));
// Cleared.
apply(
&mut c,
vec![
active(None),
Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::Controls(None)),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(relations_in(&batch, 2), Some((None, None)));
assert!(c.relators.is_empty());
}
/// The description and the view `accessibilityDescribedBy` names in one
/// view's last `ViewProps` in `batch`.
fn described_in(batch: &MountBatch, id: NodeId) -> Option<(Option<String>, Option<NodeId>)> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: at, props } if *at == id => Some((
props
.accessibility
.description
.as_deref()
.map(str::to_owned),
props.accessibility.described_by,
)),
_ => None,
})
}
/// The scroll view a view's `ios={{ scrollEdgeElement }}` names, as the
/// platform gets it in the view's props (the last ones in `batch`).
fn scroll_edge_in(batch: &MountBatch, id: NodeId) -> Option<Option<crate::ScrollEdgeElement>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: at, props } if *at == id => Some(props.scroll_edge_element),
_ => None,
})
}
/// `ios={{ scrollEdgeElement }}` names the scroll view a view floats over:
/// the platform gets its id and the edge while it is a rendered scroll
/// view, nothing while it names another kind of view or the scroll view
/// is out of the tree, and nothing once it names none.
#[test]
fn scroll_edge_element_names_the_scroll_view_a_view_floats_over() {
use crate::{ScrollEdge, ScrollEdgeElement, element::ScrollEdgeTarget};
let mut c = core();
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let floats_over = |target: Option<NodeId>| Op::SetProp {
id: 4,
prop: Prop::ScrollEdgeElement(
target.map(|t| ScrollEdgeTarget::of_node(t, ScrollEdge::Bottom)),
),
};
let at_bottom = |scroll_view| {
Some(Some(ScrollEdgeElement {
scroll_view,
edge: ScrollEdge::Bottom,
}))
};
// A list and a bar floating over its bottom edge.
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Create {
id: 6,
tag: Tag::View,
},
insert(1, 2),
insert(1, 4),
insert(1, 6),
floats_over(Some(2)),
],
);
assert_eq!(scroll_edge_in(&c.commit().unwrap(), 4), at_bottom(2));
// Something else changes: the bar's props do not go again.
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::TestId(Some("other".into())),
}],
);
assert_eq!(c.commit().and_then(|b| scroll_edge_in(&b, 4)), None);
// A view that is no scroll view names nothing.
apply(&mut c, vec![floats_over(Some(6))]);
assert_eq!(scroll_edge_in(&c.commit().unwrap(), 4), Some(None));
// The scroll view again, then out of the tree, then back.
apply(&mut c, vec![floats_over(Some(2))]);
assert_eq!(scroll_edge_in(&c.commit().unwrap(), 4), at_bottom(2));
apply(
&mut c,
vec![Op::Remove {
parent: 1,
child: 2,
}],
);
assert_eq!(scroll_edge_in(&c.commit().unwrap(), 4), Some(None));
apply(&mut c, vec![insert(1, 2)]);
assert_eq!(scroll_edge_in(&c.commit().unwrap(), 4), at_bottom(2));
// It names none.
apply(&mut c, vec![floats_over(None)]);
assert_eq!(scroll_edge_in(&c.commit().unwrap(), 4), Some(None));
}
/// A scroll view culled far down another one's content is named by a view
/// floating over it: the platform gets its id once its native view is made,
/// after the view that makes it, in the batch that makes it.
#[test]
fn scroll_edge_element_names_a_culled_scroll_view_once_it_is_made() {
use crate::{ScrollEdge, ScrollEdgeElement, element::ScrollEdgeTarget};
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// Rows of 50 in a wrapper, then a scroll view at 1900.
ops.extend(child_view(4, 2, 2000.0, &[]));
for i in 0..38u32 {
ops.extend(child_view(10 + 2 * i, 4, 50.0, &[]));
}
ops.extend([
Op::Create {
id: 200,
tag: Tag::Scroll,
},
style_op(200, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: 4,
child: 200,
before: None,
},
]);
// A bar floating over its bottom edge.
ops.extend(child_view(6, ROOT_ID, 40.0, &[]));
ops.push(Op::SetProp {
id: 6,
prop: Prop::ScrollEdgeElement(Some(ScrollEdgeTarget::of_node(200, ScrollEdge::Bottom))),
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&200));
assert_eq!(scroll_edge_in(&batch, 6).flatten(), None);
// Scrolled to it, it is made, and the bar names it after that.
c.set_scroll_offset(2, point(Points::ZERO, Points(1900.0)), 0);
let batch = c.commit().unwrap();
let made = batch
.items
.iter()
.position(|i| matches!(i, MountItem::Create { id: 200, .. }))
.expect("the scroll view is made");
let named = batch
.items
.iter()
.rposition(|i| matches!(i, MountItem::ViewProps { id: 6, .. }))
.expect("the bar's props go again");
assert!(made < named);
assert_eq!(
scroll_edge_in(&batch, 6),
Some(Some(ScrollEdgeElement {
scroll_view: 200,
edge: ScrollEdge::Bottom,
}))
);
}
/// `accessibilityDescribedBy` names the view that describes this one (a
/// field's error line): the platform gets its id, and the description is
/// that view's text, followed as it changes, over the view's own
/// `accessibilityDescription`, which comes back once it names none.
#[test]
fn accessibility_described_by_describes_a_view_with_another_ones_text() {
use crate::element::ElementTarget;
let mut c = core();
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let described_by = |target: Option<NodeId>| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::DescribedBy(
target.map(ElementTarget::of_node),
)),
};
let description = |text: &str| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::Description(Some(text.into()))),
};
let create = |id, tag| Op::Create { id, tag };
let raw = |id, text: &str| Op::CreateText {
id,
text: text.into(),
};
// A field and its error line: an icon labelled, two texts, a hidden
// one.
apply(
&mut c,
vec![
create(2, Tag::View),
create(4, Tag::View),
create(6, Tag::View),
Op::SetProp {
id: 6,
prop: Prop::Accessibility(AccessibilityProp::Label(Some("Error".into()))),
},
create(8, Tag::Text),
raw(10, "Enter a name."),
create(12, Tag::Text),
raw(14, "Use letters"),
create(16, Tag::Text),
raw(18, "hidden"),
Op::SetProp {
id: 16,
prop: Prop::Accessibility(AccessibilityProp::Hidden(true)),
},
insert(8, 10),
insert(12, 14),
insert(16, 18),
insert(4, 6),
insert(4, 8),
insert(4, 12),
insert(4, 16),
insert(1, 2),
insert(1, 4),
description("Required"),
described_by(Some(4)),
],
);
let batch = c.commit().unwrap();
assert_eq!(
described_in(&batch, 2),
Some((Some("Error Enter a name. Use letters".into()), Some(4)))
);
// The error line's text changes: the description follows.
apply(
&mut c,
vec![Op::SetText {
id: 14,
text: "Use letters only".into(),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
described_in(&batch, 2),
Some((Some("Error Enter a name. Use letters only".into()), Some(4)))
);
// Something else changes: the field's props do not go again.
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::TestId(Some("icon".into())),
}],
);
assert_eq!(c.commit().and_then(|b| described_in(&b, 2)), None);
// Its own description changes while it is described: what the
// platform reads stays the named view's text.
apply(&mut c, vec![description("Your name")]);
assert_eq!(c.commit().and_then(|b| described_in(&b, 2)), None);
// The error line leaves the tree (not released yet, as a region
// keeps what it removes until it lets it go): its own description
// is back.
apply(
&mut c,
vec![Op::Remove {
parent: 1,
child: 4,
}],
);
let batch = c.commit().unwrap();
assert_eq!(
described_in(&batch, 2),
Some((Some("Your name".into()), None))
);
// Back in the tree: described again.
apply(&mut c, vec![insert(1, 4)]);
let batch = c.commit().unwrap();
assert_eq!(
described_in(&batch, 2),
Some((Some("Error Enter a name. Use letters only".into()), Some(4)))
);
// Gone for good.
apply(
&mut c,
vec![
Op::Remove {
parent: 1,
child: 4,
},
Op::Release { id: 4 },
],
);
let batch = c.commit().unwrap();
assert_eq!(
described_in(&batch, 2),
Some((Some("Your name".into()), None))
);
// Cleared.
apply(&mut c, vec![described_by(None)]);
let _ = c.commit();
assert!(c.relators.is_empty());
let a = &c.nodes[c.key(2).unwrap() as usize]
.props
.as_ref()
.unwrap()
.accessibility;
assert_eq!(a.description.as_deref(), Some("Your name"));
assert_eq!(a.described_by, None);
}
/// An error line hidden from assistive technologies (`accessibilityHidden`,
/// so that it is not read twice) and named by `accessibilityDescribedBy`
/// still describes the field, as the web's `aria-describedby` reads a hidden
/// element it names.
#[test]
fn accessibility_described_by_a_hidden_line_still_describes() {
use crate::element::ElementTarget;
let mut c = core();
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 6,
text: "Enter a name.".into(),
},
Op::SetProp {
id: 4,
prop: Prop::Accessibility(AccessibilityProp::Hidden(true)),
},
insert(4, 6),
insert(1, 2),
insert(1, 4),
Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::DescribedBy(Some(
ElementTarget::of_node(4),
))),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(
described_in(&batch, 2),
Some((Some("Enter a name.".into()), Some(4)))
);
}
#[test]
fn screens_fill_their_stack_below_the_header() {
let mut c = core();
c.set_safe_area(crate::EdgeInsets {
top: px(20.0),
..Default::default()
});
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Stack,
},
style_op(2, &[("flex", StyleValue::Number(1.0))]),
Op::Create {
id: 3,
tag: Tag::Screen,
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("flex", StyleValue::Number(1.0))]),
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
// The screen fills the stack; its content starts below the status bar
// and the 44pt bar.
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 320.0, 480.0)));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 64.0, 320.0, 416.0)));
assert!(batch.items.iter().any(
|i| matches!(i, MountItem::ScreenConfig { id: 3, config } if config.header_height == px(64.0))
));
// The header the platform measured replaces the estimate (Catalyst
// can show its bar in the window's title bar).
c.set_screen_header(3, Some(px(52.0)));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 52.0, 320.0, 428.0)));
assert!(batch.items.iter().any(
|i| matches!(i, MountItem::ScreenConfig { id: 3, config } if config.header_height == px(52.0))
));
// Without a header, the content starts at the top.
apply(
&mut c,
vec![Op::SetProp {
id: 3,
prop: Prop::Screen(crate::ScreenProp::HeaderVisible(false)),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 0.0, 320.0, 480.0)));
}
/// Without a native header, a screen's `header` slot is as wide as the
/// screen whatever it holds: a long one-line title shrinks instead of
/// pushing the header, and the button after it, past the window's edge.
#[test]
fn a_drawn_header_is_as_wide_as_the_screen() {
let mut c = core();
c.set_header_heights(crate::NO_NATIVE_HEADER.0, crate::NO_NATIVE_HEADER.1);
let square = |id| {
style_op(
id,
&[
("width", StyleValue::Number(44.0)),
("height", StyleValue::Number(44.0)),
("flexShrink", StyleValue::Number(0.0)),
],
)
};
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Stack,
},
style_op(2, &[("flex", StyleValue::Number(1.0))]),
Op::Create {
id: 3,
tag: Tag::Screen,
},
Op::Create {
id: 4,
tag: Tag::HeaderItem,
},
Op::SetProp {
id: 4,
prop: Prop::HeaderSlot(crate::HeaderSlot::Header),
},
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(6, &[("flexDirection", StyleValue::Str("row"))]),
Op::Create {
id: 8,
tag: Tag::View,
},
square(8),
Op::Create {
id: 10,
tag: Tag::View,
},
style_op(
10,
&[
("flex", StyleValue::Number(1.0)),
("minWidth", StyleValue::Number(0.0)),
],
),
Op::Create {
id: 12,
tag: Tag::Text,
},
style_op(12, &[("numberOfLines", StyleValue::Number(1.0))]),
Op::CreateText {
id: 13,
text: "a title far too long to fit on one line of the header".repeat(2),
},
Op::Create {
id: 14,
tag: Tag::View,
},
square(14),
Op::Create {
id: 16,
tag: Tag::View,
},
style_op(16, &[("flex", StyleValue::Number(1.0))]),
];
ops.extend([
insert(12, 13),
insert(10, 12),
insert(6, 8),
insert(6, 10),
insert(6, 14),
insert(4, 6),
insert(3, 4),
insert(3, 16),
insert(2, 3),
insert(ROOT_ID, 2),
]);
apply(&mut c, ops);
let mut frames = std::collections::HashMap::new();
for width in [320.0, 360.0, 600.0] {
c.set_viewport(size_pt(width, 480.0));
let batch = c.commit().unwrap();
for item in &batch.items {
if let MountItem::Frame { id, frame } = item {
frames.insert(*id, *frame);
}
}
let header = frames[&4];
assert_eq!(header.size.width, px(width), "the header at {width}");
let right = frames[&14];
assert_eq!(
right.origin.x + right.size.width,
px(width),
"the button after the title at {width}"
);
assert_eq!(frames[&10].size.width, px(width - 88.0));
}
}
/// With a native header, a title view is as wide as its content, at most
/// the room the bar leaves between its items: a long one-line title shrinks
/// instead of running under the trailing item (#1895), a short one keeps
/// its width.
#[test]
fn a_native_title_view_fits_between_the_header_items() {
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let build = |title: &str| {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Stack,
},
style_op(2, &[("flex", StyleValue::Number(1.0))]),
Op::Create {
id: 3,
tag: Tag::Screen,
},
// The title view: a clamped text, then a button.
Op::Create {
id: 4,
tag: Tag::HeaderItem,
},
Op::SetProp {
id: 4,
prop: Prop::HeaderSlot(crate::HeaderSlot::Title),
},
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(6, &[("flexDirection", StyleValue::Str("row"))]),
Op::Create {
id: 10,
tag: Tag::View,
},
style_op(
10,
&[
("flex", StyleValue::Number(1.0)),
("minWidth", StyleValue::Number(0.0)),
],
),
Op::Create {
id: 12,
tag: Tag::Text,
},
style_op(12, &[("numberOfLines", StyleValue::Number(1.0))]),
Op::CreateText {
id: 13,
text: title.to_string(),
},
Op::Create {
id: 14,
tag: Tag::View,
},
style_op(
14,
&[
("width", StyleValue::Number(40.0)),
("height", StyleValue::Number(40.0)),
("flexShrink", StyleValue::Number(0.0)),
],
),
// The trailing item, 60 wide.
Op::Create {
id: 20,
tag: Tag::HeaderItem,
},
Op::SetProp {
id: 20,
prop: Prop::HeaderSlot(crate::HeaderSlot::Right),
},
Op::Create {
id: 22,
tag: Tag::View,
},
style_op(
22,
&[
("width", StyleValue::Number(60.0)),
("height", StyleValue::Number(40.0)),
],
),
];
ops.extend([
insert(12, 13),
insert(10, 12),
insert(6, 10),
insert(6, 14),
insert(4, 6),
insert(20, 22),
insert(3, 4),
insert(3, 20),
insert(2, 3),
insert(ROOT_ID, 2),
]);
apply(&mut c, ops);
let mut frames = std::collections::HashMap::new();
let batch = c.commit().unwrap();
for item in &batch.items {
if let MountItem::Frame { id, frame } = item {
frames.insert(*id, *frame);
}
}
frames
};
// 320 wide: the room is 320 - 2 * 16 (insets) - (60 + 16) (the item).
let frames = build(&"a title far too long to fit on one line of the header".repeat(2));
assert_eq!(frames[&4].size.width, px(212.0));
let button = frames[&14];
assert_eq!(
button.origin.x + button.size.width,
px(212.0),
"the button in the title"
);
let frames = build("Hi");
assert!(
frames[&4].size.width < px(100.0),
"a short title keeps its width"
);
}
#[test]
fn a_screen_keeps_the_bottom_bar_unless_it_says_otherwise() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Stack,
},
style_op(2, &[("flex", StyleValue::Number(1.0))]),
Op::Create {
id: 3,
tag: Tag::Screen,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
],
);
// `hidesBottomBarWhenPushed` is off unless the page asks for it: the
// platform looks the flag up on the screen it shows.
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::ScreenConfig { id: 3, config }
if !config.hides_bottom_bar_when_pushed))
);
apply(
&mut c,
vec![Op::SetProp {
id: 3,
prop: Prop::Screen(crate::ScreenProp::HidesBottomBarWhenPushed(true)),
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::ScreenConfig { id: 3, config }
if config.hides_bottom_bar_when_pushed))
);
}
#[test]
fn modals_lay_out_at_the_reported_size() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Modal,
},
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("flex", StyleValue::Number(1.0))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
// The viewport until the platform reports the presented size.
assert_eq!(frame_of(&batch, 3).map(|f| f.size.height.0), Some(480.0));
c.set_root_size(2, size_pt(320.0, 400.0), crate::EdgeInsets::default());
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).map(|f| f.size.height.0), Some(400.0));
}
#[test]
fn right_to_left_layouts() {
let mut c = core();
let n = |v: f32| StyleValue::Number(v);
let s = |v: &'static str| StyleValue::Str(v);
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(
2,
&[
("flexDirection", s("row")),
("width", n(300.0)),
("height", n(50.0)),
],
),
];
// Two boxes in a row: the first with `marginStart`, the second
// with `marginLeft`, which keeps its side right to left (CSS).
for (id, key) in [(3, "marginStart"), (4, "marginLeft")] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(
id,
&[("width", n(50.0)), ("height", n(50.0)), (key, n(10.0))],
));
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).map(|f| f.origin.x.0), Some(10.0));
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x.0), Some(70.0));
// The surface turns right to left: the row runs from the right.
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(true),
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::LayoutDirection { rtl: true }))
);
assert_eq!(
frame_of(&batch, 3).map(|f| f.origin.x.0),
Some(300.0 - 10.0 - 50.0)
);
assert_eq!(
frame_of(&batch, 4).map(|f| f.origin.x.0),
Some(300.0 - 60.0 - 50.0)
);
// A subtree built detached and inserted takes the direction too; an
// explicit `direction` overrides it.
apply(
&mut c,
vec![
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(
5,
&[
("flexDirection", s("row")),
("direction", s("ltr")),
("height", n(20.0)),
],
),
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(
6,
&[
("width", n(20.0)),
("start", n(5.0)),
("position", s("absolute")),
],
),
Op::Insert {
parent: 5,
child: 6,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 5,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 6).map(|f| f.origin.x.0), Some(5.0));
// Back to left to right.
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(false),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).map(|f| f.origin.x.0), Some(10.0));
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x.0), Some(70.0));
}
#[test]
fn right_to_left_classes_stay_physical() {
let mut c = core();
// The surface is right to left before anything is made.
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(true),
}],
);
view_with_classes(&mut c, 2, "flex-row w-[300px] h-[50px]");
let n = |v: f32| StyleValue::Number(v);
let mut ops = Vec::new();
// `ml-*` is the left margin right to left too (CSS), and so is an inline
// `marginLeft`; `ms-*` is the start.
for (id, classes) in [
(3, "w-[50px] h-[50px] ml-[10px]"),
(4, "w-[50px] h-[50px] ms-[10px]"),
(5, "w-[50px] h-[50px]"),
(
6,
"absolute left-[5px] w-[20px] h-[20px] border-l-4 border-l-red-500 rounded-tl-lg",
),
] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(class_op(id, classes));
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
}
ops.push(style_op(5, &[("marginLeft", n(10.0))]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
let x = |batch: &MountBatch, id| frame_of(batch, id).map(|f| f.origin.x.0);
// The row runs from the right: 3 is the first, at the right edge, with
// its margin on its left; 4 has its start margin on its right.
assert_eq!(x(&batch, 3), Some(300.0 - 50.0));
assert_eq!(x(&batch, 4), Some(300.0 - 60.0 - 10.0 - 50.0));
assert_eq!(x(&batch, 5), Some(300.0 - 60.0 - 60.0 - 50.0));
assert_eq!(x(&batch, 6), Some(5.0));
let v = view_style_of(&batch, 6).unwrap();
assert_eq!(v.borders.widths.left, px(4.0));
assert_eq!(v.borders.widths.right, px(0.0));
assert_eq!(v.borders.colors[3], Color(0xfb2c_36ff));
assert_eq!(v.corner_radius.top_left, Some(px(8.0)));
assert_eq!(v.corner_radius.top_right, None);
// Back to left to right, the same.
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(false),
}],
);
let batch = c.commit().unwrap();
assert_eq!(x(&batch, 3), Some(10.0));
assert_eq!(x(&batch, 4), Some(60.0 + 10.0));
// Where it was: no new frame.
assert_eq!(x(&batch, 6), None);
let v = view_style_of(&batch, 6).unwrap();
assert_eq!(v.borders.widths.left, px(4.0));
assert_eq!(v.corner_radius.top_left, Some(px(8.0)));
}
#[test]
fn right_to_left_text_alignment_stays_physical() {
let mut c = core();
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(true),
}],
);
let mut ops = Vec::new();
// Classes and style keys alike: `left` and `right` keep their sides,
// `start` and `end` follow the direction (CSS).
for (id, classes, align) in [
(2, "text-left", None),
(4, "text-end", None),
(6, "text-right", None),
(8, "", Some("left")),
(10, "", Some("end")),
(12, "", Some("start")),
] {
ops.extend([
Op::Create { id, tag: Tag::Text },
class_op(id, classes),
style_op(
id,
&align
.map(|a| vec![("textAlign", StyleValue::Str(a))])
.unwrap_or_default(),
),
Op::CreateText {
id: id + 1,
text: "hello".into(),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let align = |id| {
batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: i, text, .. } if *i == id => Some(text.align),
_ => None,
})
.unwrap()
};
assert_eq!(align(2), TextAlign::Left);
assert_eq!(align(4), TextAlign::Left);
assert_eq!(align(6), TextAlign::Right);
assert_eq!(align(8), TextAlign::Left);
assert_eq!(align(10), TextAlign::Left);
assert_eq!(align(12), TextAlign::Right);
}
#[test]
fn a_child_moved_between_space_parents_takes_the_new_margin() {
let mut c = core();
view_with_classes(&mut c, 2, "flex-row space-x-2 w-[300px] h-[20px]");
view_with_classes(&mut c, 3, "flex-row space-x-8 w-[300px] h-[20px]");
let mut ops = Vec::new();
for (id, parent) in [(4, 2), (5, 2), (6, 3), (7, 3)] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(class_op(id, "size-[20px]"));
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
apply(&mut c, ops);
c.commit().unwrap();
// 4 leaves `space-x-2` for `space-x-8`, before 7: 8 * 4 after it.
c.apply(Op::Remove {
parent: 2,
child: 4,
})
.unwrap();
apply(
&mut c,
vec![Op::Insert {
parent: 3,
child: 4,
before: Some(7),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 7).map(|f| f.origin.x.0), Some(104.0));
}
#[test]
fn space_classes_give_children_but_the_last_margins() {
let mut c = core();
view_with_classes(&mut c, 2, "flex-row space-x-4 w-[300px] h-[20px]");
let mut ops = Vec::new();
for (id, classes) in [
(3, "size-[20px]"),
(4, "size-[20px] mr-1"),
(5, "size-[20px]"),
] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(class_op(id, classes));
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
}
// A child with no classes gets it too.
ops.push(Op::Create {
id: 6,
tag: Tag::View,
});
ops.push(style_op(
6,
&[
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(20.0)),
],
));
ops.push(Op::Insert {
parent: 2,
child: 6,
before: Some(5),
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
let x = |batch: &MountBatch, id| frame_of(batch, id).map(|f| f.origin.x.0);
// 3: 16 after it; 4: its own `mr-1` wins (4); 6: 16; 5 is last.
assert_eq!(x(&batch, 3), Some(0.0));
assert_eq!(x(&batch, 4), Some(36.0));
assert_eq!(x(&batch, 6), Some(60.0));
assert_eq!(x(&batch, 5), Some(96.0));
// Appended: the last before gets its margin, the new one has none.
apply(
&mut c,
vec![
Op::Create {
id: 7,
tag: Tag::View,
},
class_op(7, "size-[20px]"),
Op::Insert {
parent: 2,
child: 7,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(x(&batch, 7), Some(132.0));
// The last one gone, the one before it is last again.
c.apply(Op::Remove {
parent: 2,
child: 7,
})
.unwrap();
apply(
&mut c,
vec![
Op::Create {
id: 8,
tag: Tag::View,
},
class_op(8, "size-[20px]"),
],
);
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 8,
before: None,
}],
);
let batch = c.commit().unwrap();
assert_eq!(x(&batch, 8), Some(132.0));
// Reversed, the margin is on the start side; without the class, none.
c.apply(class_op(
2,
"flex-row space-x-4 space-x-reverse w-[300px] h-[20px]",
))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(x(&batch, 3), Some(16.0));
c.apply(class_op(2, "flex-row w-[300px] h-[20px]")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(x(&batch, 3), Some(0.0));
assert_eq!(x(&batch, 6), Some(44.0));
}
#[test]
fn borders_and_rings_without_a_color_are_the_inherited_text_color() {
let mut c = core();
view_with_classes(&mut c, 2, "text-white");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
Op::Create {
id: 4,
tag: Tag::View,
},
class_op(4, "border-2 ring"),
Op::Insert {
parent: 3,
child: 4,
before: None,
},
// Built apart, then inserted: the color reaches it through 3.
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(5, &[("borderWidth", StyleValue::Number(1.0))]),
Op::Insert {
parent: 2,
child: 5,
before: None,
},
],
);
let batch = c.commit().unwrap();
let v = view_style_of(&batch, 4).unwrap();
assert_eq!(v.borders.colors, [Color(0xffff_ffff); 4]);
assert_eq!(
v.effects.as_ref().unwrap().box_shadows[0].color,
Color(0xffff_ffff)
);
// An inline style's border is too, as in CSS; a side whose color it sets
// keeps that.
assert_eq!(
view_style_of(&batch, 5).unwrap().borders.colors,
[Color(0xffff_ffff); 4]
);
apply(
&mut c,
vec![
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(
6,
&[
("borderWidth", StyleValue::Number(1.0)),
("borderTopColor", StyleValue::Str("#0000ff")),
],
),
Op::Insert {
parent: 2,
child: 6,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 6).unwrap().borders.colors,
[
Color(0x0000_ffff),
Color(0xffff_ffff),
Color(0xffff_ffff),
Color(0xffff_ffff)
]
);
// The ancestor's color changes: so do the borders'.
c.apply(class_op(2, "text-red-500")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 4).unwrap().borders.colors[0],
Color(0xfb2c_36ff)
);
assert_eq!(
view_style_of(&batch, 5).unwrap().borders.colors[0],
Color(0xfb2c_36ff)
);
// Moved under a view of no color: black.
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
}],
);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 4).unwrap().borders.colors[0],
Color::BLACK
);
}
#[test]
fn shadow_layers_without_a_color_are_the_text_color() {
// CSS's `currentColor`: a layer that names no color takes the node's
// text color, and follows it; one that names its color keeps it.
let mut c = core();
view_with_classes(&mut c, 2, "text-[#ff0000]");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[("boxShadow", StyleValue::Str("0 2px 4px, 0 1px 1px #0000ff"))],
),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let colors = |batch: &MountBatch| {
view_style_of(batch, 3)
.unwrap()
.effects
.unwrap()
.box_shadows
.iter()
.map(|l| l.color)
.collect::<Vec<_>>()
};
let batch = c.commit().unwrap();
assert_eq!(colors(&batch), [Color(0xff00_00ff), Color(0x0000_ffff)]);
c.apply(class_op(2, "text-[#00ff00]")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(colors(&batch), [Color(0x00ff_00ff), Color(0x0000_ffff)]);
}
#[test]
fn current_color_written_out_follows_the_text_color() {
// `backgroundColor: "currentColor"` over a class's background, and a
// gradient from it: the inherited text color, again when it changes.
let mut c = core();
view_with_classes(&mut c, 2, "text-[#ff0000]");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "bg-[#0000ff]"),
style_op(
3,
&[
("backgroundColor", StyleValue::Str("currentColor")),
(
"backgroundImage",
StyleValue::Str("linear-gradient(currentColor, #ffffff)"),
),
],
),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let background = |batch: &MountBatch| {
let style = view_style_of(batch, 3).unwrap();
let stop = style.effects.unwrap().background_images[0].stops[0].color;
(style.background_color, stop)
};
let batch = c.commit().unwrap();
let red = Color(0xff00_00ff);
assert_eq!(background(&batch), (red, red));
c.apply(class_op(2, "text-[#00ff00]")).unwrap();
let batch = c.commit().unwrap();
let green = Color(0x00ff_00ff);
assert_eq!(background(&batch), (green, green));
}
#[test]
fn space_margins_are_on_the_end_side_right_to_left() {
// Tailwind's `margin-inline-end`: the left side right to left, also
// when the direction changes after the children are styled.
let mut c = core();
view_with_classes(&mut c, 2, "flex-row space-x-4 w-[300px] h-[20px]");
for id in [3, 4, 5] {
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, "size-[20px]"),
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
let x = |batch: &MountBatch, id| frame_of(batch, id).map(|f| f.origin.x.0);
let batch = c.commit().unwrap();
assert_eq!(
[x(&batch, 3), x(&batch, 4), x(&batch, 5)],
[Some(0.0), Some(36.0), Some(72.0)]
);
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(true),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
[x(&batch, 3), x(&batch, 4), x(&batch, 5)],
[Some(280.0), Some(244.0), Some(208.0)]
);
}
#[test]
fn state_styles_take_the_text_color_and_a_flex_row() {
// `activeStyle={{ borderWidth: 2, display: "flex" }}` as `style` would.
let mut c = core();
view_with_classes(&mut c, 2, "text-[#ff0000]");
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::ActiveStyle(patch(&[
("borderWidth", StyleValue::Number(2.0)),
("display", StyleValue::Str("flex")),
])),
}],
);
c.commit();
c.set_states(2, crate::tailwind::state::PRESSED);
let v = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(v.borders.colors, [Color(0xff00_00ff); 4]);
}
#[test]
fn right_to_left_horizontal_scrolls() {
let mut c = core();
let n = |v: f32| StyleValue::Number(v);
let mut ops = vec![
Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(true),
},
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
},
style_op(
2,
&[
("width", n(150.0)),
("height", n(50.0)),
("paddingStart", n(10.0)),
],
),
];
for id in [3, 4] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(Op::SetStyle {
id,
style: style(&[("width", n(100.0)), ("height", n(50.0))]),
patch: StylePatch::default(),
});
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
// Content: 10 (start padding) + 200; the first child at the right end.
assert_eq!(
frame_of(&batch, 3).map(|f| f.origin.x.0),
Some(210.0 - 10.0 - 100.0)
);
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x.0), Some(0.0));
// It starts scrolled to its right end.
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Command {
id: 2,
command: Command::ScrollTo { x, .. }
} if x.0 == 60.0
)));
}
fn class_op(id: NodeId, classes: &str) -> Op {
Op::SetProp {
id,
prop: Prop::Class(classes.into()),
}
}
fn view_style_of(batch: &MountBatch, id: NodeId) -> Option<ViewStyle> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewStyle { id: i, style } if *i == id => Some((**style).clone()),
_ => None,
})
}
fn view_with_classes(c: &mut Core<FakeEngine>, id: NodeId, classes: &str) {
apply(
c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, classes),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
],
);
}
/// A JS value for the host decoders in these tests, with the shapes they
/// read: objects of fields, arrays, strings, numbers, booleans and null.
#[derive(Clone, Debug, PartialEq)]
#[allow(
dead_code,
reason = "a test input implements the whole HostInput trait"
)]
enum HostTestValue<'a> {
Null,
Bool(bool),
Number(f64),
String(&'a str),
Object(Vec<(&'a str, HostTestValue<'a>)>),
Array(Vec<HostTestValue<'a>>),
}
impl<'a> HostTestValue<'a> {
fn object(fields: impl IntoIterator<Item = (&'a str, HostTestValue<'a>)>) -> Self {
Self::Object(fields.into_iter().collect())
}
}
struct HostTestList<'a>(Vec<HostTestValue<'a>>);
impl<'a> crate::js::host::HostList for HostTestList<'a> {
type Item = HostTestValue<'a>;
fn len(&self) -> usize {
self.0.len()
}
fn item(&self, index: usize) -> Option<Self::Item> {
self.0.get(index).cloned()
}
}
impl<'a> crate::js::host::HostInput for HostTestValue<'a> {
type List = HostTestList<'a>;
fn is_nullish(&self) -> bool {
matches!(self, Self::Null)
}
fn is_object(&self) -> bool {
matches!(self, Self::Object(_) | Self::Array(_))
}
fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(v) => Some(*v),
_ => None,
}
}
fn as_number(&self) -> Option<f64> {
match self {
Self::Number(v) => Some(*v),
_ => None,
}
}
fn as_string(&self) -> Option<String> {
match self {
Self::String(v) => Some((*v).to_owned()),
_ => None,
}
}
fn field(&self, key: &str) -> Option<Self> {
match self {
Self::Object(fields) => fields
.iter()
.find(|(name, _)| *name == key)
.map(|(_, value)| value.clone()),
_ => None,
}
}
fn as_list(&self) -> Option<Self::List> {
match self {
Self::Array(items) => Some(HostTestList(items.clone())),
_ => None,
}
}
fn entries(&self) -> Vec<(String, Self)> {
match self {
Self::Object(fields) => fields
.iter()
.map(|(name, value)| ((*name).to_owned(), value.clone()))
.collect(),
_ => Vec::new(),
}
}
fn truthy(&self) -> bool {
match self {
Self::Null => false,
Self::Bool(v) => *v,
Self::Number(v) => *v != 0.0 && !v.is_nan(),
Self::String(v) => !v.is_empty(),
Self::Object(_) | Self::Array(_) => true,
}
}
}
#[test]
fn backdrop_material_survives_restyling_and_resets() {
use crate::{BackdropMaterial, js::host::HostProps};
let mut c = core();
// A material alone still reaches the platform on first mount.
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::BackdropMaterial(BackdropMaterial::Regular),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.backdrop_material,
BackdropMaterial::Regular
);
// Restyling must preserve the platform prop.
c.apply(style_op(
2,
&[("backdropFilter", StyleValue::Str("blur(30px)"))],
))
.unwrap();
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.backdrop_material,
BackdropMaterial::Regular
);
for material in [
BackdropMaterial::Thin,
BackdropMaterial::Thick,
BackdropMaterial::Chrome,
] {
c.apply(Op::SetProp {
id: 2,
prop: Prop::BackdropMaterial(material),
})
.unwrap();
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.backdrop_material,
material
);
}
c.apply(Op::SetProp {
id: 2,
prop: Prop::BackdropMaterial(BackdropMaterial::Chrome),
})
.unwrap();
assert!(c.commit().is_none());
// The renderer uses the generated reset when the iOS prop is removed.
c.apply(Op::SetProp {
id: 2,
prop: Prop::BackdropMaterial(BackdropMaterial::Chrome)
.reset()
.unwrap(),
})
.unwrap();
let mounted = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(mounted.backdrop_material, BackdropMaterial::UltraThin);
assert!(!mounted.effects.unwrap().backdrop_filters.is_empty());
}
#[test]
fn zoomable_decodes_per_element() {
use crate::js::host::{HostCx, HostProps};
// Scroll views and web views share the name: each decodes it as its
// own prop.
let decode = |tag: Tag| {
let mut cx = HostCx::for_element(tag);
<Prop as HostProps>::decode("zoomable", &HostTestValue::Bool(true), &mut cx)
.expect("a zoomable prop")
.expect("a value")
};
assert_eq!(
decode(Tag::WebView),
Prop::Native(NativeProp::Zoomable(true))
);
assert_eq!(decode(Tag::Scroll), Prop::Scroll(ScrollProp::Pinch(true)));
// Cleared from JS: a web view does not zoom, a scroll view does.
assert_eq!(
Prop::Native(NativeProp::Zoomable(true)).reset(),
Some(Prop::Native(NativeProp::Zoomable(false)))
);
assert_eq!(
Prop::Scroll(ScrollProp::Pinch(false)).reset(),
Some(Prop::Scroll(ScrollProp::Pinch(true)))
);
}
#[test]
fn supported_orientations_decode_per_element() {
use crate::{
ModalConfig, ModalProp, ScreenProp,
js::host::{HostCx, HostProps},
};
// Pages and dialogs share the name: each element decodes it as its own
// prop, never the other's (a dialog's went to the page's before).
let value = HostTestValue::Array(vec![
HostTestValue::String("portrait"),
HostTestValue::String("landscape-left"),
]);
let bits = ModalConfig::PORTRAIT | ModalConfig::LANDSCAPE_LEFT;
let decode = |tag: Tag| {
let mut cx = HostCx::for_element(tag);
<Prop as HostProps>::decode("supportedOrientations", &value, &mut cx)
.expect("a supportedOrientations prop")
.expect("a value")
};
assert_eq!(
decode(Tag::Screen),
Prop::Screen(ScreenProp::Orientations(bits))
);
assert_eq!(
decode(Tag::Modal),
Prop::Modal(ModalProp::Orientations(bits))
);
// Cleared from JS, each resets to its own element's "none".
assert_eq!(
Prop::Screen(ScreenProp::Orientations(bits)).reset(),
Some(Prop::Screen(ScreenProp::Orientations(0)))
);
assert_eq!(
Prop::Modal(ModalProp::Orientations(bits)).reset(),
Some(Prop::Modal(ModalProp::Orientations(0)))
);
}
#[test]
fn macos_backdrop_decodes_and_survives_restyling() {
use crate::{
MacOsBackdrop, MacOsBackdropBlending, MacOsBackdropMaterial, MacOsBackdropState,
js::host::{HostCx, HostProps},
};
let decode = |value: HostTestValue<'_>| {
let mut cx = HostCx::for_element(Tag::View);
<Prop as HostProps>::decode("backdrop", &value, &mut cx)
.expect("a macOS backdrop prop")
.expect("a value")
};
// Its fields default to AppKit's popover material, within the window,
// active.
assert_eq!(
MacOsBackdrop::default(),
MacOsBackdrop {
material: MacOsBackdropMaterial::Popover,
blending: MacOsBackdropBlending::WithinWindow,
state: MacOsBackdropState::Active,
}
);
// Every material AppKit's roles name decodes from the API's camel case.
for (name, material) in [
("titlebar", MacOsBackdropMaterial::Titlebar),
("selection", MacOsBackdropMaterial::Selection),
("menu", MacOsBackdropMaterial::Menu),
("popover", MacOsBackdropMaterial::Popover),
("sidebar", MacOsBackdropMaterial::Sidebar),
("headerView", MacOsBackdropMaterial::HeaderView),
("sheet", MacOsBackdropMaterial::Sheet),
("windowBackground", MacOsBackdropMaterial::WindowBackground),
("hudWindow", MacOsBackdropMaterial::HudWindow),
("fullScreenUI", MacOsBackdropMaterial::FullScreenUI),
("toolTip", MacOsBackdropMaterial::ToolTip),
(
"contentBackground",
MacOsBackdropMaterial::ContentBackground,
),
(
"underWindowBackground",
MacOsBackdropMaterial::UnderWindowBackground,
),
(
"underPageBackground",
MacOsBackdropMaterial::UnderPageBackground,
),
] {
let prop = decode(HostTestValue::object([(
"material",
HostTestValue::String(name),
)]));
assert_eq!(
prop,
Prop::MacOsBackdrop(Some(MacOsBackdrop {
material,
..MacOsBackdrop::default()
})),
"{name}"
);
}
for (name, blending) in [
("withinWindow", MacOsBackdropBlending::WithinWindow),
("behindWindow", MacOsBackdropBlending::BehindWindow),
] {
let prop = decode(HostTestValue::object([(
"blending",
HostTestValue::String(name),
)]));
assert_eq!(
prop,
Prop::MacOsBackdrop(Some(MacOsBackdrop {
material: MacOsBackdropMaterial::default(),
blending,
state: MacOsBackdropState::default(),
})),
"{name}"
);
}
for (name, state) in [
(
"followsWindowActiveState",
MacOsBackdropState::FollowsWindowActiveState,
),
("active", MacOsBackdropState::Active),
("inactive", MacOsBackdropState::Inactive),
] {
let prop = decode(HostTestValue::object([(
"state",
HostTestValue::String(name),
)]));
assert_eq!(
prop,
Prop::MacOsBackdrop(Some(MacOsBackdrop {
material: MacOsBackdropMaterial::default(),
blending: MacOsBackdropBlending::default(),
state,
})),
"{name}"
);
}
// The host prop's object names AppKit's roles, blending and state.
let prop = decode(HostTestValue::object([
("material", HostTestValue::String("hudWindow")),
("blending", HostTestValue::String("behindWindow")),
("state", HostTestValue::String("followsWindowActiveState")),
]));
let backdrop = MacOsBackdrop {
material: MacOsBackdropMaterial::HudWindow,
blending: MacOsBackdropBlending::BehindWindow,
state: MacOsBackdropState::FollowsWindowActiveState,
};
assert_eq!(prop, Prop::MacOsBackdrop(Some(backdrop)));
// Left out fields take their defaults.
assert_eq!(
decode(HostTestValue::Object(Vec::new())),
Prop::MacOsBackdrop(Some(MacOsBackdrop::default()))
);
// An unknown name, the kebab case the API no longer writes included,
// and a field of another type keep the default: a prop never fails.
for value in [
HostTestValue::String("unknown"),
HostTestValue::String("hud-window"),
HostTestValue::String("behind-window"),
HostTestValue::Number(1.0),
] {
assert_eq!(
decode(HostTestValue::object([("material", value)])),
Prop::MacOsBackdrop(Some(MacOsBackdrop::default()))
);
}
// A value that is not an object clears the prop, as null does.
assert_eq!(
decode(HostTestValue::String("hudWindow")),
Prop::MacOsBackdrop(None)
);
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: prop.clone(),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.macos_backdrop,
Some(backdrop)
);
// Restyling preserves the platform prop, whether or not it has a blur.
c.apply(style_op(
2,
&[("backdropFilter", StyleValue::Str("blur(30px)"))],
))
.unwrap();
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.macos_backdrop,
Some(backdrop)
);
// A cleared key resets the prop to none.
c.apply(Op::SetProp {
id: 2,
prop: <Prop as HostProps>::reset(&prop).unwrap(),
})
.unwrap();
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.macos_backdrop,
None
);
// The host decoder's null does the same.
assert_eq!(decode(HostTestValue::Null), Prop::MacOsBackdrop(None));
}
/// `windows={{ backdrop }}` decodes its one name, reaches the view
/// style, and clears through the Windows-qualified decode key.
#[test]
fn windows_backdrop_decodes_and_clears() {
use crate::{
WindowsBackdrop, WindowsBackdropMaterial,
js::host::{HostCx, HostProps},
};
let decode = |value: HostTestValue<'_>| {
let mut cx = HostCx::for_element(Tag::View);
<Prop as HostProps>::decode("windows.backdrop", &value, &mut cx)
.expect("a Windows backdrop prop")
.expect("a value")
};
let backdrop = WindowsBackdrop {
material: WindowsBackdropMaterial::Blur,
};
let prop = decode(HostTestValue::object([(
"material",
HostTestValue::String("blur"),
)]));
assert_eq!(prop, Prop::WindowsBackdrop(Some(backdrop)));
for value in [
HostTestValue::String("blur"),
HostTestValue::Number(1.0),
HostTestValue::object([]),
HostTestValue::object([("material", HostTestValue::String("mica"))]),
HostTestValue::object([("material", HostTestValue::Number(1.0))]),
HostTestValue::object([("blending", HostTestValue::String("behindWindow"))]),
HostTestValue::Null,
] {
assert_eq!(decode(value), Prop::WindowsBackdrop(None));
}
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: prop.clone(),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.windows_backdrop,
Some(backdrop)
);
c.apply(Op::SetProp {
id: 2,
prop: <Prop as HostProps>::reset(&prop).unwrap(),
})
.unwrap();
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.windows_backdrop,
None
);
}
#[test]
fn rust_windows_backdrop_reaches_the_view_style() {
use crate::{WindowsBackdrop, element::Root, prelude::*};
#[component]
fn BackdropView() -> impl IntoElement {
view().windows_backdrop(WindowsBackdrop::default())
}
let mut c = core();
c.mount_root(&Root::new::<BackdropView>(|| ()));
let backdrops = c
.commit()
.unwrap()
.items
.into_iter()
.filter_map(|item| match item {
MountItem::ViewStyle { style, .. } => style.windows_backdrop,
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(backdrops, [WindowsBackdrop::default()]);
}
#[test]
fn glass_tint_updates_and_removal_keeps_effects() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let style = |tint: Option<&str>| {
let mut props = vec![
("backdropFilter", StyleValue::Str("blur(12px)")),
("glassEffect", StyleValue::Str("regular")),
];
if let Some(tint) = tint {
props.push(("glassTintColor", StyleValue::Str(tint)));
}
style_op(2, &props)
};
c.apply(style(Some("#ff0000"))).unwrap();
let mounted = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(mounted.glass_tint_color, Some(Color(0xff00_00ff)));
assert_eq!(mounted.glass_effect, crate::GlassEffect::Regular);
// A new color updates the native tint.
c.apply(style(Some("#00ff00"))).unwrap();
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.glass_tint_color,
Some(Color(0x00ff_00ff))
);
// The style without the key resets it; the glass and blur effects stay.
c.apply(style(None)).unwrap();
let mounted = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(mounted.glass_tint_color, None);
assert_eq!(mounted.glass_effect, crate::GlassEffect::Regular);
assert!(!mounted.effects.unwrap().backdrop_filters.is_empty());
}
#[test]
fn classes_style_views_and_inline_styles_win() {
let mut c = core();
view_with_classes(&mut c, 2, "w-20 h-10 p-2 bg-blue-500 rounded-lg");
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).unwrap().size.width.0, 80.0);
let v = view_style_of(&batch, 2).unwrap();
assert_eq!(v.background_color, Color(0x2b7f_ffff));
assert_eq!(v.border_radius, px(8.0));
// The inline style applies over the classes, and survives a class change.
c.apply(style_op(
2,
&[("backgroundColor", StyleValue::Str("#ff0000"))],
))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xff00_00ff)
);
c.apply(class_op(2, "w-24 h-10 bg-green-500")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).unwrap().size.width.0, 96.0);
let v = view_style_of(&batch, 2).unwrap();
assert_eq!(v.background_color, Color(0xff00_00ff));
assert_eq!(v.border_radius, px(0.0));
// Same classes again: nothing to do.
c.apply(class_op(2, "w-24 h-10 bg-green-500")).unwrap();
assert!(c.commit().is_none());
}
#[test]
fn important_classes_win_over_inline_styles() {
let mut c = core();
view_with_classes(
&mut c,
2,
"!bg-blue-500 translate-x-2 !scale-150 opacity-50",
);
c.apply(style_op(
2,
&[
("backgroundColor", StyleValue::Str("#ff0000")),
("opacity", StyleValue::Number(0.8)),
],
))
.unwrap();
let v = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(v.background_color, Color(0x2b7f_ffff));
// Not important: the inline style wins.
assert_eq!(v.opacity, 0.8);
// The important scale still composes with the plain translation.
let mut expected = crate::Transform::default();
let _ = expected.push(crate::TransformKind::TranslateX, 8.0);
let _ = expected.push(crate::TransformKind::Scale, 1.5);
assert_eq!(v.transform, expected);
}
#[test]
fn an_inline_flex_display_is_a_row_unless_a_direction_is_set() {
// As CSS's `display: flex` and the `flex` class: a row unless a class or
// the style itself sets a direction; a view that sets no display stays a
// column.
let second_x = |classes: &str, style: &[(&str, StyleValue<'_>)]| {
let mut c = core();
view_with_classes(&mut c, 2, classes);
c.apply(style_op(2, style)).unwrap();
for id in [4, 6] {
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::View },
style_op(
id,
&[
("width", StyleValue::Number(10.0)),
("height", StyleValue::Number(10.0)),
],
),
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
frame_of(&c.commit().unwrap(), 6).unwrap().origin.x.0
};
let flex = ("display", StyleValue::Str("flex"));
let column = ("flexDirection", StyleValue::Str("column"));
assert_eq!(second_x("", &[flex]), 10.0);
assert_eq!(second_x("items-start", &[flex]), 10.0);
assert_eq!(second_x("", &[]), 0.0);
assert_eq!(second_x("flex-col", &[flex]), 0.0);
assert_eq!(second_x("", &[column, flex]), 0.0);
assert_eq!(second_x("", &[flex, column]), 0.0);
assert_eq!(second_x("flex", &[column]), 0.0);
}
#[test]
fn inline_transform_properties_replace_only_their_own() {
// As in CSS: `scale` replaces the class's scale, `transform` its
// `transform` functions, and its translation and rotation stay.
use crate::TransformKind::*;
let mut c = core();
view_with_classes(&mut c, 2, "translate-x-2 rotate-45 scale-50 skew-x-3");
c.apply(style_op(
2,
&[
("scale", StyleValue::Number(2.0)),
("transform", StyleValue::Str("skewY(10deg)")),
],
))
.unwrap();
let v = view_style_of(&c.commit().unwrap(), 2).unwrap();
let ops: Vec<_> = v
.transform
.ops()
.iter()
.map(|o| (o.kind, o.value))
.collect();
assert_eq!(
ops,
[
(TranslateX, 8.0),
(Rotate, 45.0),
(Scale, 2.0),
(SkewY, 10.0)
]
);
}
#[test]
fn inline_styles_resolve_longhands_whatever_their_order() {
use crate::effects::Keyframes;
let mut c = core();
view_with_classes(&mut c, 2, "border-t-4 outline-2 animate-spin");
// The inline style applies over the classes: its shorthand wins over a
// class's longhand, its `none` over a class's width, its duration
// changes the class's animation.
c.apply(style_op(
2,
&[
("borderWidth", StyleValue::Number(1.0)),
("outlineStyle", StyleValue::Str("none")),
("animationDuration", StyleValue::Number(500.0)),
],
))
.unwrap();
let v = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(v.borders.widths.to_array().map(|w| w.0), [1.0; 4]);
assert!(!v.outline.is_visible());
let a = v.animation.unwrap();
assert_eq!((a.keyframes, a.duration), (Keyframes::Spin, 500.0));
// In one object the longhand wins, also when the classes change.
c.apply(style_op(
2,
&[
("borderTopWidth", StyleValue::Number(5.0)),
("borderWidth", StyleValue::Number(2.0)),
("animationIterationCount", StyleValue::Number(2.0)),
("animationName", StyleValue::Str("pulse")),
],
))
.unwrap();
let v = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(
v.borders.widths.to_array().map(|w| w.0),
[5.0, 2.0, 2.0, 2.0]
);
assert_eq!(v.outline.width, px(2.0));
c.apply(class_op(2, "border-t-8")).unwrap();
let v = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(
v.borders.widths.to_array().map(|w| w.0),
[5.0, 2.0, 2.0, 2.0]
);
assert!(!v.outline.is_visible());
let a = v.animation.unwrap();
assert_eq!((a.keyframes, a.iterations), (Keyframes::Pulse, Some(2)));
// A longhand left out: the shorthand shows again.
c.apply(style_op(2, &[("borderWidth", StyleValue::Number(2.0))]))
.unwrap();
let v = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(v.borders.widths.to_array().map(|w| w.0), [2.0; 4]);
assert_eq!(v.animation, None);
}
#[test]
fn the_apps_appearance_wins_over_the_systems() {
use crate::platform::Appearance;
let mut c = core();
view_with_classes(&mut c, 2, "bg-white dark:bg-black");
let background = |batch: &MountBatch| view_style_of(batch, 2).map(|s| s.background_color);
assert_eq!(background(&c.commit().unwrap()), Some(Color(0xffff_ffff)));
let appearance = |c: &mut Core<FakeEngine>, a| {
apply(
c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::Appearance(a),
}],
)
};
appearance(&mut c, Appearance::Dark);
let batch = c.commit().unwrap();
assert_eq!(background(&batch), Some(Color(0x0000_00ff)));
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Appearance {
appearance: Appearance::Dark
}
)));
// The system turning light changes nothing; following it again does.
c.set_class_environment(crate::tailwind::ClassEnvironment::default());
assert!(c.commit().is_none_or(|b| background(&b).is_none()));
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
appearance(&mut c, Appearance::Light);
assert_eq!(background(&c.commit().unwrap()), Some(Color(0xffff_ffff)));
appearance(&mut c, Appearance::System);
assert_eq!(background(&c.commit().unwrap()), Some(Color(0x0000_00ff)));
}
#[test]
fn pointer_and_terminal_restyle_natively() {
let mut c = core();
view_with_classes(
&mut c,
2,
"bg-white pointer-fine:bg-black terminal:bg-red-500",
);
let background = |batch: &MountBatch| view_style_of(batch, 2).map(|s| s.background_color);
assert_eq!(background(&c.commit().unwrap()), Some(Color(0xffff_ffff)));
c.set_class_environment(crate::tailwind::ClassEnvironment {
pointer: crate::tailwind::Pointer::Fine,
..Default::default()
});
assert_eq!(background(&c.commit().unwrap()), Some(Color(0x0000_00ff)));
c.set_class_environment(crate::tailwind::ClassEnvironment {
pointer: crate::tailwind::Pointer::Fine,
terminal: true,
..Default::default()
});
let red = background(&c.commit().unwrap()).unwrap();
assert_ne!(red, Color(0x0000_00ff));
}
#[test]
fn dark_mode_and_breakpoints_restyle_natively() {
let mut c = core();
view_with_classes(&mut c, 2, "bg-white dark:bg-black p-2 md:p-8");
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xffff_ffff)
);
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0x0000_00ff)
);
// A wide window crosses `md`: the padding changes, the child moves.
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("height", StyleValue::Number(5.0))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().origin.x.0, 8.0);
c.set_viewport(size_pt(1024.0, 768.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().origin.x.0, 32.0);
}
/// Under the window model the host's root view keeps its size while the
/// app's primary window is resized: width variants follow the window the
/// platform reports, as `windowSize()` does (#3526).
#[test]
fn breakpoints_follow_the_reported_window_not_the_host_root() {
let mut c = core();
view_with_classes(&mut c, 2, "p-2 max-[900px]:p-6");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("height", StyleValue::Number(5.0))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
c.set_viewport(size_pt(1200.0, 800.0));
let window = |width| crate::element::Environment {
window: size_pt(width, 600.0),
..Default::default()
};
c.set_environment(window(1100.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().origin.x.0, 8.0);
// The window narrows below 900 while the host root stays 1200 wide.
c.set_environment(window(760.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().origin.x.0, 24.0);
// And widens again.
c.set_environment(window(1136.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().origin.x.0, 8.0);
}
#[test]
fn press_and_group_states() {
let mut c = core();
view_with_classes(&mut c, 2, "group bg-white active:bg-zinc-200");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-4 opacity-100 group-active:opacity-50"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
// The platform is asked to report the group's presses.
assert!(batch.items.iter().any(|i| matches!(i, MountItem::TrackStates { id: 2, states } if states & crate::tailwind::state::PRESSED != 0)));
c.set_states(2, crate::tailwind::state::PRESSED);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xe4e4_e7ff)
);
assert_eq!(view_style_of(&batch, 3).unwrap().opacity, 0.5);
c.set_states(2, 0);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 3).unwrap().opacity, 1.0);
}
#[test]
fn a_part_shows_its_groups_press() {
use crate::tailwind::state::PRESSED;
// A switch held down: its thumb stretches (`active:w-5`) wherever the
// press went down on it; a view inside it that is no part does not.
let mut c = core();
view_with_classes(&mut c, 2, "group/held flex-row items-start");
let child = |id, classes| {
vec![
Op::Create { id, tag: Tag::View },
class_op(id, classes),
Op::Insert {
parent: 2,
child: id,
before: None,
},
]
};
let mut ops = child(3, "h-4 w-4 active:w-5 transition-all duration-200");
ops.push(Op::SetProp {
id: 3,
prop: Prop::ProjectedActive(Some("held")),
});
ops.extend(child(4, "h-4 w-4 active:w-5"));
ops.extend(child(5, "h-4 w-4 active:w-5"));
ops.push(Op::SetProp {
id: 5,
prop: Prop::ProjectedActive(Some("elsewhere")),
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().size.width.0, 16.0);
// The group's press is reported: it tracks it.
assert!(
batch.items.iter().any(
|i| matches!(i, MountItem::TrackStates { id: 2, states } if states & PRESSED != 0)
)
);
c.set_states(2, PRESSED);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().size.width.0, 20.0);
// Pushed along, their own size.
assert_eq!(frame_of(&batch, 4).unwrap().size.width.0, 16.0);
assert_eq!(frame_of(&batch, 5).unwrap().size.width.0, 16.0);
// Layout changes at once, `transition-all` or not, as for any state.
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::LayoutAnimation(_)))
);
assert_eq!(frame_of(&batch, 4).unwrap().origin.x.0, 20.0);
// Released: back to its own size.
c.set_states(2, 0);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().size.width.0, 16.0);
// No longer a part: the group's press is not its own.
apply(
&mut c,
vec![Op::SetProp {
id: 3,
prop: Prop::ProjectedActive(None),
}],
);
c.commit();
c.set_states(2, PRESSED);
let batch = c.commit();
assert!(batch.is_none_or(|b| frame_of(&b, 3).is_none()));
}
#[test]
fn a_cancelled_press_resets_active_and_drops_its_release() {
let mut c = core();
view_with_classes(&mut c, 2, "bg-white active:bg-zinc-200");
c.commit().unwrap();
c.set_states(2, crate::tailwind::state::PRESSED);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xe4e4_e7ff)
);
apply(
&mut c,
vec![Op::Command {
id: 2,
command: Command::CancelPress,
}],
);
let batch = c.commit().unwrap();
// Never reaches the platform; the active styles reset at once.
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::Command {
command: Command::CancelPress,
..
}
)));
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xffff_ffff)
);
// The platform still reporting it pressed changes nothing.
c.set_states(2, crate::tailwind::state::PRESSED);
assert!(c.commit().is_none_or(|b| view_style_of(&b, 2).is_none()));
// Its release reaches no one (JS included); the next press does.
assert!(c.component_event(2, EventKind::PressUp, &EventPayload::None));
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
assert!(!c.component_event(2, EventKind::PressDown, &EventPayload::None));
assert!(!c.component_event(2, EventKind::PressUp, &EventPayload::None));
assert!(!c.component_event(2, EventKind::Press, &EventPayload::None));
}
#[test]
fn a_press_is_cancelled_after_other_nodes_were_freed() {
let mut c = core();
// Nodes made and freed before the pressed one leave vacant keys below
// its own.
view_with_classes(&mut c, 2, "bg-white");
view_with_classes(&mut c, 4, "bg-white");
view_with_classes(&mut c, 6, "bg-white active:bg-zinc-200");
c.commit().unwrap();
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
Op::Remove {
parent: ROOT_ID,
child: 4,
},
Op::Release { id: 4 },
],
);
c.commit();
c.set_states(6, crate::tailwind::state::PRESSED);
c.commit().unwrap();
apply(
&mut c,
vec![Op::Command {
id: 6,
command: Command::CancelPress,
}],
);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 6).unwrap().background_color,
Color(0xffff_ffff)
);
}
#[test]
fn release_states_after_holds_pressed_across_touch_end_hover_and_cancellation() {
use std::time::Duration;
use crate::tailwind::{ClassEnvironment, state};
let mut c = core();
view_with_classes(&mut c, 2, "bg-white hover:opacity-90 active:bg-zinc-200");
c.commit().unwrap();
// 1. Same-turn tap on a component touch responder: `TouchPhase::Start` sets
// `hold_pressed(Some(2))` and `TouchPhase::End` clears `hold_pressed(None)`
// right before `release_states_after` schedules the 64 ms impulse.
c.set_states(2, state::PRESSED);
c.hold_pressed(Some(2));
c.hold_pressed(None);
c.release_states_after(2, 0, Duration::from_millis(64));
let due = c.next_state_timer().expect("impulse deadline scheduled");
let style = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(style.background_color, Color(0xe4e4_e7ff));
// Concurrent hover update (`Surface::revisit`) and a late `hold_pressed(None)`
// keep the `PRESSED` impulse alive while updating `HOVERED`.
c.set_states(2, state::HOVERED);
c.hold_pressed(Some(2));
c.hold_pressed(None);
assert_eq!(c.next_state_timer(), Some(due));
let style = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(style.opacity, 0.9);
assert_eq!(style.background_color, Color(0xe4e4_e7ff));
// Not expired before `due`; expires at `due`, keeping `HOVERED`.
assert!(!c.expire_state_timers(due - Duration::from_millis(1)));
assert_eq!(c.next_state_timer(), Some(due));
assert!(c.expire_state_timers(due));
assert_eq!(c.next_state_timer(), None);
let style = view_style_of(&c.commit().unwrap(), 2).unwrap();
assert_eq!(style.opacity, 0.9);
assert_eq!(style.background_color, Color(0xffff_ffff));
// 2. `Command::CancelPress` clears an active impulse immediately and rejects
// any post-cancel `release_states_after` until the next press begins.
c.set_states(2, state::HOVERED | state::PRESSED);
c.release_states_after(2, state::HOVERED, Duration::from_millis(64));
assert!(c.next_state_timer().is_some());
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.background_color,
Color(0xe4e4_e7ff)
);
apply(
&mut c,
vec![Op::Command {
id: 2,
command: Command::CancelPress,
}],
);
assert_eq!(c.next_state_timer(), None);
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.background_color,
Color(0xffff_ffff)
);
c.release_states_after(2, state::HOVERED, Duration::from_millis(64));
assert_eq!(c.next_state_timer(), None);
assert!(c.commit().is_none_or(|b| view_style_of(&b, 2).is_none()));
// Clear cancellation with a new press, then verify `reduce_motion` flushes impulses.
let _ = c.component_event(2, EventKind::PressUp, &EventPayload::None);
let _ = c.component_event(2, EventKind::Press, &EventPayload::None);
assert!(!c.component_event(2, EventKind::PressDown, &EventPayload::None));
// 3. Explicit immediate release (`Duration::ZERO`) cancels any pending
// impulse on that node and clears `PRESSED` right away.
c.set_states(2, state::PRESSED);
c.release_states_after(2, 0, Duration::from_millis(64));
assert!(c.next_state_timer().is_some());
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.background_color,
Color(0xe4e4_e7ff)
);
c.release_states_after(2, 0, Duration::ZERO);
assert_eq!(c.next_state_timer(), None);
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.background_color,
Color(0xffff_ffff)
);
// 4. `reduce_motion` flushes any active impulses immediately.
c.set_states(2, state::PRESSED);
c.release_states_after(2, 0, Duration::from_millis(64));
assert!(c.next_state_timer().is_some());
c.commit().unwrap();
c.set_class_environment(ClassEnvironment {
reduce_motion: true,
..Default::default()
});
assert_eq!(c.next_state_timer(), None);
assert_eq!(
view_style_of(&c.commit().unwrap(), 2)
.unwrap()
.background_color,
Color(0xffff_ffff)
);
}
#[test]
fn a_node_joining_a_group_in_a_state_reads_it() {
let mut c = core();
view_with_classes(&mut c, 2, "group");
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Disabled(true)),
}],
);
c.commit().unwrap();
// A row inserted into the group after it was disabled reads its state.
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-4 opacity-100 group-disabled:opacity-40"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 3).unwrap().opacity, 0.4);
// Moved out of the group, it drops it.
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
}],
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 3).unwrap().opacity, 1.0);
}
#[test]
fn untracked_states_are_forgotten() {
use crate::tailwind::state::{HOVERED, PRESSED};
// A sidebar row: `hover:` while not selected, plain once selected.
let mut c = core();
view_with_classes(&mut c, 2, "bg-white hover:bg-zinc-200");
c.commit().unwrap();
c.set_states(2, HOVERED | PRESSED);
c.commit().unwrap();
// Selected: nothing reads the states, so the platform stops reporting
// them and the pointer leaves unreported.
apply(&mut c, vec![class_op(2, "bg-zinc-500")]);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::TrackStates { id: 2, states: 0 }))
);
// Not selected again: no stale hover.
apply(&mut c, vec![class_op(2, "bg-white hover:bg-zinc-200")]);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xffff_ffff)
);
}
#[test]
fn inputs_report_their_focus_to_the_views_around_them() {
use crate::tailwind::state::FOCUSED;
// A field (`focus-within:`) around an input with no classes.
let mut c = core();
view_with_classes(&mut c, 2, "bg-white focus-within:bg-black");
add(&mut c, 4, Tag::Input, 2, &[]);
let batch = c.commit().unwrap();
// The input reports its focus all the same.
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates {
id: 4,
states: FOCUSED
}
)));
c.set_states(4, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0x0000_00ff)
);
}
#[test]
fn host_foreground_is_inherited_without_resizing_the_viewport() {
use crate::{element::AdaptiveColor, platform::Appearance};
let mut c = core();
view_with_classes(&mut c, 2, "w-full h-full");
for (id, classes) in [(3, ""), (5, "text-[#0000ff]")] {
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::Text },
class_op(id, classes),
Op::CreateText {
id: id + 1,
text: "hello".into(),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
let tokens = tokens_with(&[("foreground", AdaptiveColor::rgb(0x111111, 0xeeeeee))]);
let mut colors = [None; 2];
for (host, appearance, inherited) in [
(Some(tokens.clone()), Appearance::Light, Color(0x1111_11ff)),
(None, Appearance::Light, Color(0x0000_00ff)),
(Some(tokens.clone()), Appearance::Light, Color(0x1111_11ff)),
(Some(tokens), Appearance::Dark, Color(0xeeee_eeff)),
] {
c.set_host_tokens(host);
c.set_appearance(appearance);
let batch = c.commit().unwrap();
for item in &batch.items {
if let MountItem::Text { id, text, .. } = item
&& let Some(index) = [3, 5].iter().position(|at| at == id)
{
colors[index] = Some(text.spans[0].style.color);
}
}
assert_eq!(colors, [Some(inherited), Some(Color(0x0000_ffff))]);
assert_eq!(c.measure(2).unwrap().frame, rect(0.0, 0.0, 320.0, 480.0));
}
}
/// `overflow-hidden text-ellipsis whitespace-nowrap` is cut as `truncate`;
/// without clipping or an ellipsis set, the line overflows.
#[test]
fn a_clipped_nowrap_text_with_an_ellipsis_is_cut_at_its_box() {
// `(max_lines, no_wrap, width)` of a long text in an 80pt view.
fn laid(view: &str, text: Op) -> (u32, bool, f32) {
let mut c = Core::new(crate::ApproxTextEngine, size_pt(320.0, 480.0));
c.set_tokens(crate::element::tokens::sample());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, view),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::Text,
},
text,
Op::CreateText {
id: 4,
text: "hello world this is a long title".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
mounted_text(&batch).unwrap()
}
fn mounted_text(batch: &MountBatch) -> Option<(u32, bool, f32)> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Text {
id: 3,
text,
content,
..
} => Some((text.max_lines, text.no_wrap, content.size.width.0)),
_ => None,
})
}
let cut = (1, false, 80.0);
let truncate = laid("w-20", class_op(3, "truncate"));
assert_eq!(truncate, cut);
for classes in [
"overflow-hidden text-ellipsis whitespace-nowrap",
"overflow-hidden text-ellipsis whitespace-nowrap line-clamp-none",
] {
assert_eq!(laid("w-20", class_op(3, classes)), cut, "{classes}");
}
// `white-space` inherits; `overflow` and `text-overflow` are the text's.
assert_eq!(
laid(
"w-20 whitespace-nowrap",
class_op(3, "overflow-hidden text-ellipsis")
),
cut
);
assert_eq!(
laid(
"w-20 whitespace-nowrap",
style_op(
3,
&[
("overflow", StyleValue::Str("hidden")),
("textOverflow", StyleValue::Str("ellipsis")),
],
),
),
cut
);
for classes in [
"overflow-hidden text-clip whitespace-nowrap",
"text-ellipsis whitespace-nowrap",
"overflow-hidden whitespace-nowrap",
] {
let (max_lines, no_wrap, width) = laid("w-20", class_op(3, classes));
assert_eq!((max_lines, no_wrap), (0, true), "{classes}");
assert!(width > 80.0, "{classes}: one line past the box, {width}");
}
// Toggling the clipping updates the line.
let mut c = Core::new(crate::ApproxTextEngine, size_pt(320.0, 480.0));
c.set_tokens(crate::element::tokens::sample());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, "w-20"),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::Text,
},
class_op(3, "overflow-hidden text-ellipsis whitespace-nowrap"),
Op::CreateText {
id: 4,
text: "hello world this is a long title".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
assert_eq!(mounted_text(&c.commit().unwrap()), Some(cut));
c.apply(class_op(3, "text-ellipsis whitespace-nowrap"))
.unwrap();
let (max_lines, no_wrap, _) = mounted_text(&c.commit().unwrap()).unwrap();
assert_eq!((max_lines, no_wrap), (0, true));
c.apply(class_op(
3,
"overflow-hidden text-ellipsis whitespace-nowrap",
))
.unwrap();
assert_eq!(mounted_text(&c.commit().unwrap()), Some(cut));
}
#[test]
fn text_inherits_from_views_and_classes_set_props() {
let mut c = core();
view_with_classes(&mut c, 2, "text-white text-lg text-center");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::Text,
},
class_op(3, "line-clamp-2 font-bold"),
Op::CreateText {
id: 4,
text: "hello".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 3, text, .. } => Some(text.clone()),
_ => None,
})
.unwrap();
assert_eq!(text.spans[0].style.color, Color(0xffff_ffff));
assert_eq!(text.spans[0].style.font_size, Points(18.0));
assert_eq!(text.spans[0].style.font_weight, 700);
assert_eq!(text.align, TextAlign::Center);
assert_eq!(text.max_lines, 2);
// A container's text style change reaches the text inside.
c.apply(class_op(2, "text-black text-lg")).unwrap();
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(i, MountItem::Text { id: 3, text, .. } if text.spans[0].style.color == Color(0x0000_00ff))));
}
#[test]
fn text_indent_reaches_the_engine() {
let engine = IndentEngine::default();
let mut c = Core::new(engine.clone(), size_pt(320.0, 480.0));
c.set_tokens(crate::element::tokens::sample());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
style_op(
2,
&[
("fontSize", StyleValue::Number(20.0)),
("textIndent", StyleValue::Str("2em")),
],
),
Op::CreateText {
id: 3,
text: "hello".into(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
// `em` is of the block's font size.
assert_eq!(engine.indent.get(), Some(Some(Points(40.0))));
// A content box inherits the indent of the views around it, and a
// change of it reaches the engine again.
let engine = IndentEngine::default();
let mut c = Core::new(engine.clone(), size_pt(320.0, 480.0));
c.set_tokens(crate::element::tokens::sample());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("textIndent", StyleValue::Number(12.0))]),
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::CreateText {
id: 4,
text: "hello".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
assert_eq!(engine.indent.get(), Some(Some(Points(12.0))));
// A change of it reaches the engine again.
apply(
&mut c,
vec![style_op(2, &[("textIndent", StyleValue::Number(20.0))])],
);
c.commit().unwrap();
assert_eq!(engine.indent.get(), Some(Some(Points(20.0))));
// `em` of a font size that is itself relative: 10 × 1.5 × 2.
let engine = IndentEngine::default();
let mut c = Core::new(engine.clone(), size_pt(320.0, 480.0));
c.set_tokens(crate::element::tokens::sample());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("fontSize", StyleValue::Number(10.0))]),
Op::Create {
id: 3,
tag: Tag::Text,
},
style_op(
3,
&[
("fontSize", StyleValue::Str("1.5em")),
("textIndent", StyleValue::Str("2em")),
],
),
Op::CreateText {
id: 4,
text: "hello".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
assert_eq!(engine.indent.get(), Some(Some(Points(30.0))));
}
#[test]
fn the_approx_engine_indents_a_paragraphs_first_line() {
use crate::text::{ApproxTextEngine, TextOptions};
let engine = ApproxTextEngine;
let mut text = AttributedText::default();
text.push(
"abc",
ResolvedTextStyle {
font_size: Points(10.0),
..Default::default()
},
);
// Three characters 5.5 wide, 12 high.
let plain = engine.measure(&engine.prepare(&text), None);
assert_eq!(plain, size_pt(16.5, 12.0));
let indented = engine.prepare_with(
&text,
&Default::default(),
&TextOptions::default().indent(Points(7.0)),
);
let size = engine.measure(&indented, None);
assert!((size.width.0 - 23.5).abs() < 0.01, "{size:?}");
// The first line holds 13: two characters, and the third wraps.
let wrapped = engine.measure(&indented, Some(Points(20.0)));
assert_eq!(wrapped.height, Points(24.0));
assert!((wrapped.width.0 - 20.0).abs() < 0.01, "{wrapped:?}");
// A negative indent is no indent (`TextOptions` drops it).
let hanging = engine.prepare_with(
&text,
&Default::default(),
&TextOptions::default().indent(Points(-7.0)),
);
assert_eq!(engine.measure(&hanging, None), plain);
}
#[test]
fn texts_inherit_white_space_and_user_select_from_views() {
let mut c = core();
view_with_classes(&mut c, 2, "whitespace-nowrap select-text");
let mut ops = Vec::new();
for (id, classes) in [
(3, ""),
(5, "select-none whitespace-normal"),
(7, "select-none md:select-auto"),
] {
ops.extend([
Op::Create { id, tag: Tag::Text },
class_op(id, classes),
Op::CreateText {
id: id + 1,
text: "hello".into(),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let text = |batch: &MountBatch, id| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Text { id: i, text, .. } if *i == id => {
Some((text.no_wrap, text.selectable))
}
_ => None,
})
};
// As CSS's `white-space` and `user-select: auto`, a view's reach the
// texts in it; a text's own win.
assert_eq!(text(&batch, 3), Some((true, Some(true))));
assert_eq!(text(&batch, 5), Some((false, Some(false))));
assert_eq!(text(&batch, 7), Some((true, Some(false))));
// `select-auto` takes the view's again (the window is 320 wide; at md
// it applies).
c.set_viewport(size_pt(800.0, 480.0));
let batch = c.commit().unwrap();
assert_eq!(text(&batch, 7), Some((true, Some(true))));
// The view's change reaches them.
c.apply(class_op(2, "truncate")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(text(&batch, 3), Some((true, None)));
}
#[test]
fn selection_classes_reach_the_texts_inside() {
let mut c = core();
view_with_classes(&mut c, 2, "selection:bg-red-500");
let mut ops = Vec::new();
for (id, classes) in [(3, "select-text"), (5, "select-text selection:bg-blue-500")] {
ops.extend([
Op::Create { id, tag: Tag::Text },
class_op(id, classes),
Op::CreateText {
id: id + 1,
text: "hello".into(),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let highlight = |batch: &MountBatch, id| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Text { id: i, text, .. } if *i == id => Some(text.selection_color),
_ => None,
})
};
// Tailwind's `& *::selection`: the view's reaches the texts in it; a
// text's own wins.
assert_eq!(highlight(&batch, 3), Some(Some(Color(0xfb2c_36ff))));
assert_eq!(highlight(&batch, 5), Some(Some(Color(0x2b7f_ffff))));
c.apply(class_op(2, "")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(highlight(&batch, 3), Some(None));
}
/// A view's own selection color (Rust's `Element::selection_color`)
/// reaches the texts in it as its `selection:bg-*` class does, over that
/// class; a text's own wins, and clearing it clears theirs.
#[test]
fn a_view_selection_color_reaches_the_texts_inside() {
let mut c = core();
view_with_classes(&mut c, 2, "selection:bg-red-500");
let view_color = |color| Op::SetProp {
id: 2,
prop: Prop::SelectionColor(color),
};
let mut ops = vec![view_color(Some(Color(0x00ff_00ff)))];
for (id, classes) in [(3, "select-text"), (5, "select-text selection:bg-blue-500")] {
ops.extend([
Op::Create { id, tag: Tag::Text },
class_op(id, classes),
Op::CreateText {
id: id + 1,
text: "hello".into(),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let highlight = |batch: &MountBatch, id| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Text { id: i, text, .. } if *i == id => Some(text.selection_color),
_ => None,
})
};
assert_eq!(highlight(&batch, 3), Some(Some(Color(0x00ff_00ff))));
assert_eq!(highlight(&batch, 5), Some(Some(Color(0x2b7f_ffff))));
// Changing the view's reaches them; without it the class's is left.
c.apply(view_color(Some(Color(0x0000_ffff)))).unwrap();
let batch = c.commit().unwrap();
assert_eq!(highlight(&batch, 3), Some(Some(Color(0x0000_ffff))));
c.apply(view_color(None)).unwrap();
let batch = c.commit().unwrap();
assert_eq!(highlight(&batch, 3), Some(Some(Color(0xfb2c_36ff))));
}
#[test]
fn pointer_events_classes_inherit_as_in_css() {
use crate::props::PointerEvents as P;
let mut c = core();
// 2 none { 3 { 4 }, 5 auto { 6 } }
view_with_classes(&mut c, 2, "pointer-events-none");
let mut ops = Vec::new();
for (id, parent, classes) in [
(3, 2, "p-1"),
(4, 3, "p-1"),
(5, 2, "pointer-events-auto"),
(6, 5, "p-1"),
] {
ops.extend([
Op::Create { id, tag: Tag::View },
class_op(id, classes),
Op::Insert {
parent,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let pointer = |batch: &MountBatch, id| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: i, props } if *i == id => Some(props.pointer_events),
_ => None,
})
};
// 2 lets touches through to 5, which takes them; 3 is no target, and
// blocks 4.
assert_eq!(pointer(&batch, 2), Some(P::BoxNone));
assert_eq!(pointer(&batch, 3), Some(P::None));
assert_eq!(pointer(&batch, 4), None);
assert_eq!(pointer(&batch, 5), None);
assert_eq!(pointer(&batch, 6), None);
// Without the `auto`, 2 blocks the whole subtree.
c.apply(class_op(5, "p-1")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(pointer(&batch, 2), Some(P::None));
assert_eq!(pointer(&batch, 3), Some(P::Auto));
// An `auto` moved in brings `box-none` back; moved out, `none`.
apply(
&mut c,
vec![
Op::Create {
id: 7,
tag: Tag::View,
},
class_op(7, "pointer-events-auto"),
Op::Insert {
parent: 4,
child: 7,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(pointer(&batch, 2), Some(P::BoxNone));
assert_eq!(pointer(&batch, 3), Some(P::BoxNone));
assert_eq!(pointer(&batch, 4), Some(P::BoxNone));
assert_eq!(pointer(&batch, 5), Some(P::None));
c.apply(Op::Remove {
parent: 4,
child: 7,
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(pointer(&batch, 2), Some(P::None));
assert_eq!(pointer(&batch, 4), Some(P::Auto));
// The core's own `pointerEvents` (a tooltip's overlay) keeps React
// Native's meaning, and wins.
c.apply(Op::SetProp {
id: 2,
prop: Prop::PointerEvents(P::BoxOnly),
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(pointer(&batch, 2), Some(P::BoxOnly));
}
/// A view made in a later round than its `pointer-events` was worked out
/// (one styled before it joins the tree) still mounts it: a layer that
/// lets touches through would otherwise take them all.
#[test]
fn pointer_events_reach_a_view_made_after_they_were_worked_out() {
use crate::props::PointerEvents as P;
let mut c = core();
view_with_classes(&mut c, 2, "p-1");
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("pointerEvents", StyleValue::Str("box-none"))]),
],
);
c.commit().unwrap();
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 4,
before: None,
}],
);
let batch = c.commit().unwrap();
let pointer = batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: 4, props } => Some(props.pointer_events),
_ => None,
});
assert_eq!(pointer, Some(P::BoxNone));
}
#[test]
fn pointer_events_regions_are_worked_out_once_a_round_with_the_tree_it_left() {
use crate::props::PointerEvents as P;
let mut c = core();
// 2 none { 3, 4 auto }, 5 beside it.
view_with_classes(&mut c, 2, "pointer-events-none");
view_with_classes(&mut c, 5, "p-1");
for (id, classes) in [(3, "p-1"), (4, "pointer-events-auto")] {
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, classes),
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
let batch = c.commit().unwrap();
let pointer = |batch: &MountBatch, id| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: i, props } if *i == id => Some(props.pointer_events),
_ => None,
})
};
assert_eq!(pointer(&batch, 2), Some(P::BoxNone));
assert_eq!(pointer(&batch, 3), Some(P::None));
// In one round: 3 moves out of the region, its `auto` (4) is
// released, and many views come into the region (worked out with the
// region once).
let mut ops = vec![
Op::Remove {
parent: 2,
child: 3,
},
Op::Insert {
parent: 5,
child: 3,
before: None,
},
Op::Remove {
parent: 2,
child: 4,
},
Op::Release { id: 4 },
];
for id in (100..400).step_by(2) {
ops.extend([
Op::Create { id, tag: Tag::View },
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
// Out of the region, 3 takes touches again; without its `auto` the
// region blocks them all.
assert_eq!(pointer(&batch, 3), Some(P::Auto));
assert_eq!(pointer(&batch, 2), Some(P::None));
// A view moved within the region (out and back in, as a caret moves)
// stays blocked by it: nothing to mount, never a `none` of its own.
apply(
&mut c,
vec![
Op::Remove {
parent: 2,
child: 100,
},
Op::Insert {
parent: 2,
child: 100,
before: None,
},
],
);
if let Some(batch) = c.commit() {
assert_eq!(pointer(&batch, 100), None);
assert_eq!(pointer(&batch, 2), None);
}
// An `auto` in a newcomer lets touches through the region to it.
c.apply(class_op(398, "pointer-events-auto")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(pointer(&batch, 2), Some(P::BoxNone));
}
#[test]
fn sibling_positions() {
let mut c = core();
view_with_classes(&mut c, 2, "flex-row");
for id in 3..6 {
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, "w-2 h-2 bg-red-500 first:bg-green-500 last:bg-blue-500"),
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 3).unwrap().background_color,
Color(0x00c9_50ff)
);
assert_eq!(
view_style_of(&batch, 4).unwrap().background_color,
Color(0xfb2c_36ff)
);
assert_eq!(
view_style_of(&batch, 5).unwrap().background_color,
Color(0x2b7f_ffff)
);
// Removing the last child makes the middle one last.
c.apply(Op::Remove {
parent: 2,
child: 5,
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 4).unwrap().background_color,
Color(0x2b7f_ffff)
);
}
/// A wrapper that passes its position on (`Prop::PassPosition`, an
/// `each` row's root around a `dynamic`): its child's `first:` and
/// `last:` read the wrapper's place among the rows, not the child's
/// place as its wrapper's only child, and follow the rows as they come
/// and go.
#[test]
fn a_wrapper_passes_its_position_to_its_children() {
let mut c = core();
view_with_classes(&mut c, 2, "flex-col");
// Row `n`: wrapper `n`, its content `n + 1`.
let add_row = |c: &mut Core<FakeEngine>, row: NodeId, before: Option<NodeId>| {
apply(
c,
vec![
Op::Create {
id: row,
tag: Tag::View,
},
Op::SetProp {
id: row,
prop: Prop::PassPosition(true),
},
Op::Create {
id: row + 1,
tag: Tag::View,
},
class_op(
row + 1,
"h-2 bg-red-500 first:bg-green-500 last:bg-blue-500",
),
Op::Insert {
parent: row,
child: row + 1,
before: None,
},
Op::Insert {
parent: 2,
child: row,
before,
},
],
);
};
for row in [10, 20, 30] {
add_row(&mut c, row, None);
}
let batch = c.commit().unwrap();
let green = Color(0x00c9_50ff);
let red = Color(0xfb2c_36ff);
let blue = Color(0x2b7f_ffff);
let bg = |batch: &MountBatch, id| view_style_of(batch, id).unwrap().background_color;
assert_eq!(bg(&batch, 11), green);
assert_eq!(bg(&batch, 21), red);
assert_eq!(bg(&batch, 31), blue);
// A row added first: the old first row is in the middle now.
add_row(&mut c, 40, Some(10));
let batch = c.commit().unwrap();
assert_eq!(bg(&batch, 41), green);
assert_eq!(bg(&batch, 11), red);
// Removing the last row makes the one before it last.
c.apply(Op::Remove {
parent: 2,
child: 30,
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(bg(&batch, 21), blue);
// Without the prop, the middle row's content is its wrapper's only
// child again: first and last, and `last:` comes after `first:`.
c.apply(Op::SetProp {
id: 10,
prop: Prop::PassPosition(false),
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(bg(&batch, 11), blue);
}
/// Content given its positional classes after its rows mounted, when no
/// child read a position yet: it reads its wrapper's place, and follows
/// it when a view joins the rows that reads no position itself.
#[test]
fn content_classed_after_mounting_follows_its_wrapper() {
let mut c = core();
view_with_classes(&mut c, 2, "flex-col");
for row in [10, 20] {
apply(
&mut c,
vec![
Op::Create {
id: row,
tag: Tag::View,
},
Op::SetProp {
id: row,
prop: Prop::PassPosition(true),
},
Op::Create {
id: row + 1,
tag: Tag::View,
},
class_op(row + 1, "h-2"),
Op::Insert {
parent: row,
child: row + 1,
before: None,
},
Op::Insert {
parent: 2,
child: row,
before: None,
},
],
);
}
c.commit().unwrap();
for row in [10, 20] {
c.apply(class_op(
row + 1,
"h-2 bg-red-500 first:bg-green-500 last:bg-blue-500",
))
.unwrap();
}
let batch = c.commit().unwrap();
let bg = |batch: &MountBatch, id| view_style_of(batch, id).unwrap().background_color;
assert_eq!(bg(&batch, 11), Color(0x00c9_50ff));
assert_eq!(bg(&batch, 21), Color(0x2b7f_ffff));
// A plain view first: the first row's content is no longer first.
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-2"),
Op::Insert {
parent: 2,
child: 3,
before: Some(10),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(bg(&batch, 11), Color(0xfb2c_36ff));
}
/// Wrappers in wrappers pass the outer one's place down, and content
/// styled before its wrapper joins the rows takes the wrapper's place
/// once it does.
#[test]
fn nested_wrappers_pass_the_outer_position() {
let mut c = core();
view_with_classes(&mut c, 2, "flex-col");
let pass = |id| Op::SetProp {
id,
prop: Prop::PassPosition(true),
};
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-2"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
c.commit().unwrap();
// Outer wrapper 10, inner wrapper 11, content 12: styled while
// detached, then the outer one joins after view 3.
apply(
&mut c,
vec![
Op::Create {
id: 10,
tag: Tag::View,
},
pass(10),
Op::Create {
id: 11,
tag: Tag::View,
},
pass(11),
Op::Create {
id: 12,
tag: Tag::View,
},
class_op(12, "h-2 bg-red-500 first:bg-green-500"),
Op::Insert {
parent: 11,
child: 12,
before: None,
},
Op::Insert {
parent: 10,
child: 11,
before: None,
},
],
);
// Nothing mounted yet: the rows' styles wait.
assert!(c.commit().is_none());
c.apply(Op::Insert {
parent: 2,
child: 10,
before: None,
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 12).unwrap().background_color,
Color(0xfb2c_36ff),
"the outer wrapper is second"
);
// View 3 leaves: the outer wrapper is first.
c.apply(Op::Remove {
parent: 2,
child: 3,
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 12).unwrap().background_color,
Color(0x00c9_50ff)
);
}
#[test]
fn text_inherits_a_rows_positional_classes() {
let mut c = core();
view_with_classes(&mut c, 2, "");
let add_row = |c: &mut Core<FakeEngine>, row: NodeId| {
apply(
c,
vec![
Op::Create {
id: row,
tag: Tag::View,
},
class_op(row, "text-black last:text-white"),
Op::Create {
id: row + 1,
tag: Tag::Text,
},
Op::CreateText {
id: row + 2,
text: "label".into(),
},
Op::Insert {
parent: row + 1,
child: row + 2,
before: None,
},
Op::Insert {
parent: row,
child: row + 1,
before: None,
},
Op::Insert {
parent: 2,
child: row,
before: None,
},
],
);
};
let color = |batch: &MountBatch, id: NodeId| {
batch.items.iter().find_map(|i| match i {
MountItem::Text { id: t, text, .. } if *t == id => Some(text.spans[0].style.color),
_ => None,
})
};
add_row(&mut c, 10);
add_row(&mut c, 20);
let batch = c.commit().unwrap();
assert_eq!(color(&batch, 11), Some(Color(0x0000_00ff)));
assert_eq!(color(&batch, 21), Some(Color(0xffff_ffff)));
// A row after it: the label of the row that was last turns back.
add_row(&mut c, 30);
let batch = c.commit().unwrap();
assert_eq!(color(&batch, 21), Some(Color(0x0000_00ff)));
assert_eq!(color(&batch, 31), Some(Color(0xffff_ffff)));
}
#[test]
fn fractional_translations_follow_the_size() {
let mut c = core();
view_with_classes(&mut c, 2, "w-20 h-10 -translate-x-1/2 translate-y-full");
let batch = c.commit().unwrap();
let v = view_style_of(&batch, 2).unwrap();
let ops = v.transform.ops();
assert_eq!(
(ops[0].kind, ops[0].value),
(crate::TransformKind::TranslateX, -40.0)
);
assert_eq!(
(ops[1].kind, ops[1].value),
(crate::TransformKind::TranslateY, 40.0)
);
c.apply(class_op(2, "w-40 h-10 -translate-x-1/2 translate-y-full"))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().transform.ops()[0].value,
-80.0
);
}
#[test]
fn disabled_views_take_no_presses() {
let mut c = core();
view_with_classes(&mut c, 2, "disabled:opacity-40");
let press = |enabled| Op::Listen {
id: 2,
event: EventKind::Press,
enabled,
};
let disabled = |d| Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Disabled(d)),
};
let events_of = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Events { id: 2, events } => Some(*events),
_ => None,
})
};
apply(&mut c, vec![press(true), disabled(true)]);
let batch = c.commit().unwrap();
assert!(!events_of(&batch).unwrap().contains(EventKind::Press));
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.4);
apply(&mut c, vec![disabled(false)]);
let batch = c.commit().unwrap();
assert!(events_of(&batch).unwrap().contains(EventKind::Press));
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
}
/// A view that takes no presses unmounts its other listeners when it is
/// disabled too: a secondary click goes on to the listener around it.
#[test]
fn disabled_views_hear_no_context_menus_or_file_drops() {
let mut c = core();
view_with_classes(&mut c, 2, "disabled:opacity-40");
let disabled = |d| Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Disabled(d)),
};
let events_of = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Events { id: 2, events } => Some(*events),
_ => None,
})
};
apply(
&mut c,
[EventKind::ContextMenu, EventKind::FileDrop]
.into_iter()
.map(|event| Op::Listen {
id: 2,
event,
enabled: true,
})
.collect(),
);
let batch = c.commit().unwrap();
let events = events_of(&batch).unwrap();
assert!(events.contains(EventKind::ContextMenu) && events.contains(EventKind::FileDrop));
apply(&mut c, vec![disabled(true)]);
let batch = c.commit().unwrap();
assert!(events_of(&batch).unwrap().is_empty());
apply(&mut c, vec![disabled(false)]);
let batch = c.commit().unwrap();
let events = events_of(&batch).unwrap();
assert!(events.contains(EventKind::ContextMenu) && events.contains(EventKind::FileDrop));
}
/// A style patch of `decls` (`activeStyle={{ … }}`).
fn patch(decls: &[(&str, crate::StyleValue<'_>)]) -> Option<std::rc::Rc<crate::StylePatch>> {
let mut style = crate::Style::default();
let mut patch = crate::StylePatch::default();
for (key, value) in decls {
patch.set(&mut style, key, *value).unwrap();
}
Some(std::rc::Rc::new(patch))
}
#[test]
fn disabled_views_are_disabled_for_screen_readers() {
let mut c = core();
view_with_classes(&mut c, 2, "");
let disabled = |d| Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Disabled(d)),
};
let state_of = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: 2, props } => Some(props.accessibility.state.disabled),
_ => None,
})
};
apply(&mut c, vec![disabled(true)]);
assert_eq!(state_of(&c.commit().unwrap()), Some(true));
apply(&mut c, vec![disabled(false)]);
assert_eq!(state_of(&c.commit().unwrap()), Some(false));
// The app's own state stays when `disabled` is off.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
disabled: true,
..Default::default()
})),
}],
);
assert_eq!(state_of(&c.commit().unwrap()), Some(true));
}
#[test]
fn active_style_applies_while_pressed_and_not_disabled() {
use crate::{StyleValue as V, tailwind::state};
let mut c = core();
view_with_classes(&mut c, 2, "bg-white");
apply(
&mut c,
vec![
// The inline style is under it.
Op::SetStyle {
id: 2,
style: Box::default(),
patch: {
let mut s = crate::Style::default();
let mut p = crate::StylePatch::default();
p.set(&mut s, "opacity", V::Number(0.9)).unwrap();
p
},
},
Op::SetProp {
id: 2,
prop: Prop::ActiveStyle(patch(&[
("backgroundColor", V::Str("#dddddd")),
("opacity", V::Number(0.5)),
])),
},
Op::SetProp {
id: 2,
prop: Prop::DisabledStyle(patch(&[("opacity", V::Number(0.3))])),
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates { id: 2, states } if *states == state::PRESSED
)));
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.9);
c.set_states(2, state::PRESSED);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, 2).unwrap();
assert_eq!(style.background_color, Color(0xdddd_ddff));
assert_eq!(style.opacity, 0.5);
c.set_states(2, 0);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, 2).unwrap();
assert_eq!(style.background_color, Color(0xffff_ffff));
assert_eq!(style.opacity, 0.9);
// Disabled: no active style, the disabled one.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Disabled(true)),
}],
);
c.set_states(2, state::PRESSED);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, 2).unwrap();
assert_eq!(style.background_color, Color(0xffff_ffff));
assert_eq!(style.opacity, 0.3);
// Removed: the classes alone.
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Disabled(false)),
},
Op::SetProp {
id: 2,
prop: Prop::ActiveStyle(None),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xffff_ffff)
);
}
#[test]
fn selected_style_follows_the_accessibility_state() {
use crate::{AccessibilityProp, AccessibilityState, StyleValue as V};
let mut c = core();
view_with_classes(&mut c, 2, "bg-white selected:bg-black");
let selected = |on| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
selected: on,
..AccessibilityState::default()
})),
};
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::SelectedStyle(patch(&[("opacity", V::Number(0.7))])),
},
selected(true),
],
);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, 2).unwrap();
assert_eq!(style.background_color, Color(0x0000_00ff));
assert_eq!(style.opacity, 0.7);
// The platform never tracks it.
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::TrackStates { .. }))
);
apply(&mut c, vec![selected(false)]);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, 2).unwrap();
assert_eq!(style.background_color, Color(0xffff_ffff));
assert_eq!(style.opacity, 1.0);
}
#[test]
fn expanded_style_follows_the_accessibility_state() {
use crate::{AccessibilityProp, AccessibilityState, StyleValue as V};
// A popover's trigger: styled while its popup is open, its chevron by
// its group's state.
let mut c = core();
view_with_classes(&mut c, 2, "group bg-zinc-200 aria-expanded:bg-emerald-500");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-4 w-4 group-aria-expanded:translate-x-4"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let state = |expanded| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
expanded,
..AccessibilityState::default()
})),
};
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::ExpandedStyle(patch(&[("opacity", V::Number(0.7))])),
},
state(Some(true)),
],
);
let batch = c.commit().unwrap();
let trigger = view_style_of(&batch, 2).unwrap();
assert_eq!(trigger.background_color, Color(0x00bc_7dff));
assert_eq!(trigger.opacity, 0.7);
assert_eq!(
view_style_of(&batch, 3).unwrap().transform.ops()[0].value,
16.0
);
// The platform never tracks it.
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates { id: 2, states } if states & crate::tailwind::state::EXPANDED != 0
)));
// Collapsed (`Some(false)`) is not expanded.
apply(&mut c, vec![state(Some(false))]);
let batch = c.commit().unwrap();
let trigger = view_style_of(&batch, 2).unwrap();
assert_eq!(trigger.background_color, Color(0xe4e4_e7ff));
assert_eq!(trigger.opacity, 1.0);
assert!(view_style_of(&batch, 3).unwrap().transform.ops().is_empty());
}
#[test]
fn pressed_style_and_aria_variants_follow_the_accessibility_state() {
use crate::{AccessibilityProp, AccessibilityState, Checked, StyleValue as V};
// A toggle button: styled while on, its icon by its group's state;
// `aria-busy:`, `aria-checked:` and `aria-selected:` as Tailwind has
// them.
let mut c = core();
view_with_classes(
&mut c,
2,
"group bg-zinc-200 aria-pressed:bg-emerald-500 aria-busy:rounded-[1px] \
aria-checked:rounded-[2px] aria-selected:rounded-[3px]",
);
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-4 w-4 group-aria-pressed:translate-x-4"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::SetProp {
id: 2,
prop: Prop::PressedStyle(patch(&[("opacity", V::Number(0.7))])),
},
],
);
let state = |s: AccessibilityState| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(s)),
};
let pressed = |pressed| AccessibilityState {
pressed,
..AccessibilityState::default()
};
apply(&mut c, vec![state(pressed(Some(Checked::True)))]);
let batch = c.commit().unwrap();
let toggle = view_style_of(&batch, 2).unwrap();
assert_eq!(toggle.background_color, Color(0x00bc_7dff));
assert_eq!(toggle.opacity, 0.7);
assert_eq!(
view_style_of(&batch, 3).unwrap().transform.ops()[0].value,
16.0
);
// The platform never tracks it.
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates { id: 2, states }
if states & crate::tailwind::state::ACCESSIBILITY != 0
)));
// Mixed is not pressed, nor is off.
for off in [Some(Checked::Mixed), Some(Checked::False), None] {
apply(&mut c, vec![state(pressed(off))]);
let batch = c.commit().unwrap();
let toggle = view_style_of(&batch, 2).unwrap();
assert_eq!(toggle.background_color, Color(0xe4e4_e7ff), "{off:?}");
assert_eq!(toggle.opacity, 1.0, "{off:?}");
apply(&mut c, vec![state(pressed(Some(Checked::True)))]);
c.commit().unwrap();
}
// The `aria-*` variants of the other states, later ones winning.
for (s, radius) in [
(
AccessibilityState {
busy: true,
..AccessibilityState::default()
},
1.0,
),
(
AccessibilityState {
busy: true,
checked: Some(Checked::True),
..AccessibilityState::default()
},
2.0,
),
(
AccessibilityState {
busy: true,
checked: Some(Checked::True),
selected: true,
..AccessibilityState::default()
},
3.0,
),
// `aria-checked:` is `checked` true, never mixed.
(
AccessibilityState {
checked: Some(Checked::Mixed),
..AccessibilityState::default()
},
0.0,
),
] {
apply(&mut c, vec![state(s)]);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, 2).expect("restyled");
assert_eq!(style.border_radius, px(radius), "{s:?}");
}
}
/// `accessibilityState.invalid` from its JS shape: only `true` marks the
/// content invalid.
#[test]
fn invalid_decodes_from_js() {
use crate::{
AccessibilityProp,
js::host::{HostCx, HostProps},
};
let invalid = |v: serde_json::Value| match AccessibilityProp::decode(
"accessibilityState",
&J(v),
&mut HostCx::default(),
)
.expect("accessibilityState")
.expect("a value")
{
AccessibilityProp::State(s) => s.invalid,
p => panic!("{p:?}"),
};
assert!(invalid(serde_json::json!({ "invalid": true })));
assert!(!invalid(serde_json::json!({ "invalid": false })));
assert!(!invalid(serde_json::json!({})));
assert!(!invalid(serde_json::json!({ "invalid": "yes" })));
}
/// An invalid field takes its `aria-invalid:` classes, as Tailwind's
/// `&[aria-invalid="true"]`, while its accessibility state says so; the
/// core sets the state, the platform never reports it.
#[test]
fn aria_invalid_classes_follow_the_accessibility_state() {
use crate::{AccessibilityProp, AccessibilityState};
let mut c = core();
view_with_classes(&mut c, 2, "bg-white aria-invalid:bg-black");
let state = |invalid| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(AccessibilityState {
invalid,
..AccessibilityState::default()
})),
};
apply(&mut c, vec![state(true)]);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0x0000_00ff)
);
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates { id: 2, states }
if states & crate::tailwind::state::INVALID != 0
)));
apply(&mut c, vec![state(false)]);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xffff_ffff)
);
}
/// The accessibility state's new members and `accessibilityLevel`, from
/// their JS shapes.
#[test]
fn pressed_current_and_level_decode_from_js() {
use crate::{
AccessibilityCurrent, AccessibilityProp, Checked,
js::host::{HostCx, HostProps},
};
let decode = |name: &str, v: serde_json::Value| {
AccessibilityProp::decode(name, &J(v), &mut HostCx::default())
.expect(name)
.expect("a value")
};
let state = |v| match decode("accessibilityState", v) {
AccessibilityProp::State(s) => s,
p => panic!("{p:?}"),
};
let s = state(serde_json::json!({ "pressed": true, "current": "page" }));
assert_eq!(s.pressed, Some(Checked::True));
assert_eq!(s.current, Some(AccessibilityCurrent::Page));
let s = state(serde_json::json!({ "pressed": "mixed", "current": true }));
assert_eq!(s.pressed, Some(Checked::Mixed));
assert_eq!(s.current, Some(AccessibilityCurrent::True));
let s = state(serde_json::json!({ "pressed": false, "current": false }));
assert_eq!(s.pressed, Some(Checked::False));
assert_eq!(s.current, None);
for (word, current) in [
("step", AccessibilityCurrent::Step),
("location", AccessibilityCurrent::Location),
("date", AccessibilityCurrent::Date),
("time", AccessibilityCurrent::Time),
] {
let s = state(serde_json::json!({ "current": word }));
assert_eq!(s.current, Some(current));
}
let s = state(serde_json::json!({ "pressed": "yes", "current": "now" }));
assert_eq!((s.pressed, s.current), (None, None));
for (v, level) in [
(serde_json::json!(2), Some(2)),
(serde_json::json!(1), Some(1)),
(serde_json::json!(0), None),
(serde_json::json!(-1), None),
(serde_json::json!(1.5), None),
(serde_json::json!("2"), None),
] {
assert_eq!(
decode("accessibilityLevel", v.clone()),
AccessibilityProp::Level(level),
"{v}"
);
}
let role = |name: &str| match decode("role", serde_json::json!(name)) {
AccessibilityProp::Role(r) => r,
p => panic!("{p:?}"),
};
use crate::AccessibilityRole as R;
for (name, r) in [
("textbox", R::Textbox),
("group", R::Group),
("region", R::Region),
("navigation", R::Navigation),
("tree", R::Tree),
("treeitem", R::TreeItem),
("menuitemcheckbox", R::MenuItemCheckbox),
("menuitemradio", R::MenuItemRadio),
("dialog", R::Dialog),
("alertdialog", R::AlertDialog),
("tabpanel", R::TabPanel),
] {
assert_eq!(role(name), r);
}
}
/// `accessibilityLiveRegion` from its JS shape, on every platform now that
/// it is one prop (Android's bag took it before).
#[test]
fn a_live_region_decodes_from_js() {
use crate::{
AccessibilityProp, LiveRegion,
js::host::{HostCx, HostProps},
};
let decode = |v: serde_json::Value| {
AccessibilityProp::decode("accessibilityLiveRegion", &J(v), &mut HostCx::default())
.expect("accessibilityLiveRegion")
.expect("a value")
};
assert_eq!(
decode(serde_json::json!("polite")),
AccessibilityProp::LiveRegion(LiveRegion::Polite)
);
assert_eq!(
decode(serde_json::json!("assertive")),
AccessibilityProp::LiveRegion(LiveRegion::Assertive)
);
assert_eq!(
decode(serde_json::json!("none")),
AccessibilityProp::LiveRegion(LiveRegion::None)
);
assert_eq!(
decode(serde_json::Value::Null),
AccessibilityProp::LiveRegion(LiveRegion::None)
);
assert_eq!(
decode(serde_json::json!("yes")),
AccessibilityProp::LiveRegion(LiveRegion::None)
);
}
/// `accessibilityDescription` from JS, and what platforms with one place
/// for everything read after the name get from it.
#[test]
fn a_description_decodes_and_joins_the_hint() {
use crate::{
Accessibility, AccessibilityProp,
js::host::{HostCx, HostProps},
};
let decode = |v: serde_json::Value| {
AccessibilityProp::decode("accessibilityDescription", &J(v), &mut HostCx::default())
.expect("decodes")
.expect("a value")
};
assert_eq!(
decode(serde_json::json!("This can't be undone.")),
AccessibilityProp::Description(Some("This can't be undone.".into()))
);
assert_eq!(
decode(serde_json::Value::Null),
AccessibilityProp::Description(None)
);
let mut a = Accessibility::default();
assert_eq!(a.help_text(None), None);
a.description = Some("The whole album".into());
assert_eq!(a.help_text(None).as_deref(), Some("The whole album"));
a.hint = Some("Plays it".into());
assert_eq!(
a.help_text(None).as_deref(),
Some("The whole album. Plays it")
);
assert_eq!(
a.help_text(Some("3 of 10")).as_deref(),
Some("3 of 10. The whole album. Plays it")
);
// An empty one adds nothing.
a.description = Some("".into());
assert_eq!(a.help_text(None).as_deref(), Some("Plays it"));
// A part that ends its sentence keeps its own mark, not a second one.
a.description = Some("This can't be undone.".into());
a.hint = Some("Opens it".into());
assert_eq!(
a.help_text(None).as_deref(),
Some("This can't be undone. Opens it")
);
a.description = Some("Really?".into());
assert_eq!(a.help_text(None).as_deref(), Some("Really? Opens it"));
// Full-width marks take no space after them.
a.description = Some("此操作无法撤销。".into());
a.hint = Some("打开它".into());
assert_eq!(a.help_text(None).as_deref(), Some("此操作无法撤销。打开它"));
a.description = Some("确定删除吗?".into());
assert_eq!(a.help_text(None).as_deref(), Some("确定删除吗?打开它"));
}
/// The new accessibility props go with the view's props, and nothing is
/// sent for a view that sets none of them.
#[test]
fn level_and_new_states_go_with_the_view_props() {
use crate::{AccessibilityCurrent, AccessibilityProp, AccessibilityState};
let mut c = core();
view_with_classes(&mut c, 2, "aria-pressed:bg-black");
let batch = c.commit().unwrap();
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::ViewProps { id: 2, .. })),
"{:?}",
batch.items
);
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::Level(Some(3))),
},
Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
current: Some(AccessibilityCurrent::Step),
..AccessibilityState::default()
})),
},
],
);
let batch = c.commit().unwrap();
let props: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ViewProps { id: 2, props } => Some(props),
_ => None,
})
.collect();
assert_eq!(props.len(), 1, "{:?}", batch.items);
assert_eq!(props[0].accessibility.level, Some(3));
assert_eq!(
props[0].accessibility.state.current,
Some(AccessibilityCurrent::Step)
);
// A current item changes no style: nothing restyles.
assert!(view_style_of(&batch, 2).is_none(), "{:?}", batch.items);
}
#[test]
fn checked_style_follows_the_accessibility_state() {
use crate::{AccessibilityProp, AccessibilityState, Checked, StyleValue as V};
// A switch: the track by its checked state, the thumb by its group's.
let mut c = core();
view_with_classes(
&mut c,
2,
"group bg-zinc-200 checked:bg-emerald-500 selected:opacity-50",
);
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-4 w-4 group-checked:translate-x-4"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let state = |checked, selected| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
checked,
selected,
..AccessibilityState::default()
})),
};
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::CheckedStyle(patch(&[("opacity", V::Number(0.7))])),
},
state(Some(Checked::True), false),
],
);
let batch = c.commit().unwrap();
let track = view_style_of(&batch, 2).unwrap();
assert_eq!(track.background_color, Color(0x00bc_7dff));
assert_eq!(track.opacity, 0.7);
assert_eq!(
view_style_of(&batch, 3).unwrap().transform.ops()[0].value,
16.0
);
// The platform never tracks it.
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates { id: 2, states } if states & crate::tailwind::state::CHECKED != 0
)));
// Mixed is not checked; selected changing with it is applied too.
apply(&mut c, vec![state(Some(Checked::Mixed), true)]);
let batch = c.commit().unwrap();
let track = view_style_of(&batch, 2).unwrap();
assert_eq!(track.background_color, Color(0xe4e4_e7ff));
assert_eq!(track.opacity, 0.5);
assert!(view_style_of(&batch, 3).unwrap().transform.ops().is_empty());
}
#[test]
fn indeterminate_style_follows_the_accessibility_state() {
use crate::{AccessibilityProp, AccessibilityState, Checked, StyleValue as V};
// A checkbox: the box by its mixed state, the mark by its group's.
let mut c = core();
view_with_classes(
&mut c,
2,
"group bg-zinc-200 checked:bg-emerald-500 indeterminate:bg-black",
);
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-4 w-4 group-indeterminate:opacity-50"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
let state = |checked| Op::SetProp {
id: 2,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
checked,
..AccessibilityState::default()
})),
};
apply(
&mut c,
vec![
Op::SetProp {
id: 2,
prop: Prop::IndeterminateStyle(patch(&[("opacity", V::Number(0.7))])),
},
state(Some(Checked::Mixed)),
],
);
let batch = c.commit().unwrap();
let mixed = view_style_of(&batch, 2).unwrap();
assert_eq!(mixed.background_color, Color(0x0000_00ff));
assert_eq!(mixed.opacity, 0.7);
assert_eq!(view_style_of(&batch, 3).unwrap().opacity, 0.5);
// The platform never tracks it.
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates { id: 2, states }
if states & crate::tailwind::state::INDETERMINATE != 0
)));
// Checked is not indeterminate.
apply(&mut c, vec![state(Some(Checked::True))]);
let batch = c.commit().unwrap();
let checked = view_style_of(&batch, 2).unwrap();
assert_eq!(checked.background_color, Color(0x00bc_7dff));
assert_eq!(checked.opacity, 1.0);
assert_eq!(view_style_of(&batch, 3).unwrap().opacity, 1.0);
}
#[test]
fn projected_states_style_a_part_without_its_accessibility() {
use crate::tailwind::state;
// A switch's thumb: styled by the switch's value and disabled state,
// with no accessibility state or listeners of its own.
let mut c = core();
view_with_classes(
&mut c,
2,
"h-4 w-4 checked:translate-x-4 disabled:opacity-50",
);
let projected = |states| Op::SetProp {
id: 2,
prop: Prop::ProjectedStates(states),
};
apply(&mut c, vec![projected(state::CHECKED | state::DISABLED)]);
let batch = c.commit().unwrap();
let thumb = view_style_of(&batch, 2).unwrap();
assert_eq!(thumb.transform.ops()[0].value, 16.0);
assert_eq!(thumb.opacity, 0.5);
assert!(
!batch.items.iter().any(|i| matches!(
i,
MountItem::ViewProps { id: 2, .. } | MountItem::Events { id: 2, .. }
)),
"{:?}",
batch.items
);
apply(&mut c, vec![projected(0)]);
let batch = c.commit().unwrap();
let thumb = view_style_of(&batch, 2).unwrap();
assert!(thumb.transform.ops().is_empty());
assert_eq!(thumb.opacity, 1.0);
}
#[test]
fn projected_data_attributes_style_a_part_and_the_group_inside_it() {
// A calendar's day at the start of a range: its own `data-*:` classes,
// and its content's `group-data-*:` ones.
let mut c = core();
view_with_classes(
&mut c,
2,
"group bg-white data-range-start:bg-black data-range-start:data-range-end:opacity-50",
);
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-4 w-4 group-data-range-start:translate-x-4"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
c.commit();
let data = |names: &[&'static str]| Op::SetProp {
id: 2,
prop: Prop::ProjectedData(names.into()),
};
apply(&mut c, vec![data(&["range-start"])]);
let batch = c.commit().unwrap();
let day = view_style_of(&batch, 2).unwrap();
assert_eq!(day.background_color, Color(0x0000_00ff));
assert_eq!(day.opacity, 1.0);
assert_eq!(
view_style_of(&batch, 3).unwrap().transform.ops()[0].value,
16.0
);
// Nothing for screen readers or listeners.
assert!(
!batch.items.iter().any(|i| matches!(
i,
MountItem::ViewProps { .. } | MountItem::Events { .. } | MountItem::TrackStates { .. }
)),
"{:?}",
batch.items
);
// Both: the rule needing both applies.
apply(&mut c, vec![data(&["range-end", "range-start"])]);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
// None: back to its own, and the content's.
apply(&mut c, vec![data(&[])]);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0xffff_ffff)
);
assert!(view_style_of(&batch, 3).unwrap().transform.ops().is_empty());
}
#[test]
fn projected_data_attributes_no_class_reads_send_nothing() {
// A view whose classes read no attribute (and that is no group), and
// one without classes: their attributes change nothing on screen.
let mut c = core();
view_with_classes(&mut c, 2, "bg-white hover:bg-black");
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
c.commit();
for names in [&["range-start"][..], &["range-start", "today"], &[]] {
apply(
&mut c,
[2, 4]
.map(|id| Op::SetProp {
id,
prop: Prop::ProjectedData(names.into()),
})
.into(),
);
let items = c.commit().map(|b| b.items).unwrap_or_default();
assert!(items.is_empty(), "{names:?}: {items:?}");
}
}
#[test]
fn a_projected_focus_styles_a_part_as_focused() {
use crate::tailwind::state;
// A one-time-code input's cell: `focus:` while it takes the next
// character, though the focus is the input's.
let mut c = core();
view_with_classes(&mut c, 2, "opacity-50 focus:opacity-100");
c.commit();
let projected = |states| Op::SetProp {
id: 2,
prop: Prop::ProjectedStates(states),
};
apply(&mut c, vec![projected(state::FOCUSED)]);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::ViewProps { id: 2, .. })),
"{:?}",
batch.items
);
apply(&mut c, vec![projected(0)]);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
}
#[test]
fn projected_states_are_mounted_only_for_a_platform_that_asks() {
use crate::tailwind::state;
let projected = |id, states| Op::SetProp {
id,
prop: Prop::ProjectedStates(states),
};
let sent = |items: &[MountItem]| {
items
.iter()
.filter_map(|i| match i {
MountItem::ProjectStates { id, states } => Some((*id, *states)),
_ => None,
})
.collect::<Vec<_>>()
};
// Elsewhere the classes show them and nothing more is sent.
let mut c = core();
view_with_classes(&mut c, 2, "focus:opacity-50");
c.commit();
apply(&mut c, vec![projected(2, state::FOCUSED)]);
let items = c.commit().map(|b| b.items).unwrap_or_default();
assert_eq!(sent(&items), []);
// A terminal marks a list's highlighted option itself.
let mut c = core();
c.set_projected_state_mounting(true);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
projected(2, state::FOCUSED),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let items = c.commit().unwrap().items;
let create = items
.iter()
.position(|i| matches!(i, MountItem::Create { id: 2, .. }))
.unwrap();
let shown = items
.iter()
.position(|i| matches!(i, MountItem::ProjectStates { id: 2, .. }))
.unwrap();
assert!(create < shown, "{items:?}");
assert_eq!(sent(&items), [(2, state::FOCUSED)]);
apply(&mut c, vec![projected(2, 0)]);
let items = c.commit().unwrap().items;
assert_eq!(sent(&items), [(2, 0)]);
// An unchanged value sends nothing.
apply(&mut c, vec![projected(2, 0)]);
let items = c.commit().map(|b| b.items).unwrap_or_default();
assert_eq!(sent(&items), []);
}
/// A view and the views inside it, `id`'s first: (id, parent, classes).
fn views(c: &mut Core<FakeEngine>, views: &[(NodeId, NodeId, &str)]) {
let mut ops = Vec::new();
for &(id, parent, classes) in views {
ops.push(Op::Create { id, tag: Tag::View });
if !classes.is_empty() {
ops.push(class_op(id, classes));
}
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
apply(c, ops);
}
#[test]
fn focus_within_follows_a_focus_nothing_tracks() {
use crate::tailwind::state::FOCUSED;
// A field's frame (2) ringed while the input in it (6, in 4) edits:
// the input reads no state of its own.
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50 focus-within:opacity-100"),
(4, 2, ""),
(6, 4, ""),
],
);
let batch = c.commit().unwrap();
// `focus-within` is the core's: the platform tracks nothing for it.
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::TrackStates { .. })),
"{:?}",
batch.items
);
c.set_states(6, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
assert!(c.has_focus_within(4) && c.has_focus_within(6) && c.has_focus_within(ROOT_ID));
c.set_states(6, 0);
// A lone blur lets go at the frame.
c.run_frame(crate::time::now());
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
assert!(!c.has_focus_within(2) && !c.has_focus_within(ROOT_ID));
}
#[test]
fn focus_within_follows_an_input_without_focus_classes() {
use crate::tailwind::state::FOCUSED;
// A field's frame around an input whose classes read no state: the
// platform reports the input's focus all the same.
let mut c = core();
views(
&mut c,
&[(2, ROOT_ID, "opacity-50 focus-within:opacity-100")],
);
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::Input,
},
class_op(4, "h-8 border"),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::TrackStates { .. })),
"{:?}",
batch.items
);
c.set_states(4, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
// Only the frame changes: the input reads no state.
assert!(view_style_of(&batch, 4).is_none(), "{:?}", batch.items);
c.set_states(4, 0);
// A lone blur lets go at the frame.
c.run_frame(crate::time::now());
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
}
#[test]
fn a_focus_nothing_reads_sends_nothing() {
use crate::tailwind::state::FOCUSED;
// Regression guard of reporting the focus untracked: views whose
// classes read no state (no `focus:`, no `focus-within:`) look and
// mount as before, whatever focus the platform reports.
let mut c = core();
views(
&mut c,
&[(2, ROOT_ID, "p-2 bg-white"), (4, 2, "h-8"), (6, 2, "")],
);
c.commit();
c.set_states(4, FOCUSED);
assert!(c.commit().is_none());
c.set_states(6, FOCUSED);
c.set_states(4, 0);
assert!(c.commit().is_none());
c.set_states(6, 0);
assert!(c.commit().is_none());
}
/// The items each step of Tab sends, through `n` focusable views in a
/// frame that reads `focus-within:`: the focus coming in, then moving
/// from view to view (the new one's focus reported first, then the old
/// one's blur), then reported again where it is.
fn tab_steps(n: usize) -> Vec<usize> {
use crate::tailwind::state::FOCUSED;
let mut c = core();
let ids: Vec<NodeId> = (0..n as NodeId).map(|i| 4 + 2 * i).collect();
let mut tree = vec![(2, ROOT_ID, "opacity-50 focus-within:opacity-100")];
tree.extend(ids.iter().map(|&id| (id, 2, "h-8")));
views(&mut c, &tree);
c.commit();
let mut steps = Vec::new();
let count = |c: &mut Core<FakeEngine>| c.commit().map_or(0, |b| b.items.len());
c.set_states(ids[0], FOCUSED);
steps.push(count(&mut c));
for pair in ids.windows(2) {
c.set_states(pair[1], FOCUSED);
c.set_states(pair[0], 0);
steps.push(count(&mut c));
}
c.set_states(ids[n - 1], FOCUSED);
steps.push(count(&mut c));
steps
}
#[test]
fn tab_costs_the_same_whatever_number_of_views() {
let (ten, hundred) = (tab_steps(10), tab_steps(100));
// Coming in restyles the frame, and only it.
assert!(ten[0] > 0);
assert_eq!(hundred[0], ten[0]);
// Moving inside and the same focus again send nothing.
assert!(ten[1..].iter().all(|&n| n == 0), "{ten:?}");
assert!(hundred[1..].iter().all(|&n| n == 0), "{hundred:?}");
}
#[test]
fn a_focus_moving_inside_keeps_focus_within_in_either_order() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50 focus-within:opacity-100"),
(4, 2, ""),
(6, 2, ""),
(8, ROOT_ID, ""),
],
);
c.commit();
c.set_states(4, FOCUSED);
c.commit();
// Regression: the new view's focus reported before the old one's blur
// took `focus-within` off the views both share.
c.set_states(6, FOCUSED);
c.set_states(4, 0);
assert!(
c.commit().is_none(),
"the frame keeps its look, nothing sent"
);
assert!(c.has_focus_within(2) && c.has_focus_within(6) && !c.has_focus_within(4));
// The blur reported first: no flash of the frame either.
c.set_states(6, 0);
c.set_states(4, FOCUSED);
assert!(
c.commit().is_none(),
"the frame keeps its look, nothing sent"
);
assert!(c.has_focus_within(2) && c.has_focus_within(4) && !c.has_focus_within(6));
// Out, the blur reported first.
c.set_states(4, 0);
c.set_states(8, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
assert!(c.has_focus_within(8) && !c.has_focus_within(2));
// A blur of a view that no longer has the focus changes nothing.
c.set_states(4, FOCUSED);
c.set_states(8, 0);
c.set_states(8, FOCUSED);
c.set_states(4, 0);
c.commit();
assert!(c.has_focus_within(8) && !c.has_focus_within(2));
// The root taking it (no view has it) is no focus.
c.set_states(ROOT_ID, FOCUSED);
c.set_states(8, 0);
c.commit();
assert!(!c.has_focus_within(ROOT_ID));
}
#[test]
fn a_blur_waits_for_the_frame_before_the_focus_leaves() {
use crate::tailwind::state::FOCUSED;
// Regression (#1188): a move reported as a blur then a focus in two
// messages, with a commit between them (AppKit resigns the first
// responder before the next one becomes it), left the frame for one
// commit and came back.
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50 focus-within:opacity-100"),
(4, 2, ""),
(6, 2, ""),
],
);
c.commit();
c.set_states(4, FOCUSED);
c.commit();
c.set_states(4, 0);
assert!(c.commit().is_none(), "the blur waits for the frame");
assert!(c.wants_frame());
assert!(c.has_focus_within(2));
c.set_states(6, FOCUSED);
assert!(c.commit().is_none(), "one move inside, nothing sent");
assert!(c.has_focus_within(2) && c.has_focus_within(6) && !c.has_focus_within(4));
assert!(!c.wants_frame());
// A blur no focus follows lets go at the frame.
c.set_states(6, 0);
assert!(c.commit().is_none());
c.run_frame(crate::time::now());
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
assert!(!c.has_focus_within(2) && !c.wants_frame());
}
#[test]
fn an_overlays_content_is_within_the_view_it_is_in() {
use crate::tailwind::state::FOCUSED;
// Regression: a popup's trigger (4) and the popup (an overlay in the
// same view), whose native view is in the root view: the focus in the
// popup was not within the view holding the trigger.
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50 focus-within:opacity-100"),
(4, 2, ""),
],
);
apply(
&mut c,
vec![
Op::Create {
id: 6,
tag: Tag::Overlay,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
],
);
views(&mut c, &[(8, 6, "")]);
let batch = c.commit().unwrap();
assert!(
inserts(&batch).contains(&(ROOT_ID, 6, None)),
"shown in the root view"
);
c.set_states(8, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
// From the popup to the trigger: still within, nothing sent.
c.set_states(4, FOCUSED);
c.set_states(8, 0);
assert!(c.commit().is_none());
assert!(c.has_focus_within(2) && !c.has_focus_within(6));
}
#[test]
fn focus_within_leaves_with_a_view_moved_or_released() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50 focus-within:opacity-100"),
(4, 2, ""),
(6, 4, ""),
(8, ROOT_ID, ""),
],
);
c.commit();
c.set_states(6, FOCUSED);
c.commit();
// The focused view's parent moves out: the focus goes with it.
apply(
&mut c,
vec![Op::Insert {
parent: 8,
child: 4,
before: None,
}],
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
assert!(c.has_focus_within(8));
// And back.
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 4,
before: None,
}],
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
assert!(!c.has_focus_within(8));
// Released around the focus (the children are released by ops of
// their own, later): nothing is within any more.
apply(&mut c, vec![Op::Release { id: 4 }]);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
assert!(!c.has_focus_within(ROOT_ID));
apply(&mut c, vec![Op::Release { id: 6 }]);
c.commit();
assert!(c.focus.is_none() && c.focus_chain.is_empty());
}
#[test]
fn a_focus_within_style_applies_while_the_focus_is_inside() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
views(&mut c, &[(2, ROOT_ID, "opacity-50"), (4, 2, "")]);
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::FocusWithinStyle(patch(&[("opacity", crate::StyleValue::Number(0.8))])),
}],
);
c.commit();
c.set_states(4, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.8);
c.set_states(4, 0);
// A lone blur lets go at the frame.
c.run_frame(crate::time::now());
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
}
/// Whether view `id` is in the `FOCUS_VISIBLE` state.
fn focus_visible(c: &Core<FakeEngine>, id: NodeId) -> bool {
let key = c.key(id).unwrap();
c.nodes[key as usize].states & crate::tailwind::state::FOCUS_VISIBLE != 0
}
#[test]
fn focus_moved_after_a_pointer_does_not_show_until_a_key() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let mut c = core();
views(
&mut c,
&[(
2,
ROOT_ID,
"opacity-50 focus:opacity-75 focus-visible:opacity-100",
)],
);
c.commit();
// A press that moves the focus (the app's `focus()` on it): `focus:`
// only.
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.75);
assert!(!focus_visible(&c, 2));
// A key while it has the focus shows it.
c.set_input_modality(InputModality::Keyboard);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
// A pointer after that leaves it showing: only a move decides again.
c.set_input_modality(InputModality::Pointer);
assert!(c.commit().is_none_or(|b| view_style_of(&b, 2).is_none()));
assert!(focus_visible(&c, 2));
// Leaving takes both states off.
c.set_states(2, 0);
// A lone blur lets go at the frame.
c.run_frame(crate::time::now());
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
assert!(!focus_visible(&c, 2));
}
#[test]
fn focus_moved_by_the_keyboard_shows_at_once() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50 focus-visible:opacity-100"),
(4, ROOT_ID, "opacity-50 focus-visible:opacity-100"),
],
);
c.commit();
c.set_input_modality(InputModality::Keyboard);
c.set_states(2, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 1.0);
// Tab on: the state moves with the focus, reported as the platforms
// do (the view it reaches first).
c.set_states(4, FOCUSED);
c.set_states(2, 0);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 1.0);
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
assert!(focus_visible(&c, 4) && !focus_visible(&c, 2));
// The press that comes next does not take it from where it is; a
// move after it (the app's `focus()`) does not show.
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
c.set_states(4, 0);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 0.5);
assert!(view_style_of(&batch, 2).is_none_or(|s| s.opacity == 0.5));
assert!(!focus_visible(&c, 2) && !focus_visible(&c, 4));
}
#[test]
fn a_part_projected_focused_shows_focus_visible_while_the_focus_does() {
use crate::{
platform::InputModality,
tailwind::state::{FOCUS_VISIBLE, FOCUSED},
};
// A tree (2) that keeps the focus and its row (4) at the cursor.
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50"),
(
4,
2,
"opacity-50 focus:opacity-75 focus-visible:opacity-100",
),
],
);
c.commit();
let row = c.key(4).unwrap();
let projected = |states| Op::SetProp {
id: 4,
prop: Prop::ProjectedStates(states),
};
// A press on the row: the tree takes the focus unseen, the row is the
// cursor only.
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
apply(&mut c, vec![projected(FOCUSED)]);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 0.75);
assert_eq!(c.styled_states(row) & FOCUS_VISIBLE, 0);
// An arrow key: the tree's focus shows, and so does its cursor.
c.set_input_modality(InputModality::Keyboard);
let batch = c.commit().unwrap();
assert!(focus_visible(&c, 2));
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 1.0);
// The cursor moving off the row takes both off; back on, both show.
apply(&mut c, vec![projected(0)]);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 0.5);
apply(&mut c, vec![projected(FOCUSED)]);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 1.0);
// The focus leaving the tree (its row still projected as it renders
// next) takes `focus-visible:` off as the focus goes: a lone blur
// lets go at the frame.
c.set_states(2, 0);
c.run_frame(crate::time::now());
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 0.75);
// Never its own state: its events and accessibility do not see it.
assert_eq!(c.nodes[row as usize].states & FOCUS_VISIBLE, 0);
}
#[test]
fn a_part_projected_focused_follows_a_press_moving_the_focus() {
use crate::{
platform::InputModality,
tailwind::state::{FOCUS_VISIBLE, FOCUSED},
};
// The keyboard's focus shows on a button (2); a press then gives a
// list (4) the focus, its option (6) at the cursor.
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, ""),
(4, ROOT_ID, ""),
(6, 4, "opacity-50 focus-visible:opacity-100"),
],
);
c.commit();
c.set_input_modality(InputModality::Keyboard);
c.set_states(2, FOCUSED);
c.commit();
c.set_input_modality(InputModality::Pointer);
c.set_states(4, FOCUSED);
c.set_states(2, 0);
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::ProjectedStates(FOCUSED),
}],
);
let batch = c.commit().unwrap();
assert!(view_style_of(&batch, 6).is_none_or(|s| s.opacity == 0.5));
let option = c.key(6).unwrap();
assert_eq!(c.styled_states(option) & FOCUS_VISIBLE, 0);
}
#[test]
fn focus_shows_before_any_input() {
use crate::tailwind::state::FOCUSED;
// An app's first focus (an `autoFocus`) shows, as a browser's does.
let mut c = core();
views(&mut c, &[(2, ROOT_ID, "focus-visible:opacity-50")]);
c.commit();
c.set_states(2, FOCUSED);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.5);
}
#[test]
fn an_input_that_edits_shows_its_focus_whatever_gave_it() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::Input,
},
Op::SetProp {
id: 4,
prop: Prop::Readonly(true),
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
c.commit();
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
c.commit();
assert!(focus_visible(&c, 2), "a tap into a field shows its focus");
// A read-only one takes no typing: a tap gives it the focus unseen.
c.set_states(4, FOCUSED);
c.set_states(2, 0);
c.commit();
assert!(!focus_visible(&c, 4) && !focus_visible(&c, 2));
}
#[test]
fn the_input_modality_alone_sends_nothing() {
use crate::platform::InputModality;
// No focus: a key or a press changes no view.
let mut c = core();
views(&mut c, &[(2, ROOT_ID, "focus-visible:opacity-50")]);
c.commit();
c.set_input_modality(InputModality::Keyboard);
assert!(c.commit().is_none_or(|b| b.items.is_empty()));
c.set_input_modality(InputModality::Pointer);
assert!(c.commit().is_none_or(|b| b.items.is_empty()));
}
#[test]
fn a_focus_visible_style_and_group_follow_the_shown_focus() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "group opacity-50"),
(4, 2, "opacity-50 group-focus-visible:opacity-100"),
],
);
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::FocusVisibleStyle(patch(&[("opacity", crate::StyleValue::Number(0.8))])),
}],
);
c.commit();
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
let batch = c.commit();
assert!(batch.as_ref().is_none_or(|b| view_style_of(b, 2).is_none()));
assert!(batch.as_ref().is_none_or(|b| view_style_of(b, 4).is_none()));
c.set_input_modality(InputModality::Keyboard);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).unwrap().opacity, 0.8);
assert_eq!(view_style_of(&batch, 4).unwrap().opacity, 1.0);
}
#[test]
fn a_focus_reported_untracked_survives_a_tracking_change() {
use crate::tailwind::state::{FOCUSED, HOVERED};
// The platform reports the focus whatever is tracked, and keeps it
// when the tracking changes: so does the core.
let mut c = core();
views(
&mut c,
&[
(2, ROOT_ID, "opacity-50 focus-within:opacity-100"),
(4, 2, "bg-white"),
],
);
c.commit();
c.set_states(4, FOCUSED);
c.commit();
apply(&mut c, vec![class_op(4, "bg-white hover:bg-zinc-200")]);
c.commit();
assert!(c.has_focus_within(2));
c.set_states(4, FOCUSED | HOVERED);
apply(&mut c, vec![class_op(4, "bg-white")]);
c.commit();
assert!(c.has_focus_within(2) && c.has_focus_within(4));
}
#[test]
fn a_view_goes_below_its_next_sibling_in_the_parent_not_an_input_accessory() {
let mut c = core();
let view = |id| Op::Create { id, tag: Tag::View };
let insert = |child, before| Op::Insert {
parent: ROOT_ID,
child,
before,
};
apply(
&mut c,
vec![
view(2),
Op::Create {
id: 3,
tag: Tag::InputAccessory,
},
Op::SetProp {
id: 3,
prop: Prop::NativeId(Some("bar".into())),
},
view(4),
insert(2, None),
insert(3, None),
insert(4, None),
],
);
c.commit().unwrap();
// Between the first view and the accessory: the accessory is over the
// keyboard, not among the root's subviews, so the view goes below the
// one after it.
apply(&mut c, vec![view(5), insert(5, Some(3))]);
let batch = c.commit().unwrap();
let inserts: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert { child, before, .. } => Some((*child, *before)),
_ => None,
})
.collect();
assert_eq!(inserts, vec![(5, Some(4))]);
}
#[test]
fn input_accessories_are_found_by_native_id() {
let mut c = core();
let accessory = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Input { id: 2, config } => Some(config.accessory),
_ => None,
})
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::SetProp {
id: 2,
prop: Prop::InputAccessoryViewId(Some("bar".into())),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(accessory(&batch), Some(None));
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::InputAccessory,
},
Op::SetProp {
id: 3,
prop: Prop::NativeId(Some("bar".into())),
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetStyle {
id: 4,
style: style(&[("height", StyleValue::Number(44.0))]),
patch: Default::default(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(accessory(&batch), Some(Some(3)));
// As wide as the window, as tall as its content.
let frame = frame_of(&batch, 3).unwrap();
assert_eq!((frame.size.width.0, frame.size.height.0), (320.0, 44.0));
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 3,
}],
);
let batch = c.commit().unwrap();
assert_eq!(accessory(&batch), Some(None));
}
#[test]
fn inputs_report_their_content_size() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::SetProp {
id: 2,
prop: Prop::Multiline(true),
},
Op::SetStyle {
id: 2,
style: style(&[("width", StyleValue::Number(100.0))]),
patch: Default::default(),
},
Op::Listen {
id: 2,
event: EventKind::ContentSizeChange,
enabled: true,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let sizes = |c: &mut Core<FakeEngine>| {
js_events(c)
.into_iter()
.filter(|(id, kind, _)| *id == 2 && *kind == EventKind::ContentSizeChange)
.count()
};
c.commit().unwrap();
assert_eq!(sizes(&mut c), 1);
// Typing a long text wraps it: taller.
c.input_changed(2, &"x".repeat(80), 1);
c.commit();
assert_eq!(sizes(&mut c), 1);
// The same text again: no event.
c.input_changed(2, &"x".repeat(80), 2);
c.commit();
assert_eq!(sizes(&mut c), 0);
}
#[test]
fn fixed_size_inputs_report_their_content_size() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::SetProp {
id: 2,
prop: Prop::Placeholder("A much longer placeholder".into()),
},
Op::SetStyle {
id: 2,
style: style(&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(40.0)),
]),
patch: Default::default(),
},
Op::Listen {
id: 2,
event: EventKind::ContentSizeChange,
enabled: true,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let sizes = |c: &mut Core<FakeEngine>| {
js_events(c)
.into_iter()
.filter(|(id, kind, _)| *id == 2 && *kind == EventKind::ContentSizeChange)
.map(|(_, _, p)| p)
.collect::<Vec<_>>()
};
let size = |width: f64, height: f64| {
vec![EventPayload::Map(vec![
("width", PayloadValue::Number(width)),
("height", PayloadValue::Number(height)),
])]
};
let frame = |batch: &MountBatch| {
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Frame { id: 2, .. }))
};
// Sized by its placeholder, an empty input reports an empty line (the
// fake engine gives its zero-width space a width).
let batch = c.commit().unwrap();
assert!(frame(&batch));
assert_eq!(sizes(&mut c), size(8.0, 16.0));
// Its frame stays as the user types; its text's size is reported.
for (count, (text, width)) in [("ab", 16.0), ("abc", 24.0)].into_iter().enumerate() {
c.input_changed(2, text, count as u32 + 1);
assert!(c.commit().is_none_or(|b| !frame(&b)));
assert_eq!(sizes(&mut c), size(width, 16.0), "{text:?}");
}
// A value that reads as the placeholder: its own size.
c.input_changed(2, "A much longer placeholder", 3);
c.commit();
assert_eq!(sizes(&mut c), size(200.0, 16.0));
c.input_changed(2, "", 4);
c.commit();
assert_eq!(sizes(&mut c), size(8.0, 16.0));
// Nothing changed: nothing reported, nothing measured or mounted.
c.input_changed(2, "", 5);
assert!(c.commit().is_none());
assert_eq!(sizes(&mut c), Vec::new());
}
#[test]
fn text_shrinks_to_fit_its_lines() {
let mut c = Core::new(crate::text::ApproxTextEngine, size_pt(320.0, 480.0));
let ops = vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::SetStyle {
id: 2,
style: style(&[
("width", StyleValue::Number(60.0)),
("fontSize", StyleValue::Number(20.0)),
("numberOfLines", StyleValue::Number(1.0)),
]),
patch: Default::default(),
},
Op::SetProp {
id: 2,
prop: Prop::AdjustsFontSizeToFit(true),
},
Op::CreateText {
id: 3,
text: "Hello world".into(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for op in ops {
c.apply(op).unwrap();
}
let batch = c.commit().unwrap();
let size = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text.spans[0].style.font_size.0),
_ => None,
})
.unwrap();
// 11 characters at 0.55 em in 60pt: at most ~9.9pt.
assert!(size < 10.0 && size > 9.0, "{size}");
}
#[test]
fn approx_engine_and_offscreen_text_estimate_agree_on_line_height() {
let mut text = crate::AttributedText::default();
text.push(
"hello",
crate::ResolvedTextStyle {
font_size: px(14.0),
line_height: px(28.0),
..Default::default()
},
);
let estimated = super::estimate_text(&text, None);
assert_eq!(estimated.height, px(28.0));
let mut c = Core::new(crate::text::ApproxTextEngine, size_pt(320.0, 480.0));
for op in [
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::SetStyle {
id: 2,
style: style(&[
("fontSize", StyleValue::Number(14.0)),
("lineHeight", StyleValue::Number(28.0)),
]),
patch: Default::default(),
},
Op::CreateText {
id: 3,
text: "hello\nworld".into(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
] {
c.apply(op).unwrap();
}
let batch = c.commit().unwrap();
let frame = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Frame { id: 2, frame } => Some(*frame),
_ => None,
})
.unwrap();
assert_eq!(frame.size.height, px(56.0));
}
#[test]
fn styles_clamp_cut_and_select_texts_and_say_which_views_take_touches() {
let mut c = Core::new(crate::text::ApproxTextEngine, size_pt(320.0, 480.0));
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let ops = vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::SetStyle {
id: 2,
style: style(&[
("numberOfLines", StyleValue::Number(2.0)),
("textOverflow", StyleValue::Str("ellipsis-middle")),
("userSelect", StyleValue::Str("text")),
]),
patch: Default::default(),
},
Op::CreateText {
id: 3,
text: "Hello world".into(),
},
insert(2, 3),
insert(ROOT_ID, 2),
// React Native's `box-none`: the view takes no touches, the ones in
// it do (it is not inherited).
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetStyle {
id: 4,
style: style(&[("pointerEvents", StyleValue::Str("box-none"))]),
patch: Default::default(),
},
Op::Create {
id: 6,
tag: Tag::View,
},
insert(4, 6),
insert(ROOT_ID, 4),
];
for op in ops {
c.apply(op).unwrap();
}
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text),
_ => None,
})
.unwrap();
assert_eq!(text.max_lines, 2);
assert_eq!(text.ellipsize, crate::EllipsizeMode::Middle);
assert_eq!(text.selectable, Some(true));
let pointer = |id| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewProps { id: i, props } if *i == id => Some(props.pointer_events),
_ => None,
})
};
assert_eq!(pointer(4), Some(crate::PointerEvents::BoxNone));
assert_eq!(pointer(6), None);
}
#[test]
fn texts_inside_attachments_take_the_color_of_the_text_around() {
// `<Text style={{ color }}>a <Text>b <View><Text>chip</Text></View></Text></Text>`:
// the chip's text is the paragraph's color (CSS `color` inherits into
// an inline block), its font size its own, and it follows a change.
let mut c = core();
let raw = |id, text: &str| Op::CreateText {
id,
text: text.into(),
};
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let text = |id| Op::Create { id, tag: Tag::Text };
apply(
&mut c,
vec![
text(2),
style_op(
2,
&[
("color", StyleValue::Str("#ff0000")),
("fontSize", StyleValue::Number(20.0)),
],
),
raw(3, "a "),
text(4),
raw(5, "b "),
Op::Create {
id: 6,
tag: Tag::View,
},
text(7),
raw(8, "chip"),
// A second chip whose text sets its own color.
Op::Create {
id: 9,
tag: Tag::View,
},
text(10),
style_op(10, &[("color", StyleValue::Str("#0000ff"))]),
raw(11, "own"),
insert(7, 8),
insert(6, 7),
insert(10, 11),
insert(9, 10),
insert(4, 5),
insert(4, 6),
insert(4, 9),
insert(2, 3),
insert(2, 4),
insert(ROOT_ID, 2),
],
);
let style_of = |batch: &MountBatch, id| {
batch.items.iter().find_map(|i| match i {
MountItem::Text { id: i, text, .. } if *i == id => Some(text.spans[0].style),
_ => None,
})
};
let (red, green, blue) = (Color(0xff00_00ff), Color(0x00ff_00ff), Color(0x0000_ffff));
let batch = c.commit().unwrap();
let chip = style_of(&batch, 7).expect("the chip's text");
assert_eq!(chip.color, red);
assert_eq!(chip.font_size, ResolvedTextStyle::default().font_size);
assert_eq!(style_of(&batch, 10).map(|s| s.color), Some(blue));
// The paragraph's color changes: the chip's text follows.
c.apply(style_op(2, &[("color", StyleValue::Str("#00ff00"))]))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(style_of(&batch, 7).map(|s| s.color), Some(green));
// A span's color is nearer.
c.apply(style_op(4, &[("color", StyleValue::Str("#ffff00"))]))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(
style_of(&batch, 7).map(|s| s.color),
Some(Color(0xffff_00ff))
);
// The one with a color of its own keeps it (and is not sent again).
assert_ne!(
style_of(&batch, 10).map(|s| s.color),
Some(Color(0xffff_00ff))
);
}
#[test]
fn views_inside_text_are_attachments() {
let mut c = core();
let raw = |id, text: &str| Op::CreateText {
id,
text: text.into(),
};
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
raw(3, "ab"),
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(10.0)),
("padding", StyleValue::Number(2.0)),
],
),
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(5, &[("height", StyleValue::Number(3.0))]),
insert(4, 5),
// A span holding an image (inside a span still attaches to the
// block).
Op::Create {
id: 6,
tag: Tag::Text,
},
raw(7, "cd"),
Op::Create {
id: 8,
tag: Tag::Image,
},
style_op(
8,
&[
("width", StyleValue::Number(12.0)),
("height", StyleValue::Number(12.0)),
],
),
insert(6, 7),
insert(6, 8),
insert(2, 3),
insert(2, 4),
insert(2, 6),
style_op(2, &[("padding", StyleValue::Number(5.0))]),
insert(ROOT_ID, 2),
],
);
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text.clone()),
_ => None,
})
.unwrap();
assert_eq!(text.text, "ab\u{FFFC}cd\u{FFFC}");
assert_eq!(
text.attachments,
vec![
crate::TextAttachment {
index: 2,
width: Points(20.0),
height: Points(10.0),
},
crate::TextAttachment {
index: 5,
width: Points(12.0),
height: Points(12.0),
},
]
);
// Their views go inside the text view, on their placeholders.
let inserts: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert {
parent: 2, child, ..
} => Some(*child),
_ => None,
})
.collect();
assert_eq!(inserts, vec![4, 8]);
assert_eq!(
frame_of(&batch, 4),
Some(rect(5.0 + 16.0, 5.0 + 2.0, 20.0, 10.0))
);
assert_eq!(frame_of(&batch, 8).map(|f| f.origin.x.0), Some(5.0 + 40.0));
// The attachment's own subtree is laid out inside it.
assert_eq!(frame_of(&batch, 5), Some(rect(2.0, 2.0, 16.0, 3.0)));
// Growing an attachment builds the text again.
apply(
&mut c,
vec![style_op(
4,
&[
("width", StyleValue::Number(30.0)),
("height", StyleValue::Number(10.0)),
],
)],
);
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text.clone()),
_ => None,
})
.unwrap();
assert_eq!(text.attachments[0].width, Points(30.0));
assert_eq!(frame_of(&batch, 4).map(|f| f.size.width.0), Some(30.0));
// `verticalAlign` builds the text again: the engine places it.
let align_of = |c: &mut Core<FakeEngine>, align: &str| {
apply(
c,
vec![style_op(4, &[("verticalAlign", StyleValue::Str(align))])],
);
let batch = c.commit()?;
if !batch
.items
.iter()
.any(|i| matches!(i, MountItem::Text { id: 2, .. }))
{
return None;
}
let layout = c.nodes[c.key(2).unwrap() as usize].layout.unwrap();
let cx = c.text_cx(layout);
Some(cx.alignments.get(cx.text.attachments[0].index))
};
assert_eq!(
align_of(&mut c, "text-top"),
Some(crate::VerticalAlign::TextTop)
);
assert_eq!(
align_of(&mut c, "middle"),
Some(crate::VerticalAlign::Middle)
);
// Unchanged: nothing to build.
assert_eq!(align_of(&mut c, "middle"), None);
assert_eq!(
align_of(&mut c, "baseline"),
Some(crate::VerticalAlign::Baseline)
);
// Taken out of the text: its view leaves the text view.
apply(
&mut c,
vec![Op::Remove {
parent: 2,
child: 4,
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: 4 }))
);
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text.clone()),
_ => None,
})
.unwrap();
assert_eq!(text.text, "abcd\u{FFFC}");
assert_eq!(frame_of(&batch, 8).map(|f| f.origin.x.0), Some(5.0 + 32.0));
}
/// Views `ids` in a chain, the first under `under`, each under the one
/// before.
fn chain(c: &mut Core<FakeEngine>, under: NodeId, ids: std::ops::Range<NodeId>) {
let mut parent = under;
for id in ids {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
c.apply(Op::Insert {
parent,
child: id,
before: None,
})
.unwrap();
parent = id;
}
}
/// A view whose height was counted again (it once held a deep tree that
/// left) and that then grows a deep tree again, below views of it that
/// still reckon with the tree that left, is refused when it goes too deep:
/// what it holds is counted, not what it was told.
#[test]
fn a_view_counted_again_is_refused_once_it_grows_too_deep() {
let max = MAX_TREE_DEPTH as u32;
let mut c = core();
// View 2 holds 3, which holds a chain nearly as deep as the quota.
for id in [2, 3] {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
}
c.apply(Op::Insert {
parent: 2,
child: 3,
before: None,
})
.unwrap();
chain(&mut c, 3, 1_000..1_000 + max - 100);
// The chain leaves: 2 and 3 still reckon with it.
c.apply(Op::Remove {
parent: 3,
child: 1_000,
})
.unwrap();
// 2 goes under a chain of 100, where what 2 reckons with does not fit:
// it is counted again, and fits.
chain(&mut c, ROOT_ID, 10_000..10_100);
c.apply(Op::Insert {
parent: 10_099,
child: 2,
before: None,
})
.unwrap();
// 3 grows a chain of 900 there, which fits.
chain(&mut c, 3, 20_000..20_900);
// 2, holding 901 levels, cannot go under a chain of 300.
c.apply(Op::Remove {
parent: 10_099,
child: 2,
})
.unwrap();
chain(&mut c, ROOT_ID, 30_000..30_300);
assert_eq!(
c.apply(Op::Insert {
parent: 30_299,
child: 2,
before: None,
}),
Err(ApplyError::TooDeep(MAX_TREE_DEPTH))
);
}
/// View 2 under the root holding views 3 and 4, then `n` views each
/// inserted by `place` (given the view and its number); what placing
/// them looked at ([`Components::placing_work`]).
fn placing_work(n: u32, place: impl Fn(&mut Core<FakeEngine>, NodeId, u32)) -> usize {
let mut c = core();
for id in 2..5 {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
}
for (parent, child) in [(ROOT_ID, 2), (2, 3), (2, 4)] {
c.apply(Op::Insert {
parent,
child,
before: None,
})
.unwrap();
}
c.commit();
c.components.placing_work.set(0);
for i in 0..n {
let id = 10 + i;
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
place(&mut c, id, i);
}
c.commit();
c.components.placing_work.get()
}
/// Views inserted before the last of their siblings (rows before what
/// follows a list) or before the first (a chat's older messages) are
/// placed, in the core's children and in the layout's, by looking at the
/// siblings near the anchor, not at all those before it: four times the
/// views, about four times the work.
#[test]
fn views_inserted_near_an_anchor_are_placed_without_counting_siblings() {
let before = |anchor: fn(u32) -> NodeId| {
move |c: &mut Core<FakeEngine>, id: NodeId, i: u32| {
c.apply(Op::Insert {
parent: 2,
child: id,
before: Some(anchor(i)),
})
.unwrap();
}
};
let mut grew = Vec::new();
for (name, anchor) in [
("before the last", (|_| 4) as fn(u32) -> NodeId),
("before the first", |i| if i == 0 { 3 } else { 10 + i - 1 }),
] {
let (few, many) = (
placing_work(400, before(anchor)),
placing_work(1_600, before(anchor)),
);
if many > 5 * few.max(1) {
grew.push(format!("{name}: {few} for 400 views, {many} for 1,600"));
}
}
assert!(grew.is_empty(), "{grew:#?}");
}
/// Views inserted before an anchor end up where they were put, in the
/// core's children, natively and in the layout.
#[test]
fn views_inserted_before_an_anchor_lay_out_in_order() {
let mut c = core();
for id in 2..6 {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
c.apply(Op::SetStyle {
id,
style: style(&[("height", StyleValue::Number(10.0))]),
patch: StylePatch::default(),
})
.unwrap();
}
c.apply(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
})
.unwrap();
// A raw text before the anchor takes no place in the layout.
c.apply(Op::CreateText {
id: 9,
text: "ignored".into(),
})
.unwrap();
for (child, before) in [(3, None), (9, None), (4, None), (5, Some(4))] {
c.apply(Op::Insert {
parent: 2,
child,
before,
})
.unwrap();
}
c.commit();
let y = |c: &Core<FakeEngine>, id| c.measure(id).map(|m| m.frame.origin.y.0);
assert_eq!(
[y(&c, 3), y(&c, 5), y(&c, 4)],
[Some(0.0), Some(10.0), Some(20.0)]
);
}
#[test]
fn node_quota_and_dense_ids() {
let mut c = core();
c.set_max_nodes(3);
// The root is one node.
for id in 2..4 {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
}
assert!(matches!(
c.apply(Op::Create {
id: 4,
tag: Tag::View
}),
Err(ApplyError::TooManyNodes(3))
));
let mut c = core();
c.set_max_nodes(1000);
// An id that would make the id table enormous.
let err = c
.apply(Op::Create {
id: 4_000_000_000,
tag: Tag::View,
})
.unwrap_err();
assert!(matches!(err, ApplyError::IdOutOfRange(_)) && err.is_fatal());
}
/// Views 10, 11, … nested `depth` deep, the first in `under`: made from
/// `under` down (`top_down`), or from the deepest up and put in `under`
/// last. The first insert refused, if one is.
fn nest(
c: &mut Core<FakeEngine>,
under: NodeId,
depth: u32,
top_down: bool,
) -> Result<(), ApplyError> {
for id in 10..10 + depth {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
}
let mut inserts: Vec<(NodeId, NodeId)> = (0..depth)
.map(|i| (if i == 0 { under } else { 9 + i }, 10 + i))
.collect();
if !top_down {
inserts.reverse();
}
for (parent, child) in inserts {
c.apply(Op::Insert {
parent,
child,
before: None,
})?;
}
Ok(())
}
/// Runs `f` on a thread with room for the depth quota's recursion, sized
/// past the engine's own (`a test thread's is smaller`, and a Windows
/// debug build drops a deep tree with deeper frames than a release one).
fn on_engine_stack(f: impl FnOnce() + Send + 'static) {
std::thread::Builder::new()
.stack_size(64 << 20)
.spawn(f)
.unwrap()
.join()
.unwrap();
}
#[test]
fn views_nest_to_the_depth_quota_and_no_deeper() {
on_engine_stack(views_nest_to_the_depth_quota);
}
fn views_nest_to_the_depth_quota() {
let max = MAX_TREE_DEPTH as u32;
for top_down in [true, false] {
// As deep as the quota allows: laid out and mounted.
let mut c = core();
assert_eq!(nest(&mut c, ROOT_ID, max, top_down), Ok(()));
let batch = c.commit().expect("mounted");
assert!(frame_of(&batch, 9 + max).is_some());
// One deeper: refused, and the app is stopped.
let mut c = core();
let err = nest(&mut c, ROOT_ID, max + 1, top_down).unwrap_err();
assert_eq!(err, ApplyError::TooDeep(MAX_TREE_DEPTH));
assert!(err.is_fatal());
// The refused view stays out of the tree, which still commits.
c.commit().expect("mounted");
let refused = if top_down { 10 + max } else { 10 };
assert_eq!(c.measure(refused), None);
}
}
#[test]
fn a_view_that_held_a_deep_tree_goes_deep_once_it_is_gone() {
on_engine_stack(a_view_that_held_a_deep_tree);
}
fn a_view_that_held_a_deep_tree() {
let max = MAX_TREE_DEPTH as u32;
let mut c = core();
// View 2 holds views nested nearly to the quota, then lets them go.
c.apply(Op::Create {
id: 2,
tag: Tag::View,
})
.unwrap();
c.apply(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
})
.unwrap();
nest(&mut c, 2, max - 1, true).unwrap();
c.apply(Op::Insert {
parent: ROOT_ID,
child: 10,
before: None,
})
.unwrap();
// Alone, it goes at the bottom of them: as deep as the quota.
c.apply(Op::Insert {
parent: 9 + max - 1,
child: 2,
before: None,
})
.unwrap();
// And nothing goes under it there.
c.apply(Op::Create {
id: 3,
tag: Tag::View,
})
.unwrap();
assert_eq!(
c.apply(Op::Insert {
parent: 2,
child: 3,
before: None,
}),
Err(ApplyError::TooDeep(MAX_TREE_DEPTH))
);
}
#[test]
fn returning_to_a_small_tree_keeps_legitimate_node_ids_in_range() {
let mut c = core();
c.set_max_nodes(8);
let mut id = 2;
for _ in 0..3 * crate::id_table::PAGE {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
c.alias(id + 1, id).unwrap();
c.unalias(id + 1);
c.apply(Op::Release { id }).unwrap();
id += 2;
}
// Aliases also advance when the underlying host stays mounted.
for alias in id..id + 2 * crate::id_table::PAGE as NodeId {
c.alias(alias, ROOT_ID).unwrap();
c.unalias(alias);
}
assert_eq!(c.slots.pages(), 1);
assert_eq!(c.slots.len(), 1);
}
#[test]
fn returning_to_a_small_tree_keeps_folded_text_ids_in_range() {
let mut c = core();
c.set_max_nodes(8);
for id in 2..3 * crate::id_table::PAGE as NodeId {
c.apply(Op::CreateText {
id,
text: "row".into(),
})
.unwrap();
c.apply(Op::Release { id }).unwrap();
}
assert!(c.runs.is_empty());
assert_eq!(c.slots.pages(), 1);
}
#[test]
fn the_id_table_follows_the_nodes_alive_not_every_id_made() {
let mut c = core();
// A stream of short-lived nodes with ever higher ids, as an app that
// re-renders for hours makes them.
let mut last = None;
for id in (2..2_000_000).step_by(2) {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
if let Some(old) = last.replace(id) {
c.apply(Op::Release { id: old }).unwrap();
}
if id % 20_000 == 0 {
c.commit();
}
}
c.commit();
assert!(
c.slots.pages() <= 2,
"{} pages for {} nodes",
c.slots.pages(),
c.slots.len()
);
// The newest node and the root are still known.
assert!(c.key(1_999_998).is_ok());
assert!(c.key(ROOT_ID).is_ok());
}
#[test]
fn web_views_fail_at_once_where_the_platform_shows_none() {
let made = |web_views: bool| {
let mut c = core();
c.set_environment(crate::element::Environment {
web_views,
..Default::default()
});
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
js_events(&mut c)
};
// Where web views show, nothing to report.
assert_eq!(made(true), []);
let events = made(false);
let [(2, EventKind::Error, EventPayload::Map(fields))] = &events[..] else {
panic!("expected the web view's error: {events:?}");
};
assert!(fields.contains(&(
"code",
crate::PayloadValue::Str("ERR_FEATURE_UNAVAILABLE_ON_PLATFORM".into())
)));
}
#[test]
fn refused_urls_fail_and_send_nothing() {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": ["cdn.example.com"] } }),
)
.unwrap(),
granted: None,
}));
let image = |id, uri: &str| {
vec![
Op::Create {
id,
tag: Tag::Image,
},
Op::Listen {
id,
event: EventKind::Error,
enabled: true,
},
Op::SetProp {
id,
prop: Prop::Source(Some(ImageSource {
uri: uri.into(),
size: None,
scales: ImageScales::NONE,
data: None,
})),
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]
};
let mut ops = image(2, "https://cdn.example.com/a.png");
ops.extend(image(3, "https://tracker.io/pixel.gif"));
ops.push(Op::Command {
id: ROOT_ID,
command: Command::StatusBar(Default::default()),
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
let sources: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Image { id, source, .. } => {
Some((*id, source.as_ref().map(|s| s.uri.to_string())))
}
_ => None,
})
.collect();
// The refused image loads nothing.
assert_eq!(
sources,
[
(2, Some("https://cdn.example.com/a.png".to_owned())),
(3, None)
]
);
// (The tokens `core()` set go to the platform as ever.)
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::Command { command, .. } if !matches!(command, Command::Tokens(_))
)));
let events = js_events(&mut c);
let [(3, EventKind::Error, EventPayload::Map(fields))] = &events[..] else {
panic!("expected the refused image's error: {events:?}");
};
let field = |key| fields.iter().find(|(k, _)| *k == key).map(|(_, v)| v);
assert!(
matches!(field("message"), Some(crate::PayloadValue::Str(m)) if m.contains("`tracker.io`"))
);
assert_eq!(
field("code"),
Some(&crate::PayloadValue::Str("ERR_ACCESS_DENIED".into()))
);
}
/// An image or a video loads the URL the check granted, as WHATWG's parser
/// reads it: `//` takes the base's scheme, dot segments are resolved, and a
/// source naming a host the app is not granted loads nothing.
#[test]
fn media_sources_load_the_url_the_check_granted() {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": ["docs.example.com"] } }),
)
.unwrap(),
granted: None,
}));
c.set_base_url(Some("https://app.example/index.html".into()));
let image = |id, uri: &str| {
vec![
Op::Create {
id,
tag: Tag::Image,
},
Op::SetProp {
id,
prop: Prop::Source(Some(ImageSource {
uri: uri.into(),
size: None,
scales: ImageScales::NONE,
data: None,
})),
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]
};
let mut ops = image(2, "//docs.example.com/a/../x.png");
ops.extend(image(4, "//bank.example/x.png"));
ops.extend(image(6, "https:\\\\bank.example\\x.png"));
ops.extend(image(8, "asset:/own.png"));
ops.extend([
Op::Create {
id: 10,
tag: Tag::Video,
},
Op::SetProp {
id: 10,
prop: Prop::Native(NativeProp::Src(Some(
"//docs.example.com/v/../v.mp4".into(),
))),
},
Op::SetProp {
id: 10,
prop: Prop::Native(NativeProp::Poster(Some(
"//docs.example.com/p/../poster.png".into(),
))),
},
Op::Insert {
parent: ROOT_ID,
child: 10,
before: None,
},
]);
apply(&mut c, ops);
let batch = c.commit().unwrap();
let images: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Image { id, source, .. } => {
Some((*id, source.as_ref().map(|s| s.uri.to_string())))
}
_ => None,
})
.collect();
assert_eq!(
images,
[
(2, Some("https://docs.example.com/x.png".to_owned())),
(4, None),
(6, None),
(8, Some("asset:/own.png".to_owned())),
]
);
let video = batch.items.iter().rev().find_map(|i| match i {
MountItem::NativeProps {
id: 10,
props: crate::NativeProps::Video(p),
} => Some(p),
_ => None,
});
let video = video.expect("the video's props");
assert_eq!(
video.source.as_deref(),
Some("https://docs.example.com/v.mp4")
);
assert_eq!(
video.poster.as_deref(),
Some("https://docs.example.com/poster.png")
);
}
/// In a native app (no base), a relative image or video source loads
/// nothing for an app with capabilities: the platforms read it against the
/// working directory.
#[test]
fn relative_media_sources_load_nothing_in_a_native_app() {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": ["*"] } }),
)
.unwrap(),
granted: None,
}));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Image,
},
Op::SetProp {
id: 2,
prop: Prop::Source(Some(ImageSource {
uri: "img/a.png".into(),
size: None,
scales: ImageScales::NONE,
data: None,
})),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::Video,
},
Op::SetProp {
id: 4,
prop: Prop::Native(NativeProp::Src(Some("Users/a/clip.mp4".into()))),
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
let batch = c.commit().unwrap();
let image = batch.items.iter().find_map(|i| match i {
MountItem::Image { id: 2, source, .. } => Some(source.clone()),
_ => None,
});
assert_eq!(image, Some(None));
let video = batch.items.iter().rev().find_map(|i| match i {
MountItem::NativeProps {
id: 4,
props: crate::NativeProps::Video(p),
} => Some(p.source.clone()),
_ => None,
});
assert_eq!(video.flatten(), None);
}
/// Draws `uris` on canvas 2 (made on the first call), the frame's number
/// in the destination so each draw differs: the image URIs it sent.
fn drawn_on_canvas(c: &mut Core<FakeEngine>, uris: &[&str], frame: f32) -> Vec<String> {
let mut ops = Vec::new();
if c.key(2).is_err() {
ops.extend([
Op::Create {
id: 2,
tag: Tag::Canvas,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
]);
}
ops.push(Op::Draw {
id: 2,
drawing: Box::new(crate::canvas::Drawing {
ops: uris
.iter()
.map(|uri| crate::canvas::CanvasOp::DrawImage {
image: crate::canvas::CanvasImage { uri: (*uri).into() },
source: None,
dest: [crate::canvas::Num::Const(frame); 4],
})
.collect(),
..Default::default()
}),
});
apply(c, ops);
let batch = c.commit().unwrap();
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Canvas { drawing, .. } => Some(drawing),
_ => None,
})
.flat_map(|d| d.ops.iter())
.filter_map(|op| match op {
crate::canvas::CanvasOp::DrawImage { image, .. } => Some(image.uri.to_string()),
_ => None,
})
.collect()
}
/// A canvas checks its images on every draw. What it remembers of a
/// network image's check goes with the grant: once the grant changes, the
/// next draw is checked against the new one.
#[test]
fn canvas_images_follow_a_changed_grant() {
let grant = |hosts: &[&str]| {
Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": hosts } }),
)
.unwrap(),
granted: None,
})
};
let mut c = core();
c.set_access(grant(&["docs.example.com"]));
let image = "https://docs.example.com/a/../x.png";
assert_eq!(
drawn_on_canvas(&mut c, &[image], 1.0),
["https://docs.example.com/x.png"]
);
assert_eq!(
drawn_on_canvas(&mut c, &[image], 2.0),
["https://docs.example.com/x.png"]
);
c.set_access(grant(&["cdn.example.com"]));
assert_eq!(drawn_on_canvas(&mut c, &[image], 3.0), Vec::<String>::new());
}
/// A canvas's local image is resolved on every draw, never remembered: a
/// file granted on one draw and replaced by a link out of the root is
/// refused on the next.
#[cfg(unix)]
#[test]
fn canvas_local_images_are_resolved_on_every_draw() {
let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, std::path::PathBuf::from);
let root = base.join(format!("canvas-files-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("allowed")).unwrap();
let root = crate::access::canonicalize(&root).unwrap();
std::fs::write(root.join("allowed/a.png"), b"public").unwrap();
std::fs::write(root.join("secret.png"), b"secret").unwrap();
let allowed = root.join("allowed").to_str().unwrap().to_owned();
let access = Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
)
.unwrap(),
granted: None,
});
let mut c = core();
c.set_access(access.clone());
c.set_media_files(Arc::new(crate::access::MediaFiles::new(
&access,
None,
&crate::access::TrustedPaths::default(),
true,
)));
let image = format!("{allowed}/a.png");
assert_eq!(
drawn_on_canvas(&mut c, &[&image], 1.0),
std::slice::from_ref(&image)
);
std::fs::remove_file(root.join("allowed/a.png")).unwrap();
std::os::unix::fs::symlink(root.join("secret.png"), root.join("allowed/a.png")).unwrap();
assert_eq!(
drawn_on_canvas(&mut c, &[&image], 2.0),
Vec::<String>::new()
);
let _ = std::fs::remove_dir_all(&root);
}
/// A drawing that names a local image many times (a map's tiles from one
/// sheet) resolves it on the disk once, not once per draw: still on every
/// drawing, each draw keeps it.
#[cfg(unix)]
#[test]
fn a_canvas_local_image_is_resolved_once_per_drawing() {
let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, std::path::PathBuf::from);
let root = base.join(format!("canvas-once-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let root = crate::access::canonicalize(&root).unwrap();
std::fs::write(root.join("sheet.png"), b"tiles").unwrap();
let allowed = root.to_str().unwrap().to_owned();
let access = Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
)
.unwrap(),
granted: None,
});
let mut c = core();
c.set_access(access.clone());
c.set_media_files(Arc::new(crate::access::MediaFiles::new(
&access,
None,
&crate::access::TrustedPaths::default(),
true,
)));
let image = format!("{allowed}/sheet.png");
let tiles = vec![image.as_str(); 500];
for frame in 1..=2 {
let before = crate::access::resolves();
assert_eq!(drawn_on_canvas(&mut c, &tiles, frame as f32).len(), 500);
assert_eq!(crate::access::resolves() - before, 1, "frame {frame}");
}
let _ = std::fs::remove_dir_all(&root);
}
/// Menu and tray icons load what the check granted, as an `<Image>`
/// does: one the app's capabilities do not grant is dropped.
#[test]
fn menu_and_tray_icons_load_what_the_check_granted() {
use crate::desktop::{DesktopCommand, MenuAction, MenuItem, Tray};
let icon = |uri: &str| {
Some(ImageSource {
uri: uri.into(),
..Default::default()
})
};
let action = |uri: &str| {
MenuItem::Action(MenuAction {
id: 1,
label: "A".into(),
shortcut: None,
enabled: true,
checked: None,
role: None,
when: Default::default(),
icon: icon(uri),
symbol: None,
destructive: false,
})
};
let items = || -> Arc<[MenuItem]> {
vec![
action("https://cdn.example.com/a.png"),
MenuItem::Submenu {
label: "S".into(),
enabled: true,
items: vec![action("https://evil.example/b.png")],
icon: icon("https://evil.example/c.png"),
symbol: None,
inline: false,
},
]
.into()
};
let icons = |items: &[MenuItem]| {
let mut out = Vec::new();
MenuItem::each_icon(items, &mut |i| out.push(i.uri.to_string()));
out
};
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": ["cdn.example.com"] } }),
)
.unwrap(),
granted: None,
}));
let mut menu = DesktopCommand::SetMenu(Some(items()));
c.check_menu_icons(&mut menu);
let DesktopCommand::SetMenu(Some(checked)) = &menu else {
unreachable!()
};
assert_eq!(icons(checked), ["https://cdn.example.com/a.png"]);
let mut tray = DesktopCommand::SetTray(Some(Tray {
icon: icon("https://evil.example/t.png"),
menu: items(),
..Default::default()
}));
c.check_menu_icons(&mut tray);
let DesktopCommand::SetTray(Some(checked)) = &tray else {
unreachable!()
};
assert_eq!(checked.icon, None);
assert_eq!(icons(&checked.menu), ["https://cdn.example.com/a.png"]);
// Without capabilities every icon loads as written.
c.set_access(Arc::default());
let mut menu = DesktopCommand::SetMenu(Some(items()));
c.check_menu_icons(&mut menu);
let DesktopCommand::SetMenu(Some(checked)) = &menu else {
unreachable!()
};
assert_eq!(icons(checked).len(), 3);
}
/// A placeholder loads the URL the check granted, as the image's source
/// does, and shows nothing when its host is not granted.
#[test]
fn placeholders_load_the_url_the_check_granted() {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": ["docs.example.com"] } }),
)
.unwrap(),
granted: None,
}));
c.set_base_url(Some("https://app.example/index.html".into()));
let placeholder = |id, uri: &str| {
vec![
Op::Create {
id,
tag: Tag::Image,
},
Op::SetProp {
id,
prop: Prop::Image(ImageProp::Placeholder(Some(ImageSource {
uri: uri.into(),
size: None,
scales: ImageScales::NONE,
data: None,
}))),
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]
};
let mut ops = placeholder(2, "//docs.example.com/a/../p.png");
ops.extend(placeholder(4, "//bank.example/p.png"));
ops.extend(placeholder(6, "asset:/../outside.png"));
ops.extend(placeholder(8, "asset:/inside.png"));
apply(&mut c, ops);
let batch = c.commit().unwrap();
let placeholders: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Image { id, options, .. } => {
Some((*id, options.placeholder.as_ref().map(|s| s.uri.to_string())))
}
_ => None,
})
.collect();
assert_eq!(
placeholders,
[
(2, Some("https://docs.example.com/p.png".to_owned())),
(4, None),
(6, None),
(8, Some("asset:/inside.png".to_owned())),
]
);
}
/// A local image loads its canonical path when `capabilities.fs.read` holds
/// it, in the form it was written, and nothing when it leaves the root.
#[cfg(unix)]
#[test]
fn local_images_load_the_path_the_fs_grant_holds() {
let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, std::path::PathBuf::from);
let root = base.join(format!("core-media-files-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("allowed")).unwrap();
std::fs::create_dir_all(root.join("outside")).unwrap();
let root = crate::access::canonicalize(&root).unwrap();
let allowed = root.join("allowed").to_str().unwrap().to_owned();
let access = Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
)
.unwrap(),
granted: None,
});
let mut c = core();
c.set_access(access.clone());
c.set_media_files(Arc::new(crate::access::MediaFiles::new(
&access,
None,
&crate::access::TrustedPaths::default(),
true,
)));
let image = |id, uri: String| {
vec![
Op::Create {
id,
tag: Tag::Image,
},
Op::SetProp {
id,
prop: Prop::Source(Some(ImageSource {
uri: uri.into(),
size: None,
scales: ImageScales::NONE,
data: None,
})),
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]
};
let mut ops = image(2, format!("{allowed}/./a.png"));
ops.extend(image(4, format!("file://{allowed}/sub/../a.png")));
ops.extend(image(6, format!("{allowed}/../outside/b.png")));
ops.extend(image(8, format!("file://{allowed}/%2e%2e/outside/b.png")));
apply(&mut c, ops);
let batch = c.commit().unwrap();
let images: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Image { id, source, .. } => {
Some((*id, source.as_ref().map(|s| s.uri.to_string())))
}
_ => None,
})
.collect();
assert_eq!(
images,
[
(2, Some(format!("{allowed}/a.png"))),
(4, Some(format!("file://{allowed}/a.png"))),
(6, None),
(8, None),
]
);
let _ = std::fs::remove_dir_all(&root);
}
/// A canvas image draws, and `Image.getSize` / `prefetch` loads, the URL the
/// check granted; one naming a host the app is not granted is dropped.
#[test]
fn canvas_images_and_image_info_load_the_url_the_check_granted() {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": ["docs.example.com"] } }),
)
.unwrap(),
granted: None,
}));
c.set_base_url(Some("https://app.example/index.html".into()));
let draw = |uri: &str| crate::canvas::CanvasOp::DrawImage {
image: crate::canvas::CanvasImage { uri: uri.into() },
source: None,
dest: [crate::canvas::Num::Const(0.0); 4],
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Canvas,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Draw {
id: 2,
drawing: Box::new(crate::canvas::Drawing {
ops: vec![
draw("//docs.example.com/a/../x.png"),
draw("//bank.example/x.png"),
],
..Default::default()
}),
},
Op::Command {
id: ROOT_ID,
command: Command::ImageInfo {
id: 1,
uri: "//docs.example.com/b/../y.png".into(),
},
},
Op::Command {
id: ROOT_ID,
command: Command::ImageInfo {
id: 2,
uri: "//bank.example/y.png".into(),
},
},
],
);
let batch = c.commit().unwrap();
let drawn: Vec<String> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Canvas { drawing, .. } => Some(drawing),
_ => None,
})
.flat_map(|d| d.ops.iter())
.filter_map(|op| match op {
crate::canvas::CanvasOp::DrawImage { image, .. } => Some(image.uri.to_string()),
_ => None,
})
.collect();
assert_eq!(drawn, ["https://docs.example.com/x.png"]);
let asked: Vec<String> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Command {
command: Command::ImageInfo { uri, .. },
..
} => Some(uri.clone()),
_ => None,
})
.collect();
assert_eq!(asked, ["https://docs.example.com/y.png"]);
}
/// A refusal names the host to grant, or, for a URL no host grant can
/// cover, how to write it: adding the URL itself would never grant it.
#[test]
fn refusals_name_the_host_to_grant_or_how_to_write_the_url() {
let refusal = |uri| super::not_granted("the web page", uri, "webview.hosts");
assert!(
refusal("https://docs.example.com/a").contains("add `docs.example.com` to capabilities")
);
for uri in ["https://bank.example\\@docs.example.com/", "not a url"] {
let message = refusal(uri);
assert!(!message.contains("add `"), "{message}");
assert!(message.contains("%5C"), "{message}");
}
}
#[test]
fn refused_web_view_html_fails() {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({})).unwrap(),
granted: None,
}));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::Listen {
id: 2,
event: EventKind::Error,
enabled: true,
},
Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
let events = js_events(&mut c);
let [(2, EventKind::Error, EventPayload::Map(fields))] = &events[..] else {
panic!("expected the refused web view's error: {events:?}");
};
assert!(
fields.iter().any(
|(k, v)| *k == "code" && *v == crate::PayloadValue::Str("ERR_ACCESS_DENIED".into())
)
);
}
/// The source a web view's mount items last gave.
fn web_source(batch: &MountBatch, view: NodeId) -> Option<crate::WebSource> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::NativeProps {
id,
props: crate::NativeProps::WebView(p),
} if *id == view => Some(p.source.clone()),
_ => None,
})
}
/// A core whose app declares `capabilities`, with web view 2 made from
/// `props` in one render (its errors listened to): the source the platform
/// receives, its `allowOrigin`, and the access errors it heard.
fn web_view_with_access(
capabilities: serde_json::Value,
props: Vec<Prop>,
) -> (
Core<FakeEngine>,
Option<crate::WebSource>,
Option<crate::access::WebOrigin>,
Vec<String>,
) {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&capabilities).unwrap(),
granted: None,
}));
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::Listen {
id: 2,
event: EventKind::Error,
enabled: true,
},
];
ops.extend(props.into_iter().map(|prop| Op::SetProp { id: 2, prop }));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
let origin = batch.items.iter().rev().find_map(|i| match i {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::WebView(p),
} => Some(p.allow_origin.clone()),
_ => None,
});
let denied = access_errors(&mut c, 2);
(c, web_source(&batch, 2), origin.flatten(), denied)
}
/// The messages of the access errors node `view` heard.
fn access_errors(c: &mut Core<FakeEngine>, view: NodeId) -> Vec<String> {
js_events(c)
.into_iter()
.filter_map(|e| match e {
(id, EventKind::Error, EventPayload::Map(fields))
if id == view
&& fields.iter().any(|(k, v)| {
*k == "code" && *v == crate::PayloadValue::Str("ERR_ACCESS_DENIED".into())
}) =>
{
fields.into_iter().find_map(|(k, v)| match (k, v) {
("message", crate::PayloadValue::Str(m)) => Some(m.to_string()),
_ => None,
})
}
_ => None,
})
.collect()
}
/// `allowOrigin` adds one origin, decided while the app runs, to the hosts
/// a web view may show, when the app declares `webview.runtimeOrigin`; set
/// in the same render as `src`, before or after it, it applies to it.
#[test]
fn web_view_allow_origin_grants_its_origin() {
let caps = serde_json::json!({ "webview": { "hosts": ["127.0.0.1"], "runtimeOrigin": true } });
let page = "http://192.168.1.5:9876/session-page/T/index.html";
let src = || Prop::Native(NativeProp::Src(Some(page.into())));
let origin = |o: &str| Prop::Native(NativeProp::AllowOrigin(Some(o.into())));
let loaded = Some(crate::WebSource::Uri(page.into()));
for props in [
vec![src(), origin("http://192.168.1.5:9876")],
vec![origin("http://192.168.1.5:9876"), src()],
] {
let (c, source, kept, denied) = web_view_with_access(caps.clone(), props);
assert_eq!(source, loaded);
assert_eq!(
kept.map(|o| o.to_string()).as_deref(),
Some("http://192.168.1.5:9876")
);
assert!(denied.is_empty(), "{denied:?}");
assert!(c.denied.is_empty(), "{:?}", c.denied);
}
// Written in its one form: the default port and the case dropped.
let (_, _, kept, _) =
web_view_with_access(caps.clone(), vec![origin("HTTPS://Name.Example.net:443/")]);
assert_eq!(
kept.map(|o| o.to_string()).as_deref(),
Some("https://name.example.net")
);
// Another origin is refused once, as a host not granted is.
for other in [
"http://192.168.1.5:9877/x",
"https://192.168.1.5:9876/x",
"http://a.192.168.1.5:9876/x",
"http://192.168.1.5:9876@evil.com/",
] {
let (_, source, _, denied) = web_view_with_access(
caps.clone(),
vec![
Prop::Native(NativeProp::Src(Some(other.into()))),
origin("http://192.168.1.5:9876"),
],
);
assert_eq!(source, Some(crate::WebSource::None), "{other}");
assert!(
matches!(&denied[..], [m] if m.contains("the web page")),
"{other}: {denied:?}"
);
}
// A base URL at the origin is kept with its HTML.
let (_, source, _, denied) = web_view_with_access(
caps.clone(),
vec![
Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
Prop::Native(NativeProp::BaseUrl(Some(
"http://192.168.1.5:9876/r/".into(),
))),
origin("http://192.168.1.5:9876"),
],
);
assert_eq!(
source,
Some(crate::WebSource::Html {
html: "<b>hi</b>".into(),
base_url: Some("http://192.168.1.5:9876/r/".into()),
})
);
assert!(denied.is_empty(), "{denied:?}");
// `webview.hosts` still grants on its own.
let (_, source, _, denied) = web_view_with_access(
caps,
vec![Prop::Native(NativeProp::Src(Some(
"http://127.0.0.1:6711/".into(),
)))],
);
assert_eq!(
source,
Some(crate::WebSource::Uri("http://127.0.0.1:6711/".into()))
);
assert!(denied.is_empty(), "{denied:?}");
}
/// Without `webview.runtimeOrigin` the prop is refused with a message and
/// the web view keeps to `webview.hosts`, its URLs refused as before; a
/// value that is not an origin is refused whatever the grant.
#[test]
fn web_view_allow_origin_needs_the_grant_and_an_origin() {
let page = "http://192.168.1.5:9876/index.html";
let (c, source, kept, denied) = web_view_with_access(
serde_json::json!({ "webview": { "hosts": ["127.0.0.1"] } }),
vec![
Prop::Native(NativeProp::AllowOrigin(Some(
"http://192.168.1.5:9876".into(),
))),
Prop::Native(NativeProp::Src(Some(page.into()))),
],
);
assert_eq!(source, Some(crate::WebSource::None));
assert_eq!(kept, None);
assert!(
matches!(&denied[..], [m] if m.contains("the web page")),
"{denied:?}"
);
assert!(
c.denied
.iter()
.any(|m| m.contains("add `\"runtimeOrigin\": true`")),
"{:?}",
c.denied
);
let caps = serde_json::json!({ "webview": { "hosts": ["127.0.0.1"], "runtimeOrigin": true } });
for bad in [
"http://h/path",
"http://h?q",
"http://h#f",
"http://u@h",
"*",
"ftp://h",
"http://*.h",
"http://bücher.example",
"h:80",
] {
let (c, _, kept, _) = web_view_with_access(
caps.clone(),
vec![Prop::Native(NativeProp::AllowOrigin(Some(bad.into())))],
);
assert_eq!(kept, None, "{bad}");
assert!(
c.denied.iter().any(|m| m.starts_with("`allowOrigin`")),
"{bad}: {:?}",
c.denied
);
}
}
/// `load()` checks against the web view's origin of the moment: a new
/// `allowOrigin` refuses the old one from the next load.
#[test]
fn web_view_allow_origin_applies_to_loads() {
let caps = serde_json::json!({ "webview": { "hosts": ["127.0.0.1"], "runtimeOrigin": true } });
let (mut c, _, _, _) = web_view_with_access(
caps,
vec![Prop::Native(NativeProp::AllowOrigin(Some(
"http://192.168.1.5:9876".into(),
)))],
);
let load = |c: &mut Core<FakeEngine>, url: &str| {
apply(
c,
vec![Op::Command {
id: 2,
command: Command::Load(crate::WebLoad {
src: url.into(),
headers: Vec::new(),
}),
}],
);
let batch = c.commit();
let sent = batch.is_some_and(|b| {
b.items.iter().any(|i| {
matches!(i, MountItem::Command { id: 2, command: Command::Load(l) } if l.src == url)
})
});
(sent, access_errors(c, 2))
};
assert_eq!(load(&mut c, "http://192.168.1.5:9876/a"), (true, vec![]));
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::AllowOrigin(Some("http://10.0.0.2:9876".into()))),
}],
);
c.commit();
let (sent, _) = load(&mut c, "http://192.168.1.5:9876/b");
assert!(!sent);
assert!(
c.denied
.iter()
.any(|m| m.contains("http://192.168.1.5:9876/b")),
"{:?}",
c.denied
);
assert!(load(&mut c, "http://10.0.0.2:9876/c").0);
}
/// Inline HTML loaded with a base URL runs at the base URL's origin
/// (WebKit, Android, Windows), so the base URL takes the grant a page there
/// would.
#[test]
fn web_view_base_urls_need_the_hosts_grant() {
let run_with = |capabilities: serde_json::Value, props: Vec<Prop>| {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&capabilities).unwrap(),
granted: None,
}));
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::Listen {
id: 2,
event: EventKind::Error,
enabled: true,
},
];
ops.extend(props.into_iter().map(|prop| Op::SetProp { id: 2, prop }));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
// The messages of the access errors reported.
let denied: Vec<String> = js_events(&mut c)
.into_iter()
.filter_map(|e| match e {
(2, EventKind::Error, EventPayload::Map(fields))
if fields.iter().any(|(k, v)| {
*k == "code" && *v == crate::PayloadValue::Str("ERR_ACCESS_DENIED".into())
}) =>
{
fields.into_iter().find_map(|(k, v)| match (k, v) {
("message", crate::PayloadValue::Str(m)) => Some(m.to_string()),
_ => None,
})
}
_ => None,
})
.collect();
(web_source(&batch, 2), denied)
};
let run = |props| {
run_with(
serde_json::json!({ "webview": { "hosts": ["docs.example.com"] } }),
props,
)
};
let html = |base: Option<&str>| crate::WebSource::Html {
html: "<b>hi</b>".into(),
base_url: base.map(Into::into),
};
let base_refused = |denied: &[String]| matches!(denied, [m] if m.contains("the base URL"));
for base in ["https://docs.example.com/a/", "about:blank", ""] {
// Granted: kept.
let (source, denied) = run(vec![
Prop::Native(NativeProp::BaseUrl(Some(base.into()))),
Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
]);
assert_eq!(source, Some(html(Some(base))), "{base}");
assert!(denied.is_empty(), "{base}: {denied:?}");
}
for base in [
"https://bank.example/",
"file:///etc/",
"not a url",
// WHATWG reads bank.example: the backslash ends the host.
"https://bank.example\\@docs.example.com/",
] {
// `html` with `baseUrl`, either order, and Rust's
// `.html(html, Some(base))`: the page loads without the base URL.
for props in [
vec![
Prop::Native(NativeProp::BaseUrl(Some(base.into()))),
Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
],
vec![
Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
Prop::Native(NativeProp::BaseUrl(Some(base.into()))),
],
vec![Prop::Native(NativeProp::Source(html(Some(base))))],
] {
let (source, denied) = run(props);
assert_eq!(source, Some(html(None)), "{base}");
assert!(base_refused(&denied), "{base}: {denied:?}");
}
}
// A subdomain grant: WHATWG reads bank.example here too.
let (source, denied) = run_with(
serde_json::json!({ "webview": { "hosts": ["*.docs.example.com"] } }),
vec![
Prop::Native(NativeProp::BaseUrl(Some(
"https://bank.example\\.docs.example.com/".into(),
))),
Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
],
);
assert_eq!(source, Some(html(None)));
assert!(base_refused(&denied), "{denied:?}");
// Without web views at all, the HTML itself is refused, once.
let (source, denied) = run_with(
serde_json::json!({}),
vec![
Prop::Native(NativeProp::BaseUrl(Some("https://bank.example/".into()))),
Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
],
);
assert!(
!matches!(source, Some(crate::WebSource::Html { .. })),
"{source:?}"
);
assert!(
matches!(&denied[..], [m] if m.contains("web views are not granted")),
"{denied:?}"
);
}
#[test]
fn web_view_incognito_is_read_when_it_is_made() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Incognito(true)),
},
Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Html(Some("<b>hi</b>".into()))),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let web = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|item| match item {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::WebView(p),
} => Some(p.incognito),
_ => None,
})
};
// The platform makes the web view with its first props.
assert_eq!(web(&c.commit().unwrap()), Some(true));
// Made: a change is ignored, and nothing is sent for it.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Incognito(false)),
}],
);
assert_eq!(c.commit().as_ref().and_then(web), None);
// Other props still reach it, with the store it was made with.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::UserAgent(Some("agent".into()))),
}],
);
assert_eq!(web(&c.commit().unwrap()), Some(true));
}
#[test]
fn web_view_zoomable_is_read_when_it_is_made() {
let mut c = core();
let web = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|item| match item {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::WebView(p),
} => Some(p.zoomable),
_ => None,
})
};
// Off unless asked.
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(web(&c.commit().unwrap()), Some(false));
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Zoomable(true)),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
// The platform makes the web view with its first props.
assert_eq!(web(&c.commit().unwrap()), Some(true));
// Made: a change is ignored, and nothing is sent for it.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::Zoomable(false)),
}],
);
assert_eq!(c.commit().as_ref().and_then(web), None);
// Other props still reach it, as it was made.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::UserAgent(Some("agent".into()))),
}],
);
assert_eq!(web(&c.commit().unwrap()), Some(true));
}
#[test]
fn web_view_url_schemes_are_read_when_it_is_made() {
use crate::web_resource::WebUrlScheme;
let scheme = WebUrlScheme::new("app-image", |request| request.fail()).unwrap();
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::UrlSchemes(vec![scheme.clone()])),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let schemes = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|item| match item {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::WebView(p),
} => Some(p.url_schemes.clone()),
_ => None,
})
};
// The platform makes the web view with its first props.
assert_eq!(schemes(&c.commit().unwrap()), Some(vec![scheme.clone()]));
// Made: another handler is ignored, and nothing is sent for it.
let other = WebUrlScheme::new("app-image", |request| request.fail()).unwrap();
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Native(NativeProp::UrlSchemes(vec![other])),
}],
);
assert_eq!(c.commit().as_ref().and_then(schemes), None);
}
mod components {
use serde_json::json;
use super::*;
use crate::{
Prop,
element::{Children, Event, Props, Registry, Slot},
prelude::*,
};
/// Counts taps; shows `label` and the count; holds its JSX children.
#[derive(Clone, PartialEq, Props)]
struct TallyProps {
#[prop(default = "Taps".into())]
label: crate::element::Prop<SharedString>,
children: Children,
}
#[derive(Event)]
enum TallyEvent {
Tap { count: u32 },
}
#[component]
fn Tally(props: TallyProps, cx: Scope<TallyEvent>) -> impl IntoElement {
let taps = signal(0);
view()
.p_2()
.on_press(move |_: &()| {
taps.update(|t| *t += 1);
cx.emit(TallyEvent::Tap {
count: taps.get_untracked(),
});
})
.child(text(move || {
format!("{} {}", props.label.get(), taps.get())
}))
.child(view().gap_1().child(props.children))
}
fn texts(batch: &MountBatch) -> Vec<String> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.clone()),
_ => None,
})
.collect()
}
/// Turns by what its ref's method says.
#[derive(Default)]
struct Knob;
#[derive(Clone, PartialEq, Props)]
struct KnobProps {}
#[derive(Clone, Copy)]
struct KnobApi {
at: crate::element::Signal<i32>,
}
#[crate::element::methods]
impl KnobApi {
/// Turns it by `by`; where it is.
pub(crate) fn turn(&self, by: i32) -> i32 {
self.at.update(|at| *at += by);
self.at.get_untracked()
}
/// Fails.
pub(crate) fn stuck(&self) -> Result<(), String> {
Err(format!("stuck at {}", self.at.get_untracked()))
}
}
impl Component for Knob {
type Props = KnobProps;
type Event = crate::element::NoEvent;
const METHODS: crate::element::Methods = crate::element::Methods::of::<KnobApi>();
fn view(_: KnobProps, cx: Scope<crate::element::NoEvent>) -> impl IntoElement {
let at = signal(0);
cx.methods(KnobApi { at });
text(move || format!("at {}", at.get()))
}
}
#[test]
fn methods_take_their_arguments_typed_and_answer_in_the_events() {
use crate::element::{RustCall, RustOp, json_host::JsonHost};
let mut c = core();
let mut registry = Registry::new();
registry.register::<Knob>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Knob>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(texts(&c.commit().unwrap()), ["at 0"]);
let methods = <KnobApi as crate::element::Api>::METHODS;
// Converted in the JS call: a value of another type fails there.
let call = |method: usize, args| {
let host = JsonHost::with_args(args);
(methods[method].call)(&host)
};
assert!(call(0, vec![json!("x")]).is_err());
for (n, (method, args, host)) in [
(0, vec![json!(3)], 2),
(1, vec![], 2),
(0, vec![json!(1)], 40),
]
.into_iter()
.enumerate()
{
let Ok(run) = call(method, args) else {
panic!("converts")
};
c.apply(Op::Rust(RustOp {
call: n as u32 + 1,
run: RustCall::Method(host, run),
}))
.unwrap();
}
assert_eq!(texts(&c.commit().unwrap()), ["at 3"]);
let replies: Vec<_> = js_events(&mut c)
.into_iter()
.map(|(_, _, payload)| match payload {
EventPayload::Native { data, .. } => data,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
replies,
[
json!({ "c": 1, "v": 3 }),
json!({ "c": 2, "e": "stuck at 3" }),
json!({ "c": 3, "e": "node 40 hosts no Rust component" }),
]
);
}
#[test]
fn a_method_called_before_the_view_is_made_waits_for_it() {
use crate::element::{RustCall, RustOp, json_host::JsonHost};
let mut c = core();
let mut registry = Registry::new();
registry.register::<Knob>();
c.set_components(registry);
let methods = <KnobApi as crate::element::Api>::METHODS;
let turn = |by: i32| {
let Ok(run) = (methods[0].call)(&JsonHost::with_args(vec![json!(by)])) else {
panic!("converts")
};
run
};
// As a ref callback calls it: the component is made, its view is
// not yet (it is not in the tree).
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Knob>().into()),
},
Op::Rust(RustOp {
call: 1,
run: RustCall::Method(2, turn(2)),
}),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(texts(&c.commit().unwrap()), ["at 2"]);
// One that never gets its view fails as its host goes.
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::Component(std::any::type_name::<Knob>().into()),
},
Op::Rust(RustOp {
call: 2,
run: RustCall::Method(4, turn(1)),
}),
],
);
let _ = c.commit();
apply(&mut c, vec![Op::Release { id: 4 }]);
let _ = c.commit();
let replies: Vec<_> = js_events(&mut c)
.into_iter()
.map(|(_, _, payload)| match payload {
EventPayload::Native { data, .. } => data,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
replies,
[
json!({ "c": 1, "v": 2 }),
json!({ "c": 2, "e": "node 4 hosts no Rust component" }),
]
);
}
thread_local! {
/// The runs of `Echo`'s text binding.
static ECHOES: Cell<usize> = const { Cell::new(0) };
}
/// Shows its label, counting the runs of the binding that reads it.
#[derive(Default)]
struct Echo;
#[derive(Clone, PartialEq, Props)]
struct EchoProps {
#[prop(default)]
label: crate::element::Prop<SharedString>,
}
impl Component for Echo {
type Props = EchoProps;
type Event = crate::element::NoEvent;
fn view(props: EchoProps, _: Scope<crate::element::NoEvent>) -> impl IntoElement {
text(move || {
ECHOES.with(|e| e.set(e.get() + 1));
props.label.get()
})
}
}
#[test]
fn a_prop_set_to_an_equal_value_runs_nothing() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Echo>();
c.set_components(registry);
let label = |v: &str| Op::SetProp {
id: 2,
prop: rust_prop::<EchoProps>("label", Some(json!(v))),
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Echo>().into()),
},
label("a"),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(texts(&c.commit().unwrap()), ["a"]);
let runs = ECHOES.with(Cell::get);
// The same value again (a new decoded value, equal): nothing runs.
apply(&mut c, vec![label("a")]);
assert!(c.commit().is_none());
assert_eq!(ECHOES.with(Cell::get), runs);
apply(&mut c, vec![label("b")]);
assert_eq!(texts(&c.commit().unwrap()), ["b"]);
assert_eq!(ECHOES.with(Cell::get), runs + 1);
}
thread_local! {
/// The `value` each of `Pick`'s closures after the app's answer saw.
static ANSWERED: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Shows a pick of its own (2) from a press until the app has answered
/// it, then the app's `value`, as a slider shows a drag's value.
#[derive(Clone, PartialEq, Props)]
struct PickProps {
#[prop(default)]
value: crate::element::Prop<u32>,
}
#[derive(Event)]
enum PickEvent {
Change(u32),
}
#[component]
fn Pick(props: PickProps, cx: Scope<PickEvent>) -> impl IntoElement {
let pending = signal(None::<u32>);
view()
.on_press(move |_: &()| {
pending.set(Some(2));
cx.emit(PickEvent::Change(2));
after_answer(move || {
ANSWERED.with(|a| a.borrow_mut().push(props.value.get_untracked()));
pending.set(None);
});
})
.child(text(move || {
format!(
"pick {}",
pending.get().unwrap_or_else(|| props.value.get())
)
}))
}
/// The app's answer to a `Pick`: its `value`.
fn pick_value(value: u32) -> Op {
Op::SetProp {
id: 2,
prop: rust_prop::<PickProps>("value", Some(json!(value))),
}
}
/// A `Pick` from JS showing 1, pressed: its pick shows, and its event
/// is queued for JS.
fn pressed_pick() -> Core<FakeEngine> {
ANSWERED.with(|a| a.borrow_mut().clear());
let mut c = core();
let mut registry = Registry::new();
registry.register::<Pick>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Pick>().into()),
},
pick_value(1),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(texts(&c.commit().unwrap()), ["pick 1"]);
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
// Shown at once; the event has not gone to JS yet, so nothing that
// waits for its answer runs.
assert_eq!(texts(&c.commit().unwrap()), ["pick 2"]);
assert!(!c.has_due_answers());
assert!(ANSWERED.with(|a| a.borrow().is_empty()));
c
}
/// A closure after the app's answer runs in the commit after the one
/// whose events went to JS, before the views render: it sees the props
/// JS set in answer, and no frame shows the app's earlier value.
#[test]
fn after_answer_runs_once_js_has_answered() {
let mut c = pressed_pick();
assert_eq!(
js_events(&mut c),
[(
2,
EventKind::NativeEvent,
EventPayload::Native {
name: "change".into(),
data: json!({ "value": 2 })
}
)]
);
assert!(c.has_due_answers(), "due in the next commit");
assert!(ANSWERED.with(|a| a.borrow().is_empty()));
// JS's handler set `value` to the pick.
apply(&mut c, vec![pick_value(2)]);
let batch = c.commit();
assert_eq!(ANSWERED.with(|a| a.borrow().clone()), [2]);
assert!(
batch.as_ref().is_none_or(|b| texts(b).is_empty()),
"the pick stays: {:?}",
batch.map(|b| texts(&b))
);
assert!(!c.has_due_answers());
// Once.
assert!(c.commit().is_none());
assert_eq!(ANSWERED.with(|a| a.borrow().len()), 1);
}
/// An app that keeps its value (its handler sets nothing) shows it once
/// it has answered.
#[test]
fn after_answer_shows_the_value_an_app_kept() {
let mut c = pressed_pick();
assert_eq!(js_events(&mut c).len(), 1);
assert_eq!(texts(&c.commit().unwrap()), ["pick 1"]);
assert_eq!(ANSWERED.with(|a| a.borrow().clone()), [1]);
}
/// A closure whose view went before the app answered never runs.
#[test]
fn after_answer_goes_with_its_view() {
let mut c = pressed_pick();
assert_eq!(js_events(&mut c).len(), 1);
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
c.commit();
assert!(ANSWERED.with(|a| a.borrow().is_empty()));
assert!(!c.has_due_answers());
}
/// Events of components that wait for nothing leave nothing due (the
/// engine commits no extra round for them) and allocate no queue.
#[test]
fn events_nothing_waits_for_cost_no_round() {
let mut c = core_with_tally();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Tally>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["Taps 1"]);
assert_eq!(js_events(&mut c).len(), 1);
assert!(!c.has_due_answers(), "no round of its own");
assert!(c.commit().is_none());
assert!(!c.components.executor.answers_allocated());
}
/// A Rust view holding a `Pick`, its `value` the view's own.
#[component]
fn PickHolder() -> impl IntoElement {
let value = signal(1u32);
pick()
.value(crate::element::Prop::bind(move || value.get()))
.on_change(move |next: &u32| value.set(*next))
}
/// With a Rust owner, whose listener runs when the event is emitted, the
/// closure runs in the commit after the one that rendered what the
/// listener changed.
#[test]
fn after_answer_follows_a_rust_owners_render() {
ANSWERED.with(|a| a.borrow_mut().clear());
let mut c = core();
c.mount_root(&crate::element::Root::new::<PickHolder>(|| ()));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["pick 1"]);
let pick = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the pick");
assert!(c.component_event(pick, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["pick 2"]);
assert!(ANSWERED.with(|a| a.borrow().is_empty()));
// Nothing for JS; what waited is due all the same.
assert!(js_events(&mut c).is_empty());
assert!(c.has_due_answers());
assert!(c.commit().is_none(), "the holder's value stays");
assert_eq!(ANSWERED.with(|a| a.borrow().clone()), [2]);
}
fn core_with_tally() -> Core<FakeEngine> {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Tally>();
c.set_components(registry);
c
}
/// A Rust app's root: mounted with no op from JS and no registration.
#[test]
fn a_rust_root_mounts_renders_and_handles_events() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Tally>(|| TallyProps {
label: "Root".into(),
children: Children::default(),
}));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Root 0"]);
let host = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent: ROOT_ID,
child,
..
} => Some(*child),
_ => None,
})
.expect("the root's host is in the root view");
assert_eq!(host % 2, 1, "the core's own id");
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["Root 1"]);
}
#[test]
fn components_render_handle_events_and_place_children() {
let mut c = core_with_tally();
let prop = |name: &'static str, value| Op::SetProp {
id: 2,
prop: rust_prop::<TallyProps>(name, Some(value)),
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Tally>().into()),
},
prop("label", json!("Hits")),
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Hits 0"]);
// Expanded nodes have odd ids; the JS child sits where the render
// put `Children`, not in the host.
let holder = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent, child: 4, ..
} => Some(*parent),
_ => None,
})
.expect("JS child placed");
assert!(holder % 2 == 1 && holder != 2);
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { id: 2, .. }))
);
// A press on the host goes to the component, which emits and
// updates its text.
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
let events = js_events(&mut c);
assert_eq!(
events,
[(
2,
EventKind::NativeEvent,
EventPayload::Native {
name: "tap".into(),
data: json!({ "count": 1 })
}
)]
);
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Hits 1"]);
// A prop change reaches what reads it; only what changed is sent.
// Clearing a prop restores its default.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: rust_prop::<TallyProps>("label", None),
}],
);
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Taps 1"]);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { .. }))
);
// A value of the wrong type does not convert (JS warns and sends
// nothing); one decoded for another type is refused (and logged),
// nothing changes.
let specs = <TallyProps as Props>::spec(&mut crate::element::TsTypes::default());
let decode = specs
.iter()
.find(|p| p.name == "label")
.unwrap()
.decode
.unwrap();
assert!(crate::element::json_host::decode(decode, json!(3)).is_err());
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::RustProp("label", Some(crate::element::AnyValue::new(3.0f64))),
}],
);
assert!(c.commit().is_none());
// Unknown events on the host (no handler) are JS's.
assert!(!c.component_event(2, EventKind::Layout, &EventPayload::None));
// Releasing the host frees what it rendered; its JS child stays.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
let batch = c.commit().unwrap();
let deleted: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Delete { id } => Some(*id),
_ => None,
})
.collect();
assert!(deleted.contains(&2) && deleted.contains(&holder));
assert!(!deleted.contains(&4));
assert!(c.key(4).is_ok());
}
/// A header slot above its children.
#[derive(Clone, Copy, PartialEq, Props)]
struct CardProps {
header: crate::element::Prop<Option<Slot>>,
children: Children,
}
#[component]
fn Card(props: CardProps) -> impl IntoElement {
let filled = move || props.header.with(Option::is_some);
view().child(props.header.place(|h| h.h(px(44.0)))).child(
view()
.mt_0()
.style_when(filled, |v| v.mt_2())
.child(props.children),
)
}
/// Children above a footer slot.
#[derive(Clone, Copy, PartialEq, Props)]
struct PanelProps {
footer: crate::element::Prop<Option<Slot>>,
children: Children,
}
#[component]
fn Panel(props: PanelProps) -> impl IntoElement {
view()
.child(props.children)
.child(props.footer.place(|f| f))
}
/// JS children come after the view is made (lazy ones, later ones) and
/// go before what follows their place: a region (the footer's slot)
/// that is empty then, and its node once it fills.
#[test]
fn children_go_before_a_region_that_fills_later() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Panel>();
c.set_components(registry);
let child = |id| {
vec![
Op::Create { id, tag: Tag::View },
Op::Insert {
parent: 2,
child: id,
before: None,
},
]
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Panel>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
// The footer's region is empty: the child goes at the end.
apply(&mut c, child(8));
let batch = c.commit().expect("a child before an empty region");
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Insert {
parent: 2,
child: 8,
before: None
}
)));
// The footer fills; a later child goes before its node.
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::ComponentSlot("footer".into()),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
],
);
c.commit().expect("the footer filled");
apply(&mut c, child(10));
let batch = c.commit().unwrap();
assert!(
batch.items.iter().any(|i| matches!(
i,
MountItem::Insert {
parent: 2,
child: 10,
before: Some(4)
}
)),
"{:?}",
batch.items
);
}
/// Children and a footer slot in one region, above a node of the view.
#[component]
fn Ledger(props: PanelProps) -> impl IntoElement {
view()
.child(dynamic(move || {
vec![props.children.into_element(), props.footer.place(|f| f)]
}))
.child(view())
}
/// The ids of `parent`'s children in the core's tree, in order.
fn child_ids(c: &Core<FakeEngine>, parent: NodeId) -> Vec<NodeId> {
let key = c.key(parent).unwrap();
c.nodes[key as usize]
.children
.iter()
.map(|&k| c.nodes[k as usize].id)
.collect()
}
/// A host of component `C` at node 2, in the root.
fn mount_host<C: Component>() -> Core<FakeEngine> {
let mut c = core();
let mut registry = Registry::new();
registry.register::<C>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<C>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
c
}
/// JS child `id` of host 2, before its JS sibling `before`.
fn js_child(id: NodeId, before: Option<NodeId>) -> Vec<Op> {
vec![
Op::Create { id, tag: Tag::View },
Op::Insert {
parent: 2,
child: id,
before,
},
]
}
/// Fills host 2's footer slot with node 4 (holding node 6).
fn fill_footer() -> Vec<Op> {
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::ComponentSlot("footer".into()),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
]
}
/// A region inside a region resolves to what follows the outer one:
/// the JS children before it go before the view's node after both,
/// while the inner region (the footer) is empty and once it fills.
#[test]
fn children_in_a_region_go_before_the_node_after_it() {
let mut c = mount_host::<Ledger>();
let ids = child_ids(&c, 2);
assert_eq!(ids.len(), 1, "{ids:?}");
let tail = ids[0];
apply(&mut c, js_child(8, None));
c.commit().expect("a child before an empty region");
assert_eq!(child_ids(&c, 2), [8, tail]);
apply(&mut c, fill_footer());
c.commit().expect("the footer filled");
assert_eq!(child_ids(&c, 2), [8, 4, tail]);
apply(&mut c, js_child(10, None));
c.commit().unwrap();
assert_eq!(child_ids(&c, 2), [8, 10, 4, tail]);
}
/// A region that fills and empties again leaves the children before it
/// in place, and later ones go where they would have.
#[test]
fn children_stay_in_place_as_a_region_fills_and_empties() {
let mut c = mount_host::<Ledger>();
let tail = child_ids(&c, 2)[0];
apply(&mut c, js_child(8, None));
apply(&mut c, fill_footer());
c.commit().unwrap();
assert_eq!(child_ids(&c, 2), [8, 4, tail]);
apply(
&mut c,
vec![Op::Remove {
parent: 2,
child: 4,
}],
);
c.commit().expect("the footer emptied");
assert_eq!(child_ids(&c, 2), [8, tail]);
apply(&mut c, js_child(10, None));
c.commit().unwrap();
assert_eq!(child_ids(&c, 2), [8, 10, tail]);
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 4,
before: None,
}],
);
c.commit().expect("the footer filled again");
assert_eq!(child_ids(&c, 2), [8, 10, 4, tail]);
}
/// A child inserted before a JS sibling goes before it, wherever the
/// region after them is.
#[test]
fn children_go_before_the_sibling_js_names() {
let mut c = mount_host::<Panel>();
apply(&mut c, js_child(8, None));
apply(&mut c, fill_footer());
c.commit().unwrap();
assert_eq!(child_ids(&c, 2), [8, 4]);
apply(&mut c, js_child(10, Some(8)));
c.commit().unwrap();
assert_eq!(child_ids(&c, 2), [10, 8, 4]);
apply(&mut c, js_child(12, None));
c.commit().unwrap();
assert_eq!(child_ids(&c, 2), [10, 8, 12, 4]);
}
/// A footer slot whose presses show and hide a note after it.
#[component]
fn Toggler(props: PanelProps) -> impl IntoElement {
let shown = signal(false);
view()
.child(
props
.footer
.place(move |f| f.on_press(move |_: &()| shown.update(|s| *s = !*s))),
)
.child(when(shown, || view().h(px(10.0))))
}
/// What a view gives a slot (its handlers) stays while the node is its
/// slot, also once a region of the view runs again. They are on the
/// app's element in the slot's node (node 6, in holder 4).
#[test]
fn a_slots_handlers_outlive_the_views_regions() {
let mut c = mount_host::<Toggler>();
apply(&mut c, fill_footer());
c.commit().unwrap();
assert_eq!(child_ids(&c, 2), [4]);
let press = |c: &mut Core<FakeEngine>| {
c.component_event(6, EventKind::Press, &EventPayload::None);
let _ = c.commit();
};
press(&mut c);
assert_eq!(child_ids(&c, 2).len(), 2, "the note shows");
// The region ran again: the slot still hears its presses.
press(&mut c);
assert_eq!(child_ids(&c, 2), [4], "the note is gone");
press(&mut c);
assert_eq!(child_ids(&c, 2).len(), 2, "and shows again");
}
/// Counts the mouse coming over its root, which hears it itself.
#[component]
fn OwnHover() -> impl IntoElement {
let n = signal(0_u32);
view()
.on_mouse_enter(move |_: &MouseEvent| n.update(|n| *n += 1))
.child(text(move || format!("own {}", n.get())))
}
/// Places an `OwnHover` and counts the mouse coming over it too.
#[component]
fn GivenHover() -> impl IntoElement {
let n = signal(0_u32);
view()
.child(own_hover().on_mouse_enter(move |e: &MouseEvent| {
assert_eq!(e.position.x, px(3.0));
n.update(|n| *n += 1)
}))
.child(text(move || format!("given {}", n.get())))
}
fn mouse_at(x: f32) -> EventPayload {
EventPayload::Mouse(crate::MouseEvent::new(
crate::geometry::point(px(x), px(1.0)),
crate::geometry::point(px(x), px(1.0)),
crate::keymap::Modifiers::default(),
None,
))
}
#[test]
fn js_on_a_host_hears_the_mouse_its_root_hears_as_well() {
let mut c = mount_host::<OwnHover>();
// Only the root listens: the component handles it.
assert!(c.component_event(2, EventKind::MouseEnter, &mouse_at(3.0)));
apply(
&mut c,
vec![Op::Listen {
id: 2,
event: EventKind::MouseEnter,
enabled: true,
}],
);
// JS listens too: the root hears it, then JS.
assert!(!c.component_event(2, EventKind::MouseEnter, &mouse_at(3.0)));
let batch = c.commit().unwrap();
assert!(
texts(&batch).iter().any(|t| t == "own 2"),
"{:?}",
texts(&batch)
);
// JS stops: the root still listens.
apply(
&mut c,
vec![Op::Listen {
id: 2,
event: EventKind::MouseEnter,
enabled: false,
}],
);
c.commit();
assert!(events_of(&c, 2).contains(EventKind::MouseEnter));
}
#[test]
fn a_view_hears_the_mouse_over_a_component_it_places() {
let mut c = mount_host::<GivenHover>();
let nested = child_ids(&c, 2)[0];
assert!(events_of(&c, nested).contains(EventKind::MouseEnter));
// Its root hears it, then the view that placed it; JS does not.
assert!(c.component_event(nested, EventKind::MouseEnter, &mouse_at(3.0)));
let batch = c.commit().unwrap();
let shown = texts(&batch);
assert!(shown.iter().any(|t| t == "own 1"), "{shown:?}");
assert!(shown.iter().any(|t| t == "given 1"), "{shown:?}");
}
/// Places an `OwnHover` and hears the mouse moving over it until its
/// button is pressed.
#[component]
fn MaybeGiven() -> impl IntoElement {
let listen = signal(true);
let n = signal(0_u32);
view()
.child(dynamic(move || {
let el = own_hover();
if listen.get() {
el.on_mouse_move(move |_: &MouseEvent| n.update(|n| *n += 1))
} else {
el
}
}))
.child(
view()
.on_press(move || listen.set(false))
.child(text(move || format!("moves {}", n.get()))),
)
}
#[test]
fn a_component_stops_listening_when_the_view_stops_giving_a_listener() {
let mut c = mount_host::<MaybeGiven>();
let nested = child_ids(&c, 2)[0];
assert!(events_of(&c, nested).contains(EventKind::MouseMove));
assert!(c.component_event(nested, EventKind::MouseMove, &mouse_at(3.0)));
let batch = c.commit().unwrap();
assert!(texts(&batch).iter().any(|t| t == "moves 1"));
let button = child_ids(&c, 2)[1];
c.component_event(button, EventKind::Press, &EventPayload::None);
c.commit();
let nested = child_ids(&c, 2)[0];
assert!(!events_of(&c, nested).contains(EventKind::MouseMove));
// Its root's own stay.
assert!(events_of(&c, nested).contains(EventKind::MouseEnter));
}
/// Shows a menu of its own on a context menu when `own` is set.
#[derive(Clone, PartialEq, Props)]
struct MenuOwnerProps {
#[prop(default)]
own: crate::element::Prop<bool>,
}
#[component]
fn MenuOwner(props: MenuOwnerProps) -> impl IntoElement {
let n = signal(0_u32);
let el = view()
.h(px(20.0))
.child(text(move || format!("own menus {}", n.get())));
if props.own.get() {
el.on_context_menu(move |_: &crate::ContextMenuEvent| n.update(|n| *n += 1))
} else {
el
}
}
/// Places two `MenuOwner`s, one with a menu of its own, and listens to
/// both: their context menus, frames, and the mouse released.
#[component]
fn GivenMenus() -> impl IntoElement {
let menus = signal(Vec::<&'static str>::new());
let width = signal(0.0_f32);
let ups = signal(0_u32);
let given = move |name: &'static str| {
move |_: &crate::ContextMenuEvent| menus.update(|m| m.push(name))
};
view()
.child(
menu_owner()
.own(true)
.test_id("mine")
.on_context_menu(given("mine")),
)
.child(
menu_owner()
.on_context_menu(given("plain"))
.on_layout(move |b: &Bounds<Points>| width.set(b.size.width.0))
.on_mouse_up(move |e: &MouseEvent| {
assert_eq!(e.button, Some(crate::MouseButton::Right));
ups.update(|n| *n += 1)
}),
)
.child(text(move || {
format!(
"menus {} width {} ups {}",
menus.with(|m| m.join(",")),
width.get(),
ups.get()
)
}))
}
#[test]
fn a_view_hears_a_components_context_menu_unless_it_shows_its_own() {
let mut c = mount_host::<GivenMenus>();
let [mine, plain, ..] = child_ids(&c, 2)[..] else {
panic!("two components")
};
assert!(events_of(&c, mine).contains(EventKind::ContextMenu));
assert!(events_of(&c, plain).contains(EventKind::ContextMenu));
let menu = EventPayload::ContextMenu(crate::ContextMenuEvent::default());
// The component's own menu keeps it.
assert!(c.component_event(mine, EventKind::ContextMenu, &menu));
// One with none: the view placing it hears it.
assert!(c.component_event(plain, EventKind::ContextMenu, &menu));
let mut up = crate::MouseEvent::new(
crate::geometry::point(px(1.0), px(1.0)),
crate::geometry::point(px(1.0), px(1.0)),
crate::keymap::Modifiers::default(),
None,
);
up.button = Some(crate::MouseButton::Right);
assert!(c.component_event(plain, EventKind::MouseUp, &EventPayload::Mouse(up)));
let mut shown = Vec::new();
for _ in 0..4 {
for (id, kind, payload) in js_events(&mut c) {
c.component_event(id, kind, &payload);
}
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
}
}
assert!(shown.iter().any(|t| t == "own menus 1"), "{shown:?}");
assert_eq!(
shown
.iter()
.rev()
.find(|t| t.starts_with("menus"))
.map(String::as_str),
Some("menus plain width 320 ups 1"),
);
// The test id given it names its root.
let key = c.key(mine).unwrap() as usize;
assert_eq!(
c.nodes[key]
.props
.as_ref()
.and_then(|p| p.test_id.as_deref()),
Some("mine")
);
}
/// Measures its own root.
#[component]
fn Measured() -> impl IntoElement {
let w = signal(0.0_f32);
view()
.h(px(10.0))
.on_layout(move |b: &Bounds<Points>| w.set(b.size.width.0))
.child(text(move || format!("own width {}", w.get())))
}
/// Places a `Measured` and measures it too once its button is pressed.
#[component]
fn LateMeasure() -> impl IntoElement {
let on = signal(false);
let w = signal(0.0_f32);
view()
.child(dynamic(move || {
let el = measured();
if on.get() {
el.on_layout(move |b: &Bounds<Points>| w.set(b.size.width.0))
} else {
el
}
}))
.child(
view()
.on_press(move || on.set(true))
.child(text(move || format!("given width {}", w.get()))),
)
}
/// The listener comes with the element made again, whose node reports
/// its frame on listening, after its root's own listener.
#[test]
fn a_layout_listener_given_later_gets_the_frame_at_once() {
let mut c = mount_host::<LateMeasure>();
let settle = |c: &mut Core<FakeEngine>| {
let mut shown = Vec::new();
for _ in 0..4 {
for (id, kind, payload) in js_events(c) {
c.component_event(id, kind, &payload);
}
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
}
}
shown
};
let shown = settle(&mut c);
assert!(shown.iter().any(|t| t == "own width 320"), "{shown:?}");
let button = child_ids(&c, 2)[1];
c.component_event(button, EventKind::Press, &EventPayload::None);
let shown = settle(&mut c);
assert!(shown.iter().any(|t| t == "given width 320"), "{shown:?}");
}
#[component]
fn SlotLayoutRerun(props: PanelProps) -> impl IntoElement {
let count = signal(0_u32);
let retained: Listener<Bounds<Points>> =
(move |_: &Bounds<Points>| count.update(|n| *n += 1)).into();
view().child(dynamic(move || {
let current = count.get();
let measured = signal(0.0_f32);
let retained = retained.clone();
view()
.slot(props.footer.get(), move |slot| {
slot.on_layout(retained.clone())
.on_layout(move |frame: &Bounds<Points>| measured.set(frame.size.width.0))
})
.child(text(move || {
format!("slot count {current} width {}", measured.get())
}))
}))
}
#[test]
fn a_slots_new_run_gets_layout_without_replaying_retained_or_js_listeners() {
for js_listens in [false, true] {
let mut c = mount_host::<SlotLayoutRerun>();
apply(&mut c, fill_footer());
c.apply(style_op(
6,
&[
("width", StyleValue::Number(100.0)),
("height", StyleValue::Number(40.0)),
],
))
.unwrap();
if js_listens {
c.apply(Op::Listen {
id: 6,
event: EventKind::Layout,
enabled: true,
})
.unwrap();
}
c.commit().unwrap();
let mut shown = Vec::new();
let mut layout_events = 0;
// A retained listener being initialized again would keep rerunning the region.
for _ in 0..8 {
for (id, kind, payload) in js_events(&mut c) {
if id == 6 && kind == EventKind::Layout {
layout_events += 1;
}
c.component_event(id, kind, &payload);
}
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
}
}
assert_eq!(
shown
.iter()
.rev()
.find(|text| text.starts_with("slot count"))
.map(String::as_str),
Some("slot count 1 width 100")
);
assert_eq!(layout_events, 1);
assert!(js_events(&mut c).is_empty());
assert!(c.commit().is_none());
}
}
/// A trigger the app passes, made a disclosure button: its role, focus,
/// `disabled` and expanded state, and presses that flip it; the slot's
/// node padded.
#[derive(Clone, Copy, PartialEq, Props)]
struct DisclosureProps {
#[prop(default)]
disabled: crate::element::Prop<bool>,
trigger: crate::element::Prop<Option<Slot>>,
}
#[component]
fn Disclosure(props: DisclosureProps) -> impl IntoElement {
let open = signal(false);
view().child(props.trigger.place(move |t| {
t.px_2()
.role(crate::AccessibilityRole::Button)
.focusable(true)
.disabled(props.disabled)
.accessibility_state(move || crate::AccessibilityState {
expanded: Some(open.get()),
..crate::AccessibilityState::default()
})
.on_press(move |_: &()| open.update(|o| *o = !*o))
}))
}
/// Fills host 2's trigger: holder 4 holding the app's element 6 (with
/// classes, a label, a selected state and a press listener of JS's), as
/// the JS face does (the holder's content first).
fn fill_trigger() -> Vec<Op> {
use crate::{AccessibilityProp as A, AccessibilityState};
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::ComponentSlot("trigger".into()),
},
Op::Create {
id: 6,
tag: Tag::View,
},
class_op(
6,
"w-[40px] h-[20px] bg-white active:bg-black disabled:opacity-50",
),
Op::SetProp {
id: 6,
prop: Prop::Accessibility(A::Label(Some("Open".into()))),
},
Op::SetProp {
id: 6,
prop: Prop::Accessibility(A::State(AccessibilityState {
selected: true,
..AccessibilityState::default()
})),
},
Op::Listen {
id: 6,
event: EventKind::Press,
enabled: true,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
]
}
/// The core's view props of node `id`.
fn props_of(c: &Core<FakeEngine>, id: NodeId) -> crate::ViewProps {
let key = c.key(id).unwrap();
c.nodes[key as usize]
.props
.as_deref()
.cloned()
.unwrap_or_default()
}
/// The events node `id` listens to.
fn events_of(c: &Core<FakeEngine>, id: NodeId) -> EventMask {
c.nodes[c.key(id).unwrap() as usize].events
}
/// In a TSX app a slot's node is JS's holder of the app's JSX: the
/// slot's styles stay on it, and its props, listeners and bindings go
/// to the app's one element in it, combined with the app's own; its
/// bindings stay live (they were read once: an expanded state that
/// never followed the trigger's presses).
#[test]
fn a_slots_props_go_live_to_the_apps_element() {
use crate::AccessibilityRole;
let mut c = mount_host::<Disclosure>();
apply(&mut c, fill_trigger());
c.commit().unwrap();
let trigger = props_of(&c, 6);
assert_eq!(trigger.accessibility.role, AccessibilityRole::Button);
assert_eq!(trigger.accessibility.state.expanded, Some(false));
assert!(
trigger.accessibility.state.selected,
"the app's state stays"
);
assert_eq!(trigger.accessibility.label.as_deref(), Some("Open"));
assert_eq!(trigger.focusable, Some(true));
assert!(events_of(&c, 6).contains(EventKind::Press));
// The holder: the padding, nothing else.
let holder = props_of(&c, 4);
assert_eq!(holder.accessibility.role, AccessibilityRole::None);
assert_eq!(holder.accessibility.state.expanded, None);
assert_eq!(holder.focusable, None);
assert!(!events_of(&c, 4).contains(EventKind::Press));
let frame = c.nodes[c.key(6).unwrap() as usize].frame;
assert_eq!((frame.origin.x, frame.size.width), (px(8.0), px(40.0)));
// A press on the app's element runs the component's listener (and
// goes on to JS's: an id of JS's), and the expanded state follows.
let press = |c: &mut Core<FakeEngine>| {
assert!(!c.component_event(6, EventKind::Press, &EventPayload::None));
c.commit();
};
press(&mut c);
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(true));
assert!(props_of(&c, 6).accessibility.state.selected);
press(&mut c);
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(false));
press(&mut c);
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(true));
}
#[derive(Clone, Copy, PartialEq, Props)]
struct UndescribedTriggerProps {
trigger: crate::element::Prop<Option<Slot>>,
}
/// Names no description for its trigger, as a select the app gives
/// none.
#[component]
fn UndescribedTrigger(props: UndescribedTriggerProps) -> impl IntoElement {
view().child(
props.trigger.place(|t| {
t.accessibility_described_by_target(None::<crate::element::ElementTarget>)
}),
)
}
/// A slot's component that names no description leaves the app's
/// element the one the app names (its error line).
#[test]
fn a_slots_element_keeps_the_description_the_app_names() {
let mut c = mount_host::<UndescribedTrigger>();
let mut ops = fill_trigger();
ops.extend([
Op::Create {
id: 8,
tag: Tag::Text,
},
Op::CreateText {
id: 10,
text: "Required".into(),
},
Op::Insert {
parent: 8,
child: 10,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 8,
before: None,
},
Op::SetProp {
id: 6,
prop: Prop::Accessibility(crate::AccessibilityProp::DescribedBy(Some(
crate::element::ElementTarget::of_node(8),
))),
},
]);
apply(&mut c, ops);
c.commit().unwrap();
let trigger = props_of(&c, 6);
assert_eq!(trigger.accessibility.described_by, Some(8));
assert_eq!(
trigger.accessibility.description.as_deref(),
Some("Required")
);
}
#[derive(Clone, PartialEq, Props)]
struct AnchoredTriggerProps {
trigger: crate::element::Prop<Option<Slot>>,
}
/// Gives its trigger a ref and, once the trigger is pressed, shows a
/// 40 × 20 overlay 4 points below what the trigger draws, centered on
/// it (a popover's).
#[component]
fn AnchoredTrigger(props: AnchoredTriggerProps) -> impl IntoElement {
let anchor = element_ref();
let open = signal(false);
view()
.child(
props
.trigger
.place(move |t| t.element_ref(&anchor).on_press(move || open.set(true))),
)
.child(when(
move || open.get(),
move || {
overlay()
.anchor_content(&anchor)
.placement(Placement::Bottom)
.align(Align::Center)
.offset(px(4.0))
.w(px(40.0))
.h(px(20.0))
.child(text("pop"))
},
))
}
/// An overlay placed against what a slot's element draws goes by the
/// TSX app's element's own box, as by a Rust app's: here the component's
/// column stretches it to the root's 320 points and its minimum height
/// makes it 30 tall around a 50 × 10 box (with 10 points of padding on
/// each side), so the box around its children (0, 10, 70 × 10) is not
/// what shows.
#[test]
fn a_tsx_slots_element_anchors_overlays_by_its_own_box() {
let mut c = mount_host::<AnchoredTrigger>();
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::ComponentSlot("trigger".into()),
},
Op::Create {
id: 6,
tag: Tag::View,
},
class_op(6, "min-h-[30px] px-[10px] justify-center"),
Op::Create {
id: 8,
tag: Tag::View,
},
class_op(8, "w-[50px] h-[10px]"),
Op::Insert {
parent: 6,
child: 8,
before: None,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
c.commit().unwrap();
assert_eq!(
c.components.adopted.get(&6),
Some(&4),
"the app's element takes the slot's ref"
);
let trigger = c.measure(6).expect("laid out");
assert_eq!(
(trigger.page, trigger.frame.size),
(Point::new(px(0.0), px(0.0)), size_pt(320.0, 30.0))
);
c.component_event(6, EventKind::Press, &EventPayload::None);
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id, text, .. } if text.text == "pop" => Some(*id),
_ => None,
})
.expect("shown");
let parent = c.nodes[c.key(text).unwrap() as usize].parent;
let pop = c.nodes[parent as usize].id;
// Centered below the element (0, 0, 320 × 30): not at (15, 24),
// below the box around its children.
assert_eq!(frame_of(&batch, pop), Some(rect(140.0, 34.0, 40.0, 20.0)));
}
/// On the app's element the component's props win and the app's fill
/// in the rest; `disabled` holds when either sets it, and the element's
/// own `disabled:` and `active:` classes follow it; both sides'
/// listeners stay. When the element leaves the slot, the app's own
/// props and listeners are back on it and the holder takes the
/// component's.
#[test]
fn the_apps_element_combines_its_props_with_the_slots() {
use crate::{AccessibilityProp as A, AccessibilityRole, AccessibilityState};
let mut c = mount_host::<Disclosure>();
apply(&mut c, fill_trigger());
c.commit().unwrap();
// JS changes the element: its label shows, its role and listener
// join the component's (which win), its state combines.
apply(
&mut c,
vec![
Op::SetProp {
id: 6,
prop: Prop::Accessibility(A::Label(Some("Close".into()))),
},
Op::SetProp {
id: 6,
prop: Prop::Accessibility(A::Role(AccessibilityRole::Link)),
},
Op::SetProp {
id: 6,
prop: Prop::Accessibility(A::State(AccessibilityState {
selected: true,
expanded: Some(true),
..AccessibilityState::default()
})),
},
Op::Listen {
id: 6,
event: EventKind::Press,
enabled: false,
},
],
);
c.commit();
let trigger = props_of(&c, 6);
assert_eq!(trigger.accessibility.label.as_deref(), Some("Close"));
assert_eq!(trigger.accessibility.role, AccessibilityRole::Button);
assert_eq!(trigger.accessibility.state.expanded, Some(false));
assert!(trigger.accessibility.state.selected);
assert!(
events_of(&c, 6).contains(EventKind::Press),
"the component still listens"
);
// Pressed: the element's own `active:`.
c.set_states(6, crate::tailwind::state::PRESSED);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 6).unwrap().background_color,
Color(0x0000_00ff)
);
c.set_states(6, 0);
c.commit();
// The component disables it: its `disabled:` classes, no presses
// mounted, disabled for screen readers.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: rust_prop::<DisclosureProps>("disabled", Some(json!(true))),
}],
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 6).unwrap().opacity, 0.5);
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Events { id: 6, events } if !events.contains(EventKind::Press)
)));
assert!(props_of(&c, 6).accessibility.state.disabled);
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: rust_prop::<DisclosureProps>("disabled", Some(json!(false))),
}],
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 6).unwrap().opacity, 1.0);
// Another element joins it: the slot's node holds two, so the
// holder takes the component's part, and the app's element has its
// own props and listeners back.
apply(
&mut c,
vec![
Op::Create {
id: 8,
tag: Tag::View,
},
Op::Insert {
parent: 4,
child: 8,
before: None,
},
],
);
c.commit();
let trigger = props_of(&c, 6);
assert_eq!(trigger.accessibility.role, AccessibilityRole::Link);
assert_eq!(trigger.accessibility.state.expanded, Some(true));
assert_eq!(trigger.focusable, None);
assert!(!events_of(&c, 6).contains(EventKind::Press));
let holder = props_of(&c, 4);
assert_eq!(holder.accessibility.role, AccessibilityRole::Button);
assert_eq!(holder.focusable, Some(true));
assert!(events_of(&c, 4).contains(EventKind::Press));
assert!(!c.component_event(6, EventKind::Press, &EventPayload::None));
c.component_event(4, EventKind::Press, &EventPayload::None);
c.commit();
assert_eq!(props_of(&c, 4).accessibility.state.expanded, Some(true));
// It leaves: the component's part is on the app's element again,
// live.
apply(
&mut c,
vec![Op::Remove {
parent: 4,
child: 8,
}],
);
c.commit();
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(true));
assert_eq!(
props_of(&c, 6).accessibility.role,
AccessibilityRole::Button
);
assert_eq!(props_of(&c, 4).accessibility.role, AccessibilityRole::None);
assert!(!events_of(&c, 4).contains(EventKind::Press));
c.component_event(6, EventKind::Press, &EventPayload::None);
c.commit();
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(false));
// The app empties the slot: its element keeps its own props alone.
apply(
&mut c,
vec![Op::Remove {
parent: 4,
child: 6,
}],
);
c.commit();
let trigger = props_of(&c, 6);
assert_eq!(trigger.accessibility.role, AccessibilityRole::Link);
assert_eq!(trigger.accessibility.state.expanded, Some(true));
assert_eq!(trigger.focusable, None);
assert!(!events_of(&c, 6).contains(EventKind::Press));
assert_eq!(props_of(&c, 4).accessibility.role, AccessibilityRole::None);
assert!(!c.component_event(6, EventKind::Press, &EventPayload::None));
}
/// A component's host as the app's element in a slot (a `Button` as a
/// popover's trigger) takes the slot's props and listeners: its root is
/// the innermost press target, so a press the holder took would never
/// come. A press runs the slot's listener, then the host's own; when
/// the host goes, the holder takes the slot's part.
#[test]
fn a_components_host_in_a_slot_takes_its_props() {
use crate::AccessibilityRole;
let mut c = core();
let mut registry = Registry::new();
registry.register::<Disclosure>();
registry.register::<Tally>();
c.set_components(registry);
let component = |id, name: &str| Op::SetProp {
id,
prop: Prop::Component(name.into()),
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
component(2, std::any::type_name::<Disclosure>()),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::ComponentSlot("trigger".into()),
},
Op::Create {
id: 6,
tag: Tag::View,
},
component(6, std::any::type_name::<Tally>()),
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
c.commit().unwrap();
let trigger = props_of(&c, 6);
assert_eq!(trigger.accessibility.role, AccessibilityRole::Button);
assert_eq!(trigger.accessibility.state.expanded, Some(false));
assert_eq!(trigger.focusable, Some(true));
assert!(events_of(&c, 6).contains(EventKind::Press));
assert_eq!(props_of(&c, 4).accessibility.role, AccessibilityRole::None);
assert!(!events_of(&c, 4).contains(EventKind::Press));
js_events(&mut c);
c.component_event(6, EventKind::Press, &EventPayload::None);
c.commit();
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(true));
assert!(
js_events(&mut c).iter().any(|(id, _, payload)| *id == 6
&& matches!(payload, EventPayload::Native { name, .. } if &**name == "tap")),
"the host's own listener runs too"
);
c.component_event(6, EventKind::Press, &EventPayload::None);
c.commit();
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(false));
apply(&mut c, vec![Op::Release { id: 6 }]);
c.commit();
assert_eq!(
props_of(&c, 4).accessibility.role,
AccessibilityRole::Button
);
assert!(events_of(&c, 4).contains(EventKind::Press));
c.component_event(4, EventKind::Press, &EventPayload::None);
c.commit();
assert_eq!(props_of(&c, 4).accessibility.state.expanded, Some(true));
}
/// A tally as its view's root: its node is made under the tally's id.
#[component]
fn RootedTally() -> impl IntoElement {
tally()
}
/// A component's host in a slot whose view's root is another component
/// (a library button made of a base one) takes the slot's listeners
/// too: its view is made after the slot gave the host its props, under
/// the inner component's id, and they follow it there. A press runs
/// the slot's listener, then the inner component's own.
#[test]
fn a_rooted_components_host_in_a_slot_takes_its_listeners() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Disclosure>();
registry.register::<RootedTally>();
c.set_components(registry);
let component = |id, name: &str| Op::SetProp {
id,
prop: Prop::Component(name.into()),
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
component(2, std::any::type_name::<Disclosure>()),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::ComponentSlot("trigger".into()),
},
Op::Create {
id: 6,
tag: Tag::View,
},
component(6, std::any::type_name::<RootedTally>()),
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
c.commit().unwrap();
assert!(events_of(&c, 6).contains(EventKind::Press));
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(false));
c.component_event(6, EventKind::Press, &EventPayload::None);
let shown = texts(&c.commit().unwrap());
assert_eq!(props_of(&c, 6).accessibility.state.expanded, Some(true));
assert!(shown.contains(&"Taps 1".into()), "{shown:?}");
}
#[test]
fn slots_are_the_glues_nodes_placed_by_the_render() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Card>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Card>().into()),
},
// The glue's node for `header`, then its JSX.
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::ComponentSlot("header".into()),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
// Children go before the slot's node (the anchor).
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(8, &[("height", StyleValue::Number(10.0))]),
Op::Insert {
parent: 2,
child: 8,
before: Some(4),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
// The slot's node is the header element (in the host, 44pt tall).
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Insert {
parent: 2,
child: 4,
..
}
)));
assert_eq!(frame_of(&batch, 4).map(|f| f.size.height.0), Some(44.0));
// The children sit below it, after `mt_2` (the slot is filled).
let holder = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent, child: 8, ..
} => Some(*parent),
_ => None,
})
.unwrap();
assert_eq!(frame_of(&batch, holder).map(|f| f.origin.y.0), Some(52.0));
// Emptying the slot: no header, `mt_0`.
apply(
&mut c,
vec![Op::Remove {
parent: 4,
child: 6,
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: 4 }))
);
assert_eq!(frame_of(&batch, holder).map(|f| f.origin.y.0), Some(0.0));
}
/// Renders a Tally and counts its taps.
#[derive(Clone, PartialEq, Props)]
struct OuterProps {}
#[derive(Event)]
enum OuterEvent {
InnerTap(u32),
}
#[component]
fn Outer(_props: OuterProps, cx: Scope<OuterEvent>) -> impl IntoElement {
let inner_taps = signal(0);
view()
.child(text(move || format!("outer {}", inner_taps.get())))
.child(tally().label("In").on_tap(move |_: &TallyEvent| {
inner_taps.update(|t| *t += 1);
cx.emit(OuterEvent::InnerTap(inner_taps.get_untracked()));
}))
}
#[test]
fn nested_components_render_and_report_to_their_parent() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Tally>().register::<Outer>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Outer>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let mut shown = texts(&batch);
shown.sort();
assert_eq!(shown, ["In 0", "outer 0"]);
// The nested Tally's host: the node listening to presses.
let inner = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap();
assert!(c.component_event(inner, EventKind::Press, &EventPayload::None));
let events = js_events(&mut c);
// JS hears the outer component's event, not the inner one.
assert_eq!(
events,
[(
2,
EventKind::NativeEvent,
EventPayload::Native {
name: "innerTap".into(),
data: json!({ "value": 1 })
}
)]
);
let mut shown = texts(&c.commit().unwrap());
shown.sort();
assert_eq!(shown, ["In 1", "outer 1"]);
}
#[test]
fn the_apps_class_goes_last_and_unknown_components_render_nothing() {
let mut c = core_with_tally();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Tally>().into()),
},
Op::SetProp {
id: 2,
prop: Prop::Class("p-8".into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::SetProp {
id: 6,
prop: Prop::Component("test.missing".into()),
},
Op::Insert {
parent: ROOT_ID,
child: 6,
before: None,
},
],
);
let batch = c.commit().unwrap();
// `p-8` (32pt) wins over the component's `p_2`: the text sits 32pt in.
let text_id = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id, .. } => Some(*id),
_ => None,
})
.unwrap();
let frame = frame_of(&batch, text_id).unwrap();
assert_eq!((frame.origin.x.0, frame.origin.y.0), (32.0, 32.0));
// The unknown one is an empty view.
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { id: 6, .. }))
);
}
/// A theme-colored swatch that darkens while pressed.
#[derive(Clone, PartialEq, Props)]
struct SwatchProps {}
#[component]
fn Swatch(_props: SwatchProps) -> impl IntoElement {
view()
.size_10()
.bg(move || tokens().color("primary").unwrap())
.active(|s| s.bg(rgb(0xff0000)))
}
#[test]
fn theme_colors_and_press_styles_switch_natively() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Swatch>().tokens_from(test_tokens);
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Swatch>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let background = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewStyle { id: 2, style } => Some(style.background_color),
_ => None,
})
};
let primary = token("primary");
let batch = c.commit().unwrap();
assert_eq!(background(&batch), Some(Color::from(primary.light)));
assert_eq!(frame_of(&batch, 2).map(|f| f.size.width.0), Some(40.0));
// The platform reports presses on it (`active`).
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::TrackStates { id: 2, states } if states & crate::tailwind::state::PRESSED != 0
)));
// Dark appearance: restyled natively.
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
let batch = c.commit().unwrap();
assert_eq!(background(&batch), Some(Color::from(primary.dark)));
c.set_states(2, crate::tailwind::state::PRESSED);
let batch = c.commit().unwrap();
assert_eq!(background(&batch), Some(Color(0xff0000ff)));
}
/// A selected state whose style is the app's (as `nsh_base::Button`'s).
#[derive(Clone, PartialEq, Props)]
struct PillProps {
#[prop(default)]
selected: crate::element::Prop<bool>,
#[prop(default)]
selected_style: crate::element::Prop<crate::element::Style>,
}
#[component]
fn Pill(props: PillProps) -> impl IntoElement {
view()
.size_10()
.accessibility_state(move || crate::AccessibilityState {
selected: props.selected.get(),
..crate::AccessibilityState::default()
})
.selected_style(props.selected_style)
}
/// A selected pill styled with a theme color and an opacity a press
/// changes, through its style prop's closure.
#[component]
fn Pills() -> impl IntoElement {
let dim = signal(false);
view()
.on_press(move || dim.set(true))
.child(pill().selected(true).selected_style(move |s| {
s.bg(move || tokens().color("primary").unwrap())
.opacity(move || if dim.get() { 0.5_f32 } else { 1.0 })
}))
}
#[test]
fn a_style_prop_set_with_a_closure_follows_the_theme_and_its_signals() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Pills>().tokens_from(test_tokens);
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Pills>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let styled = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewStyle { id, style } if *id != 2 => {
Some((style.background_color, style.opacity))
}
_ => None,
})
};
let primary = token("primary");
let batch = c.commit().unwrap();
assert_eq!(styled(&batch), Some((Color::from(primary.light), 1.0)));
// Dark appearance: the theme color switches natively.
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
let batch = c.commit().unwrap();
assert_eq!(styled(&batch), Some((Color::from(primary.dark), 1.0)));
// What the closure's bindings read changes it.
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(styled(&batch), Some((Color::from(primary.dark), 0.5)));
}
/// A part that shows text, styled by the app (as `nsh_base::NumberInput`'s
/// field).
#[derive(Clone, PartialEq, Props)]
struct CaptionProps {
#[prop(default)]
text_style: crate::element::Prop<crate::element::TextPartStyle>,
}
#[component]
fn Caption(props: CaptionProps) -> impl IntoElement {
view().child(text("Caption").inline_style(move || props.text_style.get()))
}
#[component]
fn Captioned() -> impl IntoElement {
caption().text_style(|s| s.opacity(0.5))
}
#[test]
fn a_text_parts_style_prop_takes_a_closure_and_reaches_the_part() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Captioned>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Captioned>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::ViewStyle { id, style } if *id != 2 && style.opacity == 0.5
)));
let mut types = crate::element::TsTypes::default();
assert_eq!(
<crate::element::TextPartStyle as crate::element::JsValue>::ts_type(&mut types),
"StyleProp<TextStyle>"
);
}
#[test]
fn the_host_theme_wins_over_the_apps_until_cleared() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Swatch>().tokens_from(test_tokens);
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Swatch>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let background = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewStyle { id: 2, style } => Some(style.background_color),
_ => None,
})
};
let themed = |hex: u32| {
tokens_with(&[("primary", rgb(hex).into())]).over(&test_tokens(None).unwrap().0)
};
c.commit().unwrap();
c.set_host_tokens(Some(themed(0x00ff00)));
assert_eq!(
c.commit().as_ref().and_then(background),
Some(Color::from(rgb(0x00ff00)))
);
// The app's own theme (`uiTheme`) waits behind the host's.
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::UiTheme(r##"{ "primary": "#0000ff" }"##.into()),
}],
);
assert_eq!(c.commit().as_ref().and_then(background), None);
c.set_host_tokens(None);
assert_eq!(
c.commit().as_ref().and_then(background),
Some(Color::from(rgb(0x0000ff)))
);
// Setting the same theme again renders nothing.
c.set_tokens(themed(0x0000ff));
assert_eq!(c.commit().as_ref().and_then(background), None);
}
#[test]
fn classes_naming_theme_tokens_follow_the_theme() {
let mut c = core();
view_with_classes(&mut c, 2, "w-10 h-10 bg-primary");
view_with_classes(&mut c, 4, "w-10 h-10 bg-chart-up");
view_with_classes(&mut c, 6, "w-10 h-10 bg-red-500");
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color::from(token("primary").light)
);
// Not a token of the app's theme.
assert!(view_style_of(&batch, 4).is_none());
let host = tokens_with(&[
("primary", AdaptiveColor::rgb(0x00ff00, 0x004400)),
("chart-up", rgb(0x0000ff).into()),
]);
c.set_host_tokens(Some(host.clone()));
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color::from(rgb(0x00ff00))
);
assert_eq!(
view_style_of(&batch, 4).unwrap().background_color,
Color::from(rgb(0x0000ff))
);
assert!(view_style_of(&batch, 6).is_none());
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color::from(rgb(0x004400))
);
// New values of the same tokens: only their classes are resolved.
let mut changed = host;
changed.set_color("primary", rgb(0xff00ff).into());
c.set_host_tokens(Some(changed));
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color::from(rgb(0xff00ff))
);
assert!(view_style_of(&batch, 4).is_none());
assert!(view_style_of(&batch, 6).is_none());
}
#[test]
fn an_unknown_token_substitution_recovers_when_its_value_becomes_valid() {
let mut tokens = crate::element::tokens::sample();
tokens.set_number("width", -1.0);
let mut c = core();
c.set_tokens(tokens.clone());
view_with_classes(&mut c, 2, "w-(--width)");
let batch = c.commit().unwrap();
let before = frame_of(&batch, 2).expect("the view is framed").size.width;
assert_ne!(before, px(4.0));
let key = c.key(2).unwrap();
assert_ne!(
c.nodes[key as usize].classes.as_ref().unwrap().deps() & crate::tailwind::deps::THEME,
0
);
tokens.set_number("width", 4.0);
c.set_tokens(tokens);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 2)
.expect("the valid token restyles the view")
.size
.width,
px(4.0)
);
}
#[test]
fn the_apps_token_classes_on_a_component_follow_the_theme() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Swatch>().tokens_from(test_tokens);
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Swatch>().into()),
},
Op::SetProp {
id: 2,
prop: Prop::Class("bg-chart-up".into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
c.set_host_tokens(Some(tokens_with(&[("chart-up", rgb(0x0000ff).into())])));
let batch = c.commit().unwrap();
// The app's class wins over the component's own background.
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color::from(rgb(0x0000ff))
);
}
#[test]
fn a_host_theme_keeps_the_apps_own_tokens() {
let mut c = core();
let mut registry = Registry::new();
registry.tokens_from(test_tokens);
c.set_components(registry);
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::UiTheme(r##"{ "chart-up": "#0000ff" }"##.into()),
}],
);
view_with_classes(&mut c, 2, "w-10 h-10 bg-chart-up");
c.set_host_tokens(Some(crate::element::tokens::sample()));
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color::from(rgb(0x0000ff))
);
}
/// Wraps each JS child in a padded row.
#[derive(Clone, PartialEq, Props)]
struct RowsProps {
children: Children,
}
#[component]
fn Rows(props: RowsProps) -> impl IntoElement {
view().children_each(props.children, |child, at| {
view()
.p_1()
.style_when(move || !at.is_first(), |v| v.mt_2())
.style_when(move || at.is_last(), |v| v.pb_2())
.child(child)
})
}
#[test]
fn children_each_wraps_every_js_child_and_follows_changes() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Rows>();
c.set_components(registry);
let child = |id: NodeId| {
vec![
Op::Create { id, tag: Tag::View },
style_op(id, &[("height", StyleValue::Number(10.0))]),
]
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Rows>().into()),
},
];
ops.extend(child(4));
ops.extend(child(6));
ops.extend([
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
]);
apply(&mut c, ops);
let batch = c.commit().unwrap();
let wrapper_of = |batch: &MountBatch, id: NodeId| {
batch.items.iter().find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == id => Some(*parent),
_ => None,
})
};
let (w4, w6) = (
wrapper_of(&batch, 4).unwrap(),
wrapper_of(&batch, 6).unwrap(),
);
assert!(w4 % 2 == 1 && w6 % 2 == 1 && w4 != w6);
// 4pt padding, 10pt children, 8pt between the rows.
assert_eq!(
frame_of(&batch, w4).map(|f| (f.origin.y.0, f.size.height.0)),
Some((0.0, 18.0))
);
// The last has 8pt below.
assert_eq!(
frame_of(&batch, w6).map(|f| (f.origin.y.0, f.size.height.0)),
Some((26.0, 22.0))
);
// A child inserted first gets its own wrapper; the others keep theirs
// and move down (the second row now has the margin).
let mut ops = child(8);
ops.push(Op::Insert {
parent: 2,
child: 8,
before: Some(4),
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
let w8 = wrapper_of(&batch, 8).unwrap();
assert!(![w4, w6].contains(&w8));
assert_eq!(frame_of(&batch, w8).map(|f| f.origin.y.0), Some(0.0));
assert_eq!(frame_of(&batch, w4).map(|f| f.origin.y.0), Some(26.0));
assert!(wrapper_of(&batch, 4).is_none() && wrapper_of(&batch, 6).is_none());
// A child moved (inserted again, as a keyed `<Each>` moves its row)
// keeps its wrapper and stays in it; the wrapper moves.
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 8,
before: None,
}],
);
let batch = c.commit().unwrap();
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == 8)),
"the moved child stays in its wrapper"
);
assert_eq!(frame_of(&batch, w8).map(|f| f.origin.y.0), Some(52.0));
assert_eq!(frame_of(&batch, w4).map(|f| f.origin.y.0), Some(0.0));
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 8,
before: Some(4),
}],
);
c.commit().unwrap();
// A child removed takes its wrapper away; the child itself stays JS's.
apply(
&mut c,
vec![Op::Remove {
parent: 2,
child: 4,
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == w4))
);
assert!(c.key(4).is_ok());
assert_eq!(frame_of(&batch, w6).map(|f| f.origin.y.0), Some(26.0));
}
thread_local! {
/// What [`Labels`] was told of each child it placed, in order.
static TOLD: std::cell::RefCell<Vec<bool>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Wraps each text child in a text of its own (its label) and places
/// any other child as it is.
#[derive(Clone, PartialEq, Props)]
struct LabelsProps {
children: Children,
}
#[component]
fn Labels(props: LabelsProps) -> impl IntoElement {
view().children_each(props.children, |child, _| {
TOLD.with(|t| t.borrow_mut().push(child.is_text()));
if child.is_text() {
crate::element::text("").child(child).into_element()
} else {
child.into_element()
}
})
}
#[test]
fn children_each_tells_text_children_from_other_elements() {
TOLD.with(|t| t.borrow_mut().clear());
let mut c = core();
let mut registry = Registry::new();
registry.register::<Labels>();
c.set_components(registry);
// `<Labels>Save<Text>As</Text><View /></Labels>`.
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Labels>().into()),
},
Op::CreateText {
id: 4,
text: "Save".into(),
},
Op::Create {
id: 6,
tag: Tag::Text,
},
Op::CreateText {
id: 8,
text: "As".into(),
},
Op::Insert {
parent: 6,
child: 8,
before: None,
},
Op::Create {
id: 10,
tag: Tag::View,
},
style_op(10, &[("width", StyleValue::Number(16.0))]),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 10,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
// The string and the `Text` are text; the view is not.
assert_eq!(TOLD.with(|t| t.take()), [true, true, false]);
// The view is placed as it is, in the component's view.
let parent_of = |batch: &MountBatch, id: NodeId| {
batch.items.iter().find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == id => Some(*parent),
_ => None,
})
};
assert_eq!(parent_of(&batch, 10), Some(2));
// A view inserted later is not text either; a string is.
apply(
&mut c,
vec![
Op::Create {
id: 12,
tag: Tag::View,
},
Op::Insert {
parent: 2,
child: 12,
before: Some(4),
},
Op::CreateText {
id: 14,
text: "Later".into(),
},
Op::Insert {
parent: 2,
child: 14,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(TOLD.with(|t| t.take()), [false, true]);
assert_eq!(parent_of(&batch, 12), Some(2));
// The earlier unwrapped view stays placed rather than being dropped
// when siblings change around it.
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == 10)),
"kept unwrapped child must not be detached"
);
let k2 = c.key(2).unwrap() as usize;
assert!(
c.nodes[k2]
.children
.iter()
.any(|&k| c.nodes[k as usize].id == 10),
"kept unwrapped child stays attached to the component's view"
);
// Removing the inserted sibling keeps the original unwrapped child too.
apply(
&mut c,
vec![Op::Remove {
parent: 2,
child: 12,
}],
);
let batch = c.commit().unwrap();
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == 10)),
"kept unwrapped child must not be detached when a sibling leaves"
);
let k2 = c.key(2).unwrap() as usize;
assert!(
c.nodes[k2]
.children
.iter()
.any(|&k| c.nodes[k as usize].id == 10),
"kept unwrapped child stays attached after a sibling leaves"
);
}
/// Ticks every 20ms from `start` until 3, then reports it; shows
/// whether the window is wide.
#[derive(Clone, Copy, PartialEq, Props)]
struct ClockProps {
#[prop(default)]
start: crate::element::Prop<u32>,
}
#[derive(Event)]
enum ClockEvent {
Done,
}
#[component]
fn Clock(props: ClockProps, cx: Scope<ClockEvent>) -> impl IntoElement {
let ticks = signal(props.start.get_untracked());
// A new start starts again from it.
effect(move || ticks.set(props.start.get()));
let timer = stored(None::<Spawned<()>>);
timer.replace(Some(set_interval(
std::time::Duration::from_millis(20),
move || {
ticks.update(|t| *t += 1);
if ticks.get_untracked() == 3 {
cx.emit(ClockEvent::Done);
// Cancelling the task stops it (`clearInterval`).
if let Some(timer) = timer.replace(None) {
timer.cancel();
}
}
},
)));
view().child(text(move || {
let width = if window().width > Points(500.0) {
"wide"
} else {
"narrow"
};
format!("{} {width}", ticks.get())
}))
}
/// Fetches a value on the runtime's threads, then shows it.
#[derive(Clone, PartialEq, Props)]
struct LoaderProps {}
#[component]
fn Loader(_props: LoaderProps) -> impl IntoElement {
let value = signal(None::<u64>);
spawn(async move {
// tokio's ecosystem: a `Send` future on the runtime, a timer.
let loaded = background(async { (1..=10u64).product::<u64>() })
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
value.set(Some(loaded));
});
view().child(text(move || match value.get() {
Some(v) => format!("loaded {v}"),
None => "loading".to_owned(),
}))
}
/// A resource through its states, driven by a task of its own: a slow
/// load overtaken, a refetch, a failure, a value set here, no source.
#[derive(Clone, PartialEq, Props)]
struct ProfileProps {}
#[component]
fn Profile(_props: ProfileProps) -> impl IntoElement {
let id = signal(Some(1u32));
let profile = resource(
move || id.get(),
|id, info: crate::element::ResourceInfo| async move {
// The first load is slow: the second overtakes it.
let ms = if id == 1 { 80 } else { 5 };
timer(std::time::Duration::from_millis(ms)).await;
if id == 3 {
Err(format!("no user {id}"))
} else {
Ok(format!(
"user {id}{}",
if info.refetching { " again" } else { "" }
))
}
},
);
spawn(async move {
let settled = || async {
while profile.loading() {
timer(std::time::Duration::from_millis(2)).await;
}
};
timer(std::time::Duration::from_millis(10)).await;
id.set(Some(2));
settled().await;
profile.refetch();
settled().await;
id.set(Some(3));
settled().await;
profile.mutate("local".into());
id.set(None);
});
view().child(text(move || {
format!(
"{:?}|{}|{}",
profile.state(),
profile.get().unwrap_or_default(),
profile.error().unwrap_or_default()
)
}))
}
#[test]
fn resources_load_refresh_fail_and_count_the_latest_load_only() {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_time()
.build()
.unwrap();
let mut c = core();
let mut registry = Registry::new();
registry.register::<Profile>();
c.set_components(registry);
c.set_task_runtime(runtime.handle().clone());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Profile>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let mut shown = texts(&c.commit().unwrap());
shown.extend(run_until(&mut c, |s| s.iter().any(|t| t == "Ready|local|")));
shown.dedup();
assert_eq!(
shown,
[
"Pending||",
// The slow first load never shows: the second replaced it.
"Ready|user 2|",
"Refreshing|user 2|",
"Ready|user 2 again|",
"Refreshing|user 2 again|",
// A failure keeps the value.
"Errored|user 2 again|no user 3",
// A value set here clears the error; no source loads nothing.
"Ready|local|",
]
);
assert_eq!(c.components.executor.task_count(), 0);
}
/// Runs the tasks and commits until `done` holds of what was shown.
fn run_until(c: &mut Core<FakeEngine>, done: impl Fn(&[String]) -> bool) -> Vec<String> {
let mut shown = Vec::new();
let end = std::time::Instant::now() + std::time::Duration::from_secs(5);
while std::time::Instant::now() < end {
c.run_component_tasks();
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
if done(&shown) {
return shown;
}
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
panic!("not done: {shown:?}");
}
#[test]
fn state_tasks_props_and_the_environment() {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_time()
.build()
.unwrap();
let mut c = core();
let mut registry = Registry::new();
registry.register::<Clock>().register::<Loader>();
c.set_components(registry);
c.set_task_runtime(runtime.handle().clone());
let mount = |c: &mut Core<FakeEngine>, id: NodeId, name: &str| {
apply(
c,
vec![
Op::Create { id, tag: Tag::View },
Op::SetProp {
id,
prop: Prop::Component(name.into()),
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
],
)
};
mount(&mut c, 2, std::any::type_name::<Clock>());
assert_eq!(texts(&c.commit().unwrap()), ["0 narrow"]);
// The interval (a task: a timer, then an update) ticks to 3,
// reports it and stops.
let shown = run_until(&mut c, |s| s.iter().any(|t| t == "3 narrow"));
assert!(shown.starts_with(&["1 narrow".to_owned()]));
let events = js_events(&mut c);
assert!(
matches!(&events[..], [(2, EventKind::NativeEvent, EventPayload::Native { name, .. })] if &**name == "done")
);
std::thread::sleep(std::time::Duration::from_millis(60));
c.run_component_tasks();
assert!(c.commit().is_none(), "stopped");
// A prop change reaches what reads it.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: rust_prop::<ClockProps>("start", Some(json!(10))),
}],
);
assert_eq!(texts(&c.commit().unwrap()), ["10 narrow"]);
// What a binding read of the environment updates it; the rest does
// not.
let env = crate::element::Environment {
window: size_pt(390.0, 844.0),
..Default::default()
};
c.set_environment(crate::element::Environment {
keyboard_height: px(300.0),
..env
});
assert!(c.commit().is_none());
c.set_viewport(size_pt(800.0, 600.0));
assert!(texts(&c.commit().unwrap()).contains(&"10 wide".to_owned()));
// A task with background work and a tokio timer.
mount(&mut c, 4, std::any::type_name::<Loader>());
assert!(texts(&c.commit().unwrap()).contains(&"loading".to_owned()));
run_until(&mut c, |s| s.iter().any(|t| t == "loaded 3628800"));
// A released component's tasks end with it.
mount(&mut c, 6, std::any::type_name::<Clock>());
c.commit();
assert_eq!(c.components.executor.task_count(), 1);
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 6,
},
Op::Release { id: 6 },
],
);
c.commit();
assert_eq!(c.components.executor.task_count(), 0);
}
/// A form: an input it controls, a scroll view, a modal while the
/// name is long enough, a canvas drawing its length.
#[component]
fn Form(_props: FormProps) -> impl IntoElement {
let name = signal(String::new());
let focused = signal(false);
let field = element_ref();
view()
.child(
scroll().bounces(false).child(
input()
.element_ref(&field)
.value(move || name.get())
.placeholder(move || {
if name.with(String::is_empty) {
"Name"
} else {
""
}
})
.on_change(move |text: &str| name.set(text.to_owned()))
.on_focus(move |_: &()| focused.set(true)),
),
)
.child(canvas(move || {
let len = name.with(String::len) as f32;
Painter::new().fill_rect(0.0, 0.0, len, 4.0)
}))
.child(when(
move || name.with(String::len) > 2,
// `nsh_base::dialog` is this, and nsh-base depends on the core.
#[allow(deprecated)]
move || {
modal()
.close_on_swipe(false)
.child(text(move || format!("Hi {}", name.get())))
},
))
.child(text(move || if focused.get() { "focused" } else { "idle" }))
// Back to the field: focus it, the caret at the end.
.child(view().on_press(move |_: &()| {
field.focus();
field.set_selection(3, 3);
// As an app allowing a paste it heard first.
field.insert_text("!");
}))
}
#[derive(Clone, PartialEq, Props)]
struct FormProps {}
#[test]
fn host_elements_take_typed_props_and_events() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Form>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Form>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let created = |batch: &MountBatch, wanted: ViewKind| {
batch.items.iter().find_map(|i| match i {
MountItem::Create { id, kind } if *kind == wanted => Some(*id),
_ => None,
})
};
let input = created(&batch, ViewKind::Input).expect("an input");
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button listens to presses");
assert!(created(&batch, ViewKind::Scroll).is_some());
assert!(created(&batch, ViewKind::Modal).is_none(), "no modal yet");
let placeholder = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::Input { config, .. } => Some(config.placeholder.clone()),
_ => None,
})
};
assert_eq!(placeholder(&batch).as_deref(), Some("Name"));
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Canvas { .. }))
);
assert_eq!(texts(&batch), ["idle"]);
// Typing: the component gets the text, the placeholder goes back to
// its default, the modal appears, the canvas draws again; the
// input's value is the platform's already, so it is not sent back.
c.input_changed(input, "Ada", 1);
assert!(c.component_event(
input,
EventKind::ChangeText,
&EventPayload::Text {
text: "Ada".into(),
count: 1
}
));
assert!(c.component_event(input, EventKind::Focus, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(placeholder(&batch).as_deref(), Some(""));
assert!(created(&batch, ViewKind::Modal).is_some());
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Canvas { .. }))
);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::InputValue { .. }))
);
assert_eq!(texts(&batch), ["Hi Ada", "focused"]);
// The ref's commands reach the input it is on, in the next batch.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let commands: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Command { id, command } => Some((*id, command.clone())),
_ => None,
})
.collect();
assert_eq!(
commands,
[
(input, Command::Focus),
(input, Command::SetSelection { start: 3, end: 3 }),
(input, Command::InsertText("!".into()))
]
);
}
/// Measures its box when pressed (and a ref no element carries).
#[component]
fn Ruler() -> impl IntoElement {
let target = element_ref();
let unused = element_ref();
let shown = signal(String::new());
view()
.p_4()
.child(
view()
.pl(px(10.0))
.child(view().element_ref(&target).w(px(30.0)).h(px(20.0))),
)
.child(text(move || shown.get()))
.child(view().w(px(5.0)).h(px(5.0)).on_press(move |_: &()| {
let (target, unused) = (target.measure(), unused.measure());
spawn(async move {
let (m, none) = (target.await, unused.await);
let m = m.expect("laid out");
shown.set(format!(
"{},{} {}x{} at {},{} {}",
m.frame.origin.x.0,
m.frame.origin.y.0,
m.frame.size.width.0,
m.frame.size.height.0,
m.page.x.0,
m.page.y.0,
none.is_none()
));
});
}))
}
#[test]
fn element_refs_measure_with_the_commits_layout() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Ruler>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Ruler>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button listens to presses");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
// The frame in its parent (past the parent's padding), the corner
// in the surface (past the component's padding too); the ref no
// element carries measures nothing.
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains(" at ")));
assert_eq!(shown.last().unwrap(), "10,0 30x20 at 26,16 true");
}
/// Reads its box's text when pressed (and a ref no element carries):
/// the texts inside it in order, one hidden left out.
#[component]
fn Reader() -> impl IntoElement {
let target = element_ref();
let unused = element_ref();
let shown = signal(String::new());
view()
.child(
view()
.element_ref(&target)
.child(text("Open "))
.child(view().child(text("recent")).child(text(" file")))
.child(view().hidden().child(text(" secret"))),
)
.child(text(move || shown.get()))
.child(view().w(px(5.0)).h(px(5.0)).on_press(move |_: &()| {
let (target, unused) = (target.text_content(), unused.text_content());
spawn(async move {
let (text, none) = (target.await, unused.await);
shown.set(format!("read:{text}|{none}"));
});
}))
}
#[test]
fn element_refs_read_the_text_they_show() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Reader>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Reader>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button listens to presses");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("read:")));
assert_eq!(shown.last().unwrap(), "read:Open recent file|");
}
#[derive(Clone, PartialEq, Debug)]
struct Accent(u32);
#[derive(Default, Clone)]
struct Clicks(u32);
#[derive(Clone, PartialEq, Props)]
struct WithChildren {
children: Children,
}
/// Provides an accent to what is below it, through the app's JSX.
#[component]
fn Theming(props: WithChildren) -> impl IntoElement {
let accent = signal(Accent(0));
provide_context(accent);
view()
.on_press(move |_: &()| accent.update(|a| a.0 += 1))
.child(props.children)
}
/// Shows the accent above it and the surface's clicks; a press counts
/// one.
#[component]
fn AccentSwatch(_props: FormProps) -> impl IntoElement {
let accent = use_context::<Signal<Accent>>();
let clicks = global::<Clicks>();
view()
.on_press(move |_: &()| clicks.update(|c| c.0 += 1))
.child(text(move || {
let accent = accent.map_or(0, |a| a.with(|a| a.0));
format!("accent {accent} clicks {}", clicks.with(|c| c.0))
}))
}
#[test]
fn context_flows_down_and_globals_reach_their_readers() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Theming>().register::<AccentSwatch>();
c.set_components(registry);
// <Theming><view><Swatch/></view></Theming> and a second Swatch
// outside it.
let host = |id, name: &str| {
vec![
Op::Create { id, tag: Tag::View },
Op::SetProp {
id,
prop: Prop::Component(name.into()),
},
]
};
let mut ops = host(2, std::any::type_name::<Theming>());
ops.push(Op::Create {
id: 4,
tag: Tag::View,
});
ops.extend(host(6, std::any::type_name::<AccentSwatch>()));
ops.extend(host(8, std::any::type_name::<AccentSwatch>()));
for (parent, child) in [(4, 6), (2, 4), (ROOT_ID, 2), (ROOT_ID, 8)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let mut shown = texts(&batch);
shown.sort();
assert_eq!(shown, ["accent 0 clicks 0", "accent 0 clicks 0"]);
// A new value: only the swatch below the provider changes.
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["accent 1 clicks 0"]);
// A global changed by one swatch changes both.
assert!(c.component_event(8, EventKind::Press, &EventPayload::None));
let mut shown = texts(&c.commit().unwrap());
shown.sort();
assert_eq!(shown, ["accent 0 clicks 1", "accent 1 clicks 1"]);
}
thread_local! {
/// What [`OrphanSwatch`]'s bindings found once its provider was
/// gone.
static ORPHAN_READS: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// [`AccentSwatch`], noting a run that finds the accent above it gone
/// (where [`AccentSwatch`] would panic reading it).
#[component]
fn OrphanSwatch(_props: FormProps) -> impl IntoElement {
let accent = use_context::<Signal<Accent>>();
let clicks = global::<Clicks>();
view()
.on_press(move |_: &()| clicks.update(|c| c.0 += 1))
.child(text(move || {
let clicks = clicks.with(|c| c.0);
let accent = match accent.map(|a| a.try_get().map(|a| a.0)) {
Some(Some(accent)) => accent,
Some(None) => {
ORPHAN_READS.with(|r| r.borrow_mut().push(format!("clicks {clicks}")));
return "gone".to_string();
}
None => 0,
};
format!("accent {accent} clicks {clicks}")
}))
}
/// Places its children (a base component another one's view is made
/// of).
#[component]
fn ChildrenPlacer(props: WithChildren) -> impl IntoElement {
view().child(props.children)
}
/// [`Theming`] whose view's root is another component, which places
/// the children. As it goes, after its accent (made after), it writes
/// a global (as a registration undone in a cleanup does).
#[component]
fn RootedTheming(props: WithChildren) -> impl IntoElement {
let clicks = global::<Clicks>();
crate::element::effect(move || {
crate::element::cleanup(move || clicks.update(|c| c.0 += 10));
});
let accent = signal(Accent(0));
provide_context(accent);
children_placer().child(props.children)
}
/// The JS nodes of a subtree are released one by one in no set order
/// (on the web, as the browser's garbage collector finalizes them):
/// a provider's may go before those of the components JS placed in
/// it. Those go with it then, before what it made: none of their
/// bindings runs again and reads its state, which is gone.
#[test]
fn components_js_placed_in_a_released_one_go_with_it() {
released_provider_first::<Theming>();
}
/// [`components_js_placed_in_a_released_one_go_with_it`] where the
/// component placing them is the one the provider's view is made of.
#[test]
fn components_js_placed_in_a_released_ones_root_go_with_it() {
released_provider_first::<RootedTheming>();
}
/// Clicks a released provider adds as it goes ([`RootedTheming`]).
fn added_as_it_goes<P: 'static>() -> u32 {
if std::any::TypeId::of::<P>() == std::any::TypeId::of::<RootedTheming>() {
10
} else {
0
}
}
fn released_provider_first<P: Component>() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<P>().register::<OrphanSwatch>();
c.set_components(registry);
ORPHAN_READS.with(|r| r.borrow_mut().clear());
// <Provider><view><Swatch/></view></Provider> and a second Swatch
// outside it.
let host = |id, name: &str| {
vec![
Op::Create { id, tag: Tag::View },
Op::SetProp {
id,
prop: Prop::Component(name.into()),
},
]
};
let mut ops = host(2, std::any::type_name::<P>());
ops.push(Op::Create {
id: 4,
tag: Tag::View,
});
ops.extend(host(6, std::any::type_name::<OrphanSwatch>()));
ops.extend(host(8, std::any::type_name::<OrphanSwatch>()));
for (parent, child) in [(4, 6), (2, 4), (ROOT_ID, 2), (ROOT_ID, 8)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
apply(&mut c, ops);
let mut shown = texts(&c.commit().unwrap());
shown.sort();
assert_eq!(shown, ["accent 0 clicks 0", "accent 0 clicks 0"]);
// JS takes the provider out; its node is released before those
// inside it.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
c.commit().unwrap();
assert_eq!(ORPHAN_READS.with(|r| r.take()), Vec::<String>::new());
// A global the swatches read changes: only the one still shown
// runs.
let added = added_as_it_goes::<P>();
assert!(c.component_event(8, EventKind::Press, &EventPayload::None));
assert_eq!(
texts(&c.commit().unwrap()),
[format!("accent 0 clicks {}", added + 1)]
);
assert_eq!(ORPHAN_READS.with(|r| r.take()), Vec::<String>::new());
// The rest of the subtree is released later.
apply(&mut c, vec![Op::Release { id: 4 }, Op::Release { id: 6 }]);
c.commit().unwrap();
assert!(c.component_event(8, EventKind::Press, &EventPayload::None));
assert_eq!(
texts(&c.commit().unwrap()),
[format!("accent 0 clicks {}", added + 2)]
);
assert_eq!(ORPHAN_READS.with(|r| r.take()), Vec::<String>::new());
}
/// A sheet that follows drags natively and springs back when let go.
#[component]
fn Sheet(_props: FormProps) -> impl IntoElement {
let offset = animated_value(0.0);
let state = signal("resting");
view()
.bind_translate_y(&offset)
.bind_opacity(&offset.interpolate(&[0.0, 300.0], &[1.0, 0.2]))
.pan_values(None, Some(&offset))
.on_pan_end(move |e: &PanEvent| {
assert_eq!(e.value_y, Some(120.0));
let end = offset.spring(0.0, Spring::default());
state.set("springing");
spawn(async move {
let finished = end.await;
state.set(if finished { "back" } else { "stopped" });
});
})
.child(text(move || state.get()))
}
#[test]
fn animated_values_bind_animate_and_end() {
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let mut c = core();
let mut registry = Registry::new();
registry.register::<Sheet>();
c.set_components(registry);
c.set_task_runtime(runtime.handle().clone());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Sheet>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let animations: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Animation(op) => Some(op.clone()),
_ => None,
})
.collect();
// The value and its interpolation, in the core's id range.
let value = match animations[0] {
crate::animation::AnimationOp::CreateValue { node, value: 0.0 } => node,
ref op => panic!("{op:?}"),
};
assert_eq!(value % 2, 1, "the core's ids are odd");
assert!(
matches!(animations[1], crate::animation::AnimationOp::CreateInterpolate { input, .. } if input == value)
);
assert_eq!(texts(&batch), ["resting"]);
// Let go: a spring starts; its end resolves the task.
let payload = EventPayload::Pan {
origin: point(px(40.0), px(300.0)),
translation: point(px(0.0), px(120.0)),
velocity_x: 0.0,
velocity_y: 300.0,
value_x: None,
value_y: Some(px(120.0)),
};
assert!(c.component_event(2, EventKind::PanEnd, &payload));
let batch = c.commit().unwrap();
let animation = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Animation(crate::animation::AnimationOp::Start {
node,
animation,
..
}) if *node == value => Some(*animation),
_ => None,
})
.expect("a spring");
assert_eq!(texts(&batch), ["springing"]);
let mut finished = vec![
crate::animation::Finished::new(animation, true),
// JS's (even ids) stay for JS.
crate::animation::Finished::new(8, true),
];
c.animations_finished(&mut finished);
assert_eq!(finished.len(), 1);
let _guard = runtime.enter();
assert_eq!(
run_until(&mut c, |s| s.contains(&"back".to_owned())),
["back"]
);
// Released with the component: the value and what derives from it.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
let batch = [c.commit(), c.commit()];
let released = batch
.iter()
.flatten()
.flat_map(|b| &b.items)
.filter(|i| {
matches!(
i,
MountItem::Animation(crate::animation::AnimationOp::Release { .. })
)
})
.count();
assert_eq!(released, 2, "{batch:?}");
}
/// Handles made under an owner of their own, which a press disposes
/// while the view stays: the view's binding and input hold what they
/// name, so the fade goes on; the handles, shared by two listeners,
/// do nothing from then on.
#[component]
fn Outlived() -> impl IntoElement {
let (owner, (fade, field)) =
crate::element::create_root(|| (animated_value(1.0), element_ref()));
let _ = fade.timing(0.0, 300.0, Easing::Linear);
let shown = signal(String::new());
view()
.bind_opacity(&fade)
.child(input().element_ref(&field))
.child(view().on_press(move |_: &()| {
field.focus();
fade.set(0.5);
}))
.child(view().on_press(move |_: &()| {
owner.dispose();
fade.set(0.25);
fade.stop();
let _ = fade.spring(1.0, Spring::default());
field.focus();
let gone = fade.interpolate(&[0.0, 1.0], &[0.0, 1.0]);
shown.set(format!("{:?} {:?}", field.node(), gone.live().is_none()));
}))
.child(text(move || shown.get()))
}
#[test]
fn handles_outlived_by_what_binds_them_do_nothing() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Outlived>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Outlived>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let animations = |batch: &MountBatch| -> Vec<crate::animation::AnimationOp> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Animation(op) => Some(op.clone()),
_ => None,
})
.collect()
};
let commands = |batch: &MountBatch| -> Vec<(NodeId, Command)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Command { id, command } => Some((*id, command.clone())),
_ => None,
})
.collect()
};
let batch = c.commit().unwrap();
let ops = animations(&batch);
let fade = match ops[..] {
[
crate::animation::AnimationOp::CreateValue { node, value: 1.0 },
crate::animation::AnimationOp::Start { node: started, .. },
] if started == node => node,
_ => panic!("{ops:?}"),
};
let input = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create {
id,
kind: ViewKind::Input,
} => Some(*id),
_ => None,
})
.expect("an input");
let buttons: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.collect();
let [first, second] = buttons[..] else {
panic!("{buttons:?}");
};
// The handles work while their owner lives.
assert!(c.component_event(first, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(
animations(&batch),
[crate::animation::AnimationOp::Set {
node: fade,
value: 0.5
}]
);
assert_eq!(commands(&batch), [(input, Command::Focus)]);
// Its owner goes: the binding holds the node (no release, its fade
// runs on); the handles do nothing and name nothing, with no panic.
assert!(c.component_event(second, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(animations(&batch), []);
assert_eq!(commands(&batch), []);
assert_eq!(texts(&batch), ["None true"]);
assert!(c.component_event(first, EventKind::Press, &EventPayload::None));
assert!(
c.commit()
.is_none_or(|b| animations(&b).is_empty() && commands(&b).is_empty())
);
// The node goes with the view that binds it.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
let released: Vec<_> = [c.commit(), c.commit()]
.iter()
.flatten()
.flat_map(animations)
.collect();
assert_eq!(
released,
[crate::animation::AnimationOp::Release { node: fade }]
);
}
/// One press derives nodes from the view's value (colors that follow
/// the appearance too); the other makes state of its own, and a task
/// that makes more.
#[component]
fn Repeated() -> impl IntoElement {
let v = animated_value(0.0);
let presses = signal(0);
let colors = [AdaptiveColor {
light: Color::BLACK.into(),
dark: Color::TRANSPARENT.into(),
}; 2];
view()
.bind_opacity(&v)
.child(view().on_press(move |_: &()| {
let half = v.mul(0.5);
let _ = half.interpolate(&[0.0, 1.0], &[0.0, 1.0]);
let _ = v.interpolate_colors(&[0.0, 1.0], &colors);
presses.update(|n| *n += 1);
}))
.child(view().on_press(move |_: &()| {
let _ = (signal(0), animated_value(1.0), element_ref(), stored(0));
spawn(async move {
let _ = (signal(1), animated_value(2.0));
});
}))
.child(text(move || presses.get().to_string()))
}
#[test]
fn repeated_presses_do_not_grow_the_graph() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Repeated>();
c.set_components(registry);
let mount = |c: &mut Core<FakeEngine>, id| {
apply(
c,
vec![
Op::Create { id, tag: Tag::View },
Op::SetProp {
id,
prop: Prop::Component(std::any::type_name::<Repeated>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
],
);
let batch = c.commit().unwrap();
let buttons: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => {
Some(*id)
}
_ => None,
})
.collect();
[buttons[0], buttons[1]]
};
let unmount = |c: &mut Core<FakeEngine>, id| {
apply(
c,
vec![
Op::Remove {
parent: ROOT_ID,
child: id,
},
Op::Release { id },
],
);
let _ = (c.commit(), c.commit());
};
let press = |c: &mut Core<FakeEngine>, button| {
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.run_component_tasks();
let _ = c.commit();
};
let slots = |c: &Core<FakeEngine>| c.components.runtime.slots_in_use();
// What the surface makes once (its environment, the theme) first.
let _ = mount(&mut c, 2);
unmount(&mut c, 2);
let empty = slots(&c);
let [derive, make] = mount(&mut c, 4);
for _ in 0..5 {
press(&mut c, derive);
}
let derived = slots(&c);
for _ in 0..500 {
press(&mut c, derive);
}
assert_eq!(slots(&c), derived, "deriving again adds nothing");
// State a press makes is the component's: it goes with it.
for _ in 0..50 {
press(&mut c, make);
}
assert!(slots(&c) > derived);
unmount(&mut c, 4);
assert_eq!(slots(&c), empty, "released with the component");
}
/// A press disposes the branch its view is in (as what closes it does,
/// unbatched), then makes state and a task.
#[component]
fn SelfClosing() -> impl IntoElement {
let open = signal(true);
view().child(when(open, move || {
view().on_press(move |_: &()| {
Owner::current().dispose();
let _ = (signal(5), animated_value(1.0), element_ref());
spawn(async {});
})
}))
}
#[test]
fn a_listener_closing_its_own_view_leaves_nothing() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<SelfClosing>();
c.set_components(registry);
let mount = |c: &mut Core<FakeEngine>, id| {
apply(
c,
vec![
Op::Create { id, tag: Tag::View },
Op::SetProp {
id,
prop: Prop::Component(std::any::type_name::<SelfClosing>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
],
);
let batch = c.commit().unwrap();
batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => {
Some(*id)
}
_ => None,
})
.unwrap()
};
let unmount = |c: &mut Core<FakeEngine>, id| {
apply(
c,
vec![
Op::Remove {
parent: ROOT_ID,
child: id,
},
Op::Release { id },
],
);
let _ = (c.commit(), c.commit());
};
let _ = mount(&mut c, 2);
unmount(&mut c, 2);
let empty = c.components.runtime.slots_in_use();
let button = mount(&mut c, 4);
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.run_component_tasks();
let _ = c.commit();
unmount(&mut c, 4);
assert_eq!(c.components.runtime.slots_in_use(), empty);
}
/// Its own rows indexing its data; a press clears the data. Its errors
/// show as a text.
#[component]
fn Clearable() -> impl IntoElement {
let rows = signal((0..3).map(|i| format!("row {i}")).collect::<Vec<_>>());
view()
.flex_1()
.child(
view()
.h(px(20.0))
.on_press(move |_: &()| rows.set(Vec::new())),
)
.child(catch_error(
move || {
virtual_list(
move || rows.with(Vec::len),
move |at| {
view()
.h(px(40.0))
.child(text(move || rows.with(|r| r[at.index()].clone())))
},
)
.estimated_item_size(px(40.0))
.flex_1()
},
|e, _| text(format!("failed: {}", e.message)),
))
}
#[test]
fn virtual_lists_drop_rows_that_are_gone() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Clearable>(|| ()));
let batch = c.commit().unwrap();
assert!(
texts(&batch).contains(&"row 2".to_owned()),
"{:?}",
texts(&batch)
);
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
// The cells of rows that are gone render nothing until the list
// binds them again, never a row past the end.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let mut shown = Vec::new();
for _ in 0..3 {
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
}
}
assert!(shown.iter().all(|t| !t.starts_with("failed")), "{shown:?}");
}
// A list of wrapping texts beside a panel shown while `narrow`; a
// press toggles the panel inside `animate_layout` when `animated`.
thread_local! {
static PANEL: Cell<(bool, bool)> = const { Cell::new((false, false)) };
}
#[component]
fn ListBesidePanel() -> impl IntoElement {
let (animated, narrow) = PANEL.with(Cell::get);
let narrow = signal(narrow);
view()
.flex_1()
.child(view().h(px(20.0)).on_press(move |_: &()| {
if animated {
animate_layout(crate::LayoutAnimation {
create: Some(crate::LayoutTransition::new(
crate::LayoutCurve::EaseOut,
150.0,
)),
update: Some(crate::LayoutTransition::new(
crate::LayoutCurve::EaseInEaseOut,
220.0,
)),
delete: Some(crate::LayoutTransition::new(
crate::LayoutCurve::EaseOut,
150.0,
)),
});
}
narrow.update(|n| *n = !*n);
}))
.child(
view()
.flex_row()
.flex_1()
.child(
virtual_list(6, move |at| {
// 160, 320 and 480 points of text at 8 a char.
text("x".repeat(20 * (at.index() % 3 + 1)))
})
.keys(|| 0..6)
.estimated_item_size(px(64.0))
.flex_1(),
)
.child(when(move || narrow.get(), || view().w(px(160.0)))),
)
}
/// The frames of the texts shown, by length, once commits settle,
/// after a press on the button when `press`.
fn text_frames(c: &mut Core<FakeEngine>, press: bool) -> Vec<(usize, Bounds<Points>)> {
let mut frames = std::collections::HashMap::new();
let mut texts = std::collections::HashMap::new();
let mut button_id = None;
let mut take = |batch: MountBatch, button_id: &mut Option<NodeId>| {
for item in batch.items {
match item {
MountItem::Frame { id, frame } => {
frames.insert(id, frame);
}
MountItem::Text { id, text, .. } => {
texts.insert(id, text.text.chars().count());
}
MountItem::Events { id, events } if events.contains(EventKind::Press) => {
*button_id = Some(id);
}
_ => {}
}
}
};
for _ in 0..4 {
if let Some(batch) = c.commit() {
take(batch, &mut button_id);
}
}
if press && let Some(id) = button_id {
assert!(c.component_event(id, EventKind::Press, &EventPayload::None));
for _ in 0..4 {
if let Some(batch) = c.commit() {
take(batch, &mut button_id);
}
}
}
let mut out: Vec<_> = texts
.into_iter()
.filter_map(|(id, chars)| Some((chars, *frames.get(&id)?)))
.collect();
out.sort_by(|a, b| {
a.0.cmp(&b.0)
.then(a.1.origin.y.0.total_cmp(&b.1.origin.y.0))
});
out
}
/// #1830: a list narrowed inside `animate_layout` measures its rows at
/// the new width, as it does without the animation.
#[test]
fn a_list_narrowed_inside_a_layout_animation_measures_its_rows_again() {
for animated in [false, true] {
let mut c = core();
PANEL.with(|p| p.set((animated, false)));
c.mount_root(&crate::element::Root::new::<ListBesidePanel>(|| ()));
let toggled = text_frames(&mut c, true);
let mut fresh = core();
PANEL.with(|p| p.set((false, true)));
fresh.mount_root(&crate::element::Root::new::<ListBesidePanel>(|| ()));
let expected = text_frames(&mut fresh, false);
assert!(!expected.is_empty());
for (chars, frame) in &expected {
// 160 points wide: one line per 20 characters.
assert_eq!(
frame.size.height.0,
(*chars / 20) as f32 * 16.0,
"{expected:?}"
);
}
let heights = |f: &[(usize, Bounds<Points>)]| {
f.iter()
.map(|(n, b)| (*n, b.size.height.0))
.collect::<Vec<_>>()
};
assert_eq!(
heights(&toggled),
heights(&expected),
"animated: {animated}"
);
}
}
/// A long list of its own rows: row 1 holds a field, row 2 a menu (an
/// overlay) while it is open; a press closes the menu.
#[component]
fn RowsWithFieldAndMenu() -> impl IntoElement {
let menu = signal(true);
view()
.flex_1()
.child(view().h(px(20.0)).on_press(move |_: &()| menu.set(false)))
.child(
virtual_list(500, move |at| {
view()
.h(px(40.0))
.child(text(move || format!("row {}", at.index())))
.child(when(
move || at.index() == 1,
|| view().focusable(true).child(text("field")),
))
.child(when(
move || at.index() == 2 && menu.get(),
|| overlay().child(text("menu")),
))
})
.estimated_item_size(px(40.0))
.flex_1(),
)
}
/// A row holding the keyboard focus or an open overlay stays rendered
/// while the list scrolls far away: recycled, its field would lose the
/// focus and its menu close. Once they are gone, the row is recycled.
#[test]
fn virtual_lists_keep_rows_with_the_focus_or_an_open_overlay() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
c.mount_root(&crate::element::Root::new::<RowsWithFieldAndMenu>(|| ()));
let batch = c.commit().unwrap();
let list = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create { id, kind } if *kind == ViewKind::Scroll => Some(*id),
_ => None,
})
.expect("a list");
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
let text_node = |content: &str| {
batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id, text, .. } if text.text == content => Some(*id),
_ => None,
})
.unwrap_or_else(|| panic!("no text {content:?}"))
};
let field = {
let key = c.key(text_node("field")).unwrap();
c.nodes[c.nodes[key as usize].parent as usize].id
};
let menu = text_node("menu");
c.set_states(field, FOCUSED);
let _ = c.commit();
let bound = |c: &Core<FakeEngine>, row: u32| {
let key = c.key(list).unwrap();
let list = c.nodes[key as usize].list.as_ref().unwrap();
list.slots.iter().any(|s| s.index == Some(row))
};
let scroll = |c: &mut Core<FakeEngine>, y: f32, applied| {
c.set_scroll_offset(list, point(px(0.0), px(y)), applied);
for _ in 0..3 {
let _ = c.commit();
}
};
scroll(&mut c, 4000.0, 1);
scroll(&mut c, 12000.0, 2);
assert!(
bound(&c, 1) && c.key(field).is_ok(),
"the focused row stays"
);
assert!(
bound(&c, 2) && c.key(menu).is_ok(),
"the row with the open menu stays"
);
// The focus leaves and the menu closes: the rows go.
c.set_states(field, 0);
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let _ = c.commit();
scroll(&mut c, 16000.0, 3);
assert!(!bound(&c, 1) && !bound(&c, 2));
}
/// A long list of keyed rows, each a stop of Tab; a press moves row 10
/// to the third place, another moves row 3 past the rendered rows.
#[component]
fn MovingRows() -> impl IntoElement {
let rows = signal((0..100).map(|i| format!("r{i}")).collect::<Vec<_>>());
let move_row = move |from: usize, to: usize| {
move |_: &()| {
rows.update(|r| {
let row = r.remove(from);
r.insert(to, row);
})
}
};
view()
.flex_1()
.child(view().h(px(20.0)).label("up").on_press(move_row(10, 2)))
.child(view().h(px(20.0)).label("down").on_press(move_row(3, 90)))
.child(
virtual_list(
move || rows.with(Vec::len),
move |at| {
view()
.h(px(40.0))
.focusable(true)
.child(text(move || rows.with(|r| r[at.index()].clone())))
},
)
.keys(move || rows.get())
.estimated_item_size(px(40.0))
.flex_1(),
)
}
/// A keyed row that moves keeps its cell, and so do the rows it passes:
/// nothing is made or drawn again, only placed, and the focus in a row
/// that moved stays where it is.
#[test]
fn virtual_lists_move_keyed_rows_with_their_cells() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
c.mount_root(&crate::element::Root::new::<MovingRows>(|| ()));
let batch = c.commit().unwrap();
let text_node = |content: &str| {
batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id, text, .. } if text.text == content => Some(*id),
_ => None,
})
.unwrap_or_else(|| panic!("no text {content:?}"))
};
let row = |c: &Core<FakeEngine>, text: NodeId| {
let key = c.key(text).unwrap();
c.nodes[c.nodes[key as usize].parent as usize].id
};
let buttons: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.collect();
let press = |c: &mut Core<FakeEngine>, label: &str| {
let button = buttons[usize::from(label == "down")];
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let mut batches = Vec::new();
while let Some(batch) = c.commit() {
batches.push(batch);
}
batches
};
let (moved, passed) = (text_node("r10"), text_node("r5"));
let focused = row(&c, passed);
c.set_states(focused, FOCUSED);
let _ = c.commit();
for label in ["up", "down"] {
let batches = press(&mut c, label);
let items: Vec<&MountItem> = batches.iter().flat_map(|b| &b.items).collect();
assert!(
!items.iter().any(|i| matches!(i, MountItem::Create { .. })),
"{label}: {items:?}"
);
// Only a row coming into the window is drawn: row 3's cell,
// moved past it, shows it.
let drawn = items
.iter()
.filter(|i| matches!(i, MountItem::Text { .. }))
.count();
assert_eq!(drawn, usize::from(label == "down"), "{label}: {items:?}");
assert!(c.key(moved).is_ok() && c.key(passed).is_ok(), "{label}");
assert_eq!(c.focus.map(|(_, id)| id), Some(focused), "{label}");
}
}
/// A change to `ChangingRows`'s rows.
type RowsChange = fn(&mut Vec<String>);
thread_local! {
/// How many rows `ChangingRows` starts with.
static CHANGING_ROWS: Cell<usize> = const { Cell::new(100) };
/// What a press does to `ChangingRows`'s rows.
static ROWS_CHANGE: Cell<Option<RowsChange>> = const { Cell::new(None) };
}
/// Keyed rows, `r0`, `r1`, ...; a press changes them as
/// [`ROWS_CHANGE`] says.
#[component]
fn ChangingRows() -> impl IntoElement {
let count = CHANGING_ROWS.get();
let rows = signal((0..count).map(|i| format!("r{i}")).collect::<Vec<_>>());
view()
.flex_1()
.child(view().h(px(20.0)).on_press(move |_: &()| {
let change = ROWS_CHANGE.get().expect("a change");
rows.update(change);
}))
.child(
virtual_list(
move || rows.with(Vec::len),
move |at| {
view()
.h(px(40.0))
.child(text(move || rows.with(|r| r[at.index()].clone())))
},
)
.keys(move || rows.get())
.estimated_item_size(px(40.0))
.flex_1(),
)
}
/// Keyed rows, `r0`..`r5`; rows named `n...` are taller than the
/// estimate. A press replaces rows 1 and 2 with two new ones.
#[component]
fn ReplacedRows() -> impl IntoElement {
let rows = signal((0..6).map(|i| format!("r{i}")).collect::<Vec<_>>());
view()
.flex_1()
.child(view().h(px(20.0)).on_press(move |_: &()| {
rows.update(|r| {
r.splice(1..3, ["n1", "n2"].map(String::from));
})
}))
.child(
virtual_list(
move || rows.with(Vec::len),
move |at| {
let tall = move || {
rows.with(|r| r.get(at.index()).is_some_and(|r| r.starts_with('n')))
};
view()
.h(move || px(if tall() { 100.0 } else { 40.0 }))
.child(text(move || {
rows.with(|r| r.get(at.index()).cloned().unwrap_or_default())
}))
},
)
.keys(move || rows.get())
.estimated_item_size(px(40.0))
.flex_1(),
)
}
/// Rows replaced in place (old keys gone, new ones at their indexes):
/// a cell that takes back the new row at its index is measured in the
/// same commit, so the rows after it are placed after its real size,
/// not over it while nothing else lays the list out again.
#[test]
fn replaced_keyed_rows_are_measured_before_the_rows_after_them_are_placed() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<ReplacedRows>(|| ()));
while c.commit().is_some() {}
let list = c
.nodes
.iter()
.find(|(_, n)| n.list.is_some())
.map(|(k, _)| k as Key)
.expect("a list");
let button = c
.nodes
.iter()
.find(|(_, n)| n.events.contains(EventKind::Press))
.map(|(_, n)| n.id)
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
while c.commit().is_some() {}
let cells: Vec<(String, f32, f32)> = {
let l = c.nodes[list as usize].list.as_ref().unwrap();
let mut cells: Vec<(String, f32, f32)> = l
.slots
.iter()
.filter(|s| s.ready().is_some())
.map(|s| {
let frame = c.nodes[s.cell as usize].frame;
let text = texts_in(&c, s.cell);
(text, frame.origin.y.0, frame.size.height.0)
})
.collect();
cells.sort_by(|a, b| a.1.total_cmp(&b.1));
cells
};
let names: Vec<&str> = cells.iter().map(|c| c.0.as_str()).collect();
assert_eq!(names, ["r0", "n1", "n2", "r3", "r4", "r5"], "{cells:?}");
for w in cells.windows(2) {
assert_eq!(w[0].1 + w[0].2, w[1].1, "{cells:?}");
}
}
/// The raw texts inside cell `cell`, joined.
fn texts_in(c: &Core<FakeEngine>, cell: Key) -> String {
let mut out = String::new();
let mut stack = vec![cell];
while let Some(k) = stack.pop() {
let n = &c.nodes[k as usize];
if n.kind == Kind::RawText {
out.push_str(&n.text);
}
if let Some(r) = c.runs.values().find(|r| r.block == k) {
out.push_str(&r.text);
}
stack.extend(n.children.iter().rev());
}
out
}
/// The rows two or more cells show at once: each row is in one cell,
/// spare cells included (which keep showing their last row).
fn rows_shown_twice(c: &Core<FakeEngine>) -> Vec<String> {
let mut shown = std::collections::HashMap::<&str, u32>::new();
for text in texts_shown(c) {
if !text.is_empty() {
*shown.entry(text).or_default() += 1;
}
}
let mut twice: Vec<String> = shown
.into_iter()
.filter(|&(_, n)| n > 1)
.map(|(t, _)| t.to_owned())
.collect();
twice.sort();
twice
}
/// The raw texts in the tree: those with a node, and those a text block
/// shows without one (its only run).
fn texts_shown(c: &Core<FakeEngine>) -> Vec<&str> {
c.nodes
.iter()
.filter(|(_, n)| n.kind == Kind::RawText)
.map(|(_, n)| n.text.as_str())
.chain(
c.runs
.values()
.filter(|r| r.block != NO_KEY)
.map(|r| r.text.as_str()),
)
.collect()
}
/// A row that goes leaves its cell spare, and the rows after it move up
/// into theirs; data replaced or cut short leaves spare cells too.
/// No row shows in two cells at any point: the spare ones show rows no
/// other cell does, or nothing, so a row's elements are found once.
#[test]
fn spare_list_cells_never_show_a_row_another_cell_shows() {
// The window holds about 34 rows wherever it is (one more in the
// middle, where both its edges cut a row): scrolled from the middle
// to an end, a cell is spare.
let cases: [(&str, usize, &[f32], RowsChange); 8] = [
// At the end: the gone row's cell stays spare, the rows after
// it move up into theirs.
("drop at the end", 100, &[2000.0, 3560.0], |r| {
r.remove(90);
}),
("drop the last", 100, &[2000.0, 3560.0], |r| {
r.pop();
}),
("drop at the start", 100, &[2000.0, 0.0], |r| {
r.remove(3);
}),
("drop two", 100, &[2000.0, 0.0], |r| {
r.drain(3..5);
}),
("replace", 100, &[2000.0, 0.0], |r| {
*r = (0..100).map(|i| format!("s{i}")).collect();
}),
("move", 100, &[2000.0, 0.0], |r| {
let row = r.remove(30);
r.insert(2, row);
}),
("cut short", 100, &[2000.0, 0.0], |r| r.truncate(5)),
// Every row in the window: no row comes for the gone one.
("short list", 10, &[], |r| {
r.remove(3);
}),
];
let mut failures = Vec::new();
for (name, count, scrolls, change) in cases {
CHANGING_ROWS.set(count);
let mut c = core();
c.mount_root(&crate::element::Root::new::<ChangingRows>(|| ()));
let batch = c.commit().unwrap();
let list = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create { id, kind } if *kind == ViewKind::Scroll => Some(*id),
_ => None,
})
.expect("a list");
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => {
Some(*id)
}
_ => None,
})
.expect("a button");
let mut check = |c: &Core<FakeEngine>, when: String| {
let twice = rows_shown_twice(c);
if !twice.is_empty() {
failures.push(format!("{name}, {when}: {twice:?}"));
}
};
let settle = |c: &mut Core<FakeEngine>| {
for _ in 0..4 {
let _ = c.commit();
}
};
settle(&mut c);
let mut applied = 0;
for &y in scrolls {
applied += 1;
c.set_scroll_offset(list, point(px(0.0), px(y)), applied);
settle(&mut c);
check(&c, format!("scrolled to {y}"));
}
let mut rows: Vec<String> = (0..count).map(|i| format!("r{i}")).collect();
change(&mut rows);
ROWS_CHANGE.set(Some(change));
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
// At every commit, not only once the list settled; the cells
// that take the new rows are bound again, not made.
let mut made = 0;
for round in 0..4 {
let batch = c.commit();
let items = batch.iter().flat_map(|b| &b.items);
made += items
.filter(|i| matches!(i, MountItem::Create { .. }))
.count();
check(&c, format!("round {round}"));
}
// And as the list scrolls on.
for y in [400.0, 1600.0, 0.0] {
applied += 1;
c.set_scroll_offset(list, point(px(0.0), px(y)), applied);
settle(&mut c);
check(&c, format!("then at {y}"));
}
// Two rows gone, one spare cell: the second new row takes a
// cell whose row went, and makes its content (a view, a text).
let allowed = if name == "drop two" { 2 } else { 0 };
if made != allowed {
failures.push(format!("{name}: {made} views made"));
}
// Back at the start, the rows in the viewport show, once each.
let shown = texts_shown(&c);
for row in rows.iter().take(11) {
if !shown.contains(&row.as_str()) {
failures.push(format!("{name}: {row} does not show"));
}
}
}
CHANGING_ROWS.set(100);
assert_eq!(failures, Vec::<String>::new());
}
thread_local! {
/// Every value the id memo of a `KeyedIdRows` cell took: the cell's
/// number and the id.
static IDS_READ: std::cell::RefCell<Vec<(u32, Option<String>)>> = const { std::cell::RefCell::new(Vec::new()) };
/// How many times a `KeyedIdRows` row's content was made again for
/// the id it already showed.
static ROWS_REMADE: Cell<u32> = const { Cell::new(0) };
/// The `KeyedIdRows` cells made so far (their numbers).
static ID_CELLS: Cell<u32> = const { Cell::new(0) };
/// The rows inserted so far (their keys).
static INSERTED: Cell<u32> = const { Cell::new(0) };
}
/// Keyed rows, `r0`, `r1`, ..., whose cells read their row's id in a
/// memo and make the row's content from it, as an app does to keep a
/// row's state with its item; a press changes the rows as
/// [`ROWS_CHANGE`] says.
#[component]
fn KeyedIdRows() -> impl IntoElement {
let count = CHANGING_ROWS.get();
let rows = signal((0..count).map(|i| format!("r{i}")).collect::<Vec<_>>());
view()
.flex_1()
.child(view().h(px(20.0)).on_press(move |_: &()| {
let change = ROWS_CHANGE.get().expect("a change");
rows.update(change);
}))
.child(
virtual_list(
move || rows.with(Vec::len),
move |at| {
let cell = ID_CELLS.get();
ID_CELLS.set(cell + 1);
let id = computed(move || {
let id = rows.with(|r| r.get(at.index()).cloned());
IDS_READ.with_borrow_mut(|read| read.push((cell, id.clone())));
id
});
let shown: std::rc::Rc<std::cell::RefCell<Option<Option<String>>>> =
std::rc::Rc::default();
view().h(px(40.0)).child(dynamic(move || {
let id = id.get();
if shown.replace(Some(id.clone())).as_ref() == Some(&id) {
ROWS_REMADE.set(ROWS_REMADE.get() + 1);
}
text(id.unwrap_or_default())
}))
},
)
.keys(move || rows.get())
.estimated_item_size(px(40.0))
.flex_1(),
)
}
/// A keyed list's cells read their rows at their new indices as soon as
/// the rows change: a memo of a cell's row never sees another row on
/// the way (the row now at the cell's old index), so content made from
/// it is not made again. However long the list is, and however often
/// its rows changed before.
#[test]
fn keyed_list_cells_never_read_another_row_on_the_way() {
let changes: [(&str, RowsChange); 4] = [
("move to the top", |r| {
let row = r.remove(5);
r.insert(0, row);
}),
("remove", |r| {
r.remove(3);
}),
("insert", |r| {
let n = INSERTED.get();
INSERTED.set(n + 1);
r.insert(4, format!("n{n}"));
}),
("reorder", |r| r[..12].reverse()),
];
let mut failures = Vec::new();
for count in [40, 2000] {
CHANGING_ROWS.set(count);
let mut c = core();
c.mount_root(&crate::element::Root::new::<KeyedIdRows>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => {
Some(*id)
}
_ => None,
})
.expect("a button");
for _ in 0..4 {
let _ = c.commit();
}
// The id each cell showed last.
let mut shown = std::collections::HashMap::new();
for (cell, id) in IDS_READ.take() {
shown.insert(cell, id);
}
// The order the graph runs the memos in follows the history of
// the rows' changes: go through the changes a few times.
for round in 0..4 {
for (name, change) in changes {
IDS_READ.with_borrow_mut(Vec::clear);
ROWS_REMADE.set(0);
ROWS_CHANGE.set(Some(change));
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let mut made = 0;
for _ in 0..4 {
let batch = c.commit();
made += batch
.iter()
.flat_map(|b| &b.items)
.filter(|i| matches!(i, MountItem::Create { .. }))
.count();
}
let case = format!("{count} rows, round {round}, {name}");
// Each cell's memo went from the id it showed (if it
// showed one) straight to the id it settled on: no
// other row on the way.
let mut taken = std::collections::HashMap::<u32, Vec<Option<String>>>::new();
for (cell, id) in IDS_READ.take() {
let ids = taken.entry(cell).or_default();
if ids.last() != Some(&id) {
ids.push(id);
}
}
for (cell, ids) in taken {
let settled = ids.last().cloned().expect("an id");
let before = shown.insert(cell, settled.clone());
let straight = match &ids[..] {
[_] => true,
[from, _] => before.as_ref() == Some(from),
_ => false,
};
if !straight {
failures.push(format!("{case}: cell {cell} took {ids:?}"));
}
}
let remade = ROWS_REMADE.get();
if remade != 0 {
failures.push(format!("{case}: {remade} rows made again"));
}
if matches!(name, "move to the top" | "reorder") && made != 0 {
failures.push(format!("{case}: {made} views made"));
}
}
}
}
CHANGING_ROWS.set(100);
assert_eq!(failures, Vec::<String>::new());
}
/// The cell of a keyed row that goes can be the first to read the new
/// rows (the graph runs what reads them in an order their earlier
/// changes left): reading its position lets the cell's content go, the
/// running memo with it, and nothing fails.
#[test]
fn keyed_list_cell_whose_row_goes_can_read_first() {
let changes: [RowsChange; 2] = [|r| r.swap(0, 1), |r| drop(r.remove(0))];
CHANGING_ROWS.set(3);
let mut c = core();
c.mount_root(&crate::element::Root::new::<KeyedIdRows>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("a button");
for _ in 0..4 {
let _ = c.commit();
}
for change in changes {
ROWS_CHANGE.set(Some(change));
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert!(c.components.runtime.take_failures().is_empty());
for _ in 0..4 {
let _ = c.commit();
}
}
let mut shown: Vec<&str> = texts_shown(&c)
.into_iter()
.filter(|t| !t.is_empty())
.collect();
shown.sort();
CHANGING_ROWS.set(100);
assert_eq!(shown, ["r0", "r2"]);
}
/// A long list of its own rows, each a stop of Tab.
#[component]
fn FocusableRows() -> impl IntoElement {
virtual_list(500, move |at| {
view()
.h(px(40.0))
.focusable(true)
.child(text(move || format!("item {}", at.index())))
})
.estimated_item_size(px(40.0))
.flex_1()
}
/// The rows on either side of the one holding the keyboard focus stay
/// rendered with it, wherever the list scrolls: Tab and Shift+Tab find
/// the next stop in the list, not the view after it.
#[test]
fn virtual_lists_keep_the_rows_beside_the_focused_one() {
use crate::tailwind::state::FOCUSED;
// The focused row, the rows kept with it, rows that go. At the
// list's start there is no row before.
for (focused, kept, gone) in [(5, &[4, 5, 6][..], &[3, 7][..]), (0, &[0, 1], &[2])] {
let mut c = core();
c.mount_root(&crate::element::Root::new::<FocusableRows>(|| ()));
let batch = c.commit().unwrap();
let list = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create { id, kind } if *kind == ViewKind::Scroll => Some(*id),
_ => None,
})
.expect("a list");
let content = format!("item {focused}");
let row = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id, text, .. } if text.text == content => Some(*id),
_ => None,
})
.map(|id| {
let key = c.key(id).unwrap();
c.nodes[c.nodes[key as usize].parent as usize].id
})
.unwrap_or_else(|| panic!("no text {content:?}"));
let bound = |c: &Core<FakeEngine>, row: u32| {
let key = c.key(list).unwrap();
let list = c.nodes[key as usize].list.as_ref().unwrap();
list.slots.iter().any(|s| s.index == Some(row))
};
let scroll = |c: &mut Core<FakeEngine>, y: f32, applied| {
c.set_scroll_offset(list, point(px(0.0), px(y)), applied);
for _ in 0..3 {
let _ = c.commit();
}
};
c.set_states(row, FOCUSED);
let _ = c.commit();
scroll(&mut c, 12000.0, 1);
for &i in kept {
assert!(bound(&c, i), "row {i} stays with row {focused}");
}
for &i in gone {
assert!(!bound(&c, i), "row {i} goes");
}
// The focus leaves: they go too.
c.set_states(row, 0);
let _ = c.commit();
scroll(&mut c, 16000.0, 2);
for &i in kept {
assert!(!bound(&c, i), "row {i} goes");
}
}
}
/// What a branch of `ScopedRows` provides to what it makes.
#[derive(Clone)]
struct BranchContext(&'static str);
thread_local! {
/// Whether a row of `ScopedRows` ran after its branch went.
static RAN_AFTER_BRANCH: Cell<bool> = const { Cell::new(false) };
}
/// Its own rows in a branch that provides a context and holds a signal
/// of its own; a press closes the branch and changes what the rows read.
#[component]
fn ScopedRows() -> impl IntoElement {
let (open, tick) = (signal(true), signal(0u32));
view()
.flex_1()
.child(view().h(px(20.0)).on_press(move |_: &()| {
batch(|| {
tick.update(|t| *t += 1);
open.set(false);
})
}))
.child(when(open, move || {
provide_context(BranchContext("provided"));
let local = signal(1u32);
virtual_list(3, move |at| {
let label = use_context::<BranchContext>().map_or("missing", |c| c.0);
effect(move || {
tick.get();
if local.try_get().is_none() {
RAN_AFTER_BRANCH.with(|r| r.set(true));
}
});
view()
.h(px(40.0))
.child(text(format!("{label} {}", at.index())))
})
.estimated_item_size(px(40.0))
.flex_1()
}))
}
#[test]
fn virtual_list_rows_belong_to_the_run_that_made_the_list() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<ScopedRows>(|| ()));
let batch = c.commit().unwrap();
// The rows see what the branch around the list provides.
let shown = texts(&batch);
assert!(shown.contains(&"provided 0".to_owned()), "{shown:?}");
assert!(!shown.iter().any(|t| t.starts_with("missing")), "{shown:?}");
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
// They go with the branch: nothing of theirs runs once it went.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
for _ in 0..3 {
let _ = c.commit();
}
assert!(!RAN_AFTER_BRANCH.with(Cell::get));
}
thread_local! {
static REOWNED_CONTROL:
Cell<Option<(Signal<bool>, Owner, Owner)>> = const { Cell::new(None) };
static REOWNED_B_ROW:
Cell<Option<Signal<u32>>> = const { Cell::new(None) };
}
#[component]
fn ReownedVirtualList() -> impl IntoElement {
let use_b = signal(false);
let (owner_a, list_a) = crate::element::create_root(|| {
virtual_list(1, |_| text("A").h(px(40.0)))
.estimated_item_size(px(40.0))
.flex_1()
});
let (owner_b, list_b) = crate::element::create_root(|| {
virtual_list(1, |_| {
let live = signal(7u32);
REOWNED_B_ROW.with(|r| r.set(Some(live)));
text("B").h(px(40.0))
})
.estimated_item_size(px(40.0))
.flex_1()
});
REOWNED_CONTROL.with(|c| c.set(Some((use_b, owner_a, owner_b))));
// These independent roots require explicit disposal.
cleanup(move || {
owner_a.dispose();
owner_b.dispose();
});
view().flex_1().child(dynamic(move || {
if use_b.get() {
list_b.clone()
} else {
list_a.clone()
}
}))
}
#[test]
fn disposing_a_lists_previous_creator_keeps_its_current_rows() {
REOWNED_B_ROW.with(|r| r.set(None));
let mut c = core();
c.mount_root(&crate::element::Root::new::<ReownedVirtualList>(|| ()));
let first = c.commit().unwrap();
assert_eq!(texts(&first), ["A"]);
let list = first
.items
.iter()
.find_map(|i| match i {
MountItem::Create {
id,
kind: ViewKind::Scroll,
} => Some(*id),
_ => None,
})
.expect("the list");
let (use_b, owner_a, owner_b) = REOWNED_CONTROL.with(Cell::get).unwrap();
let _entered = c.components.runtime.enter();
assert!(owner_a.is_live() && owner_b.is_live());
use_b.set(true);
let switched = c.commit().unwrap();
assert_eq!(texts(&switched), ["B"]);
// Switching creators retains the native list instead of replacing it.
assert!(
!switched
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == list))
);
assert!(!switched.items.iter().any(|i| matches!(
i,
MountItem::Create {
kind: ViewKind::Scroll,
..
}
)));
assert!(owner_a.is_live() && owner_b.is_live());
let row = REOWNED_B_ROW.with(Cell::get).expect("B rendered");
assert_eq!(row.try_get(), Some(7));
owner_a.dispose();
assert!(owner_b.is_live(), "B's creator remains live");
assert_eq!(
row.try_get(),
Some(7),
"A's cleanup must not dispose the retained list's B row"
);
}
#[derive(Clone, PartialEq, Props)]
struct ScopedItemsProps {
items: Items,
}
#[component]
fn ScopedItemsHost(props: ScopedItemsProps) -> impl IntoElement {
view().flex_1().list(
props.items,
|list| list.flex_1().estimated_item_size(px(40.0)),
|row, _| row,
)
}
#[component]
fn ScopedItemsCaller() -> impl IntoElement {
view().flex_1().child(when(true, || {
provide_context(BranchContext("provided"));
ScopedItemsHost::element(ScopedItemsProps::initial())
.flex_1()
.items(virtual_list(1, |at| {
let label = use_context::<BranchContext>().map_or("missing", |c| c.0);
text(format!("{label} {}", at.index())).h(px(40.0))
}))
}))
}
#[test]
fn virtual_rows_passed_as_items_see_their_creators_context() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<ScopedItemsCaller>(|| ()));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["provided 0"]);
}
/// A chat: its own rows in a list that follows its end; a press makes
/// the last row taller (a reply streaming in).
#[component]
fn Chat() -> impl IntoElement {
let tall = signal(false);
view()
.flex_1()
.child(
view()
.h(px(20.0))
.on_press(move |_: &()| tall.update(|t| *t = !*t)),
)
.child(
virtual_list(20, move |at| {
view().h(move || {
px(if tall.get() && at.is_last() {
120.0
} else {
40.0
})
})
})
.estimated_item_size(px(40.0))
.follow_end(px(10.0))
.flex_1(),
)
}
#[test]
fn virtual_lists_follow_their_end() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Chat>(|| ()));
let batch = c.commit().unwrap();
let created = |kind: ViewKind| {
batch.items.iter().find_map(|i| match i {
MountItem::Create { id, kind: k } if *k == kind => Some(*id),
_ => None,
})
};
let list = created(ViewKind::Scroll).expect("a list");
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
let scrolled = |batch: &MountBatch| -> f32 {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ScrollBy { id, dy, .. } if *id == list => Some(dy.0),
_ => None,
})
.sum()
};
// At its end (20 rows of 40 in 460 points), the last row grows by
// 80: the list scrolls with it.
c.set_scroll_offset(list, point(px(0.0), px(800.0 - 460.0)), 0);
assert!(c.commit().is_none(), "every row is bound already");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert_eq!(scrolled(&c.commit().unwrap()), 80.0);
// Scrolled up, what is visible stays as the last row shrinks and
// grows again.
c.set_scroll_offset(list, point(px(0.0), px(100.0)), 1);
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert_eq!(scrolled(&c.commit().unwrap()), 0.0);
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert_eq!(scrolled(&c.commit().unwrap()), 0.0);
}
thread_local! {
/// How many times `Opened` was made on this thread.
static SETUPS: Cell<u32> = const { Cell::new(0) };
}
/// A drawer whose content (lazy children) shows while it is open.
#[derive(Clone, Copy, PartialEq, Props)]
struct DrawerProps {
#[prop(default)]
open: crate::element::Prop<bool>,
#[prop(lazy)]
children: Children,
}
#[component]
fn Drawer(props: DrawerProps) -> impl IntoElement {
view().child(when(props.open, move || view().p_2().child(props.children)))
}
/// Content with state of its own: the how-manieth it was made.
#[component]
fn Opened() -> impl IntoElement {
let n = SETUPS.with(|s| {
s.set(s.get() + 1);
s.get()
});
view().child(text(format!("opened {n}")))
}
/// Renders a drawer with content, opened and closed by a press.
#[component]
fn Shelf() -> impl IntoElement {
let open = signal(false);
view()
.child(
view()
.h(px(10.0))
.on_press(move |_: &()| open.update(|o| *o = !*o)),
)
.child(drawer().open(open).child(opened()))
}
#[test]
fn lazy_children_a_component_passes_are_made_while_placed() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Shelf>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
let instances = c.components.instances.len();
assert_eq!(SETUPS.with(Cell::get), 0, "closed: not made");
let events = js_events(&mut c);
assert!(events.is_empty(), "nothing for JS: {events:?}");
// Opened: made, and placed in the same commit.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["opened 1"]);
assert_eq!(c.components.instances.len(), instances + 1);
// Closed: released.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.commit();
assert_eq!(c.components.instances.len(), instances);
// Opened again: made afresh.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["opened 2"]);
let events = js_events(&mut c);
assert!(events.is_empty(), "nothing for JS: {events:?}");
}
/// A drawer in a drawer, both open while one signal says so: closing
/// closes both regions in one commit.
#[component]
fn NestedShelf() -> impl IntoElement {
let open = signal(false);
view()
.child(
view()
.h(px(10.0))
.on_press(move |_: &()| open.update(|o| *o = !*o)),
)
.child(
drawer()
.open(open)
.child(drawer().open(open).child(text("deep"))),
)
}
/// The outer drawer's region goes first: the run of the view that
/// passed the inner drawer its children is disposed, with the signal
/// saying whether the inner one places them, before the inner drawer's
/// own region (closing in the same commit) says it does not any more.
#[test]
fn nested_lazy_children_close_together() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<NestedShelf>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
let instances = c.components.instances.len();
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["deep"]);
// Both close in one commit: released, nothing written to what the
// disposed run made.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.commit();
assert_eq!(c.components.instances.len(), instances);
// And open again.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["deep"]);
}
/// Pastes the clipboard's text when pressed, if it holds some.
#[component]
fn Paster() -> impl IntoElement {
let pasted = signal(String::new());
view()
.child(text(move || format!("pasted {}", pasted.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let (has, text) = (clipboard_has_string(), clipboard_string());
spawn(async move {
let value = if has.await { text.await } else { "-".into() };
pasted.set(value);
});
}))
}
#[test]
fn components_read_the_clipboard() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Paster>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let reads: Vec<_> = c
.commit()
.unwrap()
.items
.into_iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command: Command::ReadClipboard { id, has_only },
} => Some((id, has_only)),
_ => None,
})
.collect();
assert_eq!(reads, [(1, true), (2, false)]);
// The platform answers both on the root.
for (id, has_only) in reads {
let mut payload = vec![
("id", crate::PayloadValue::Number(f64::from(id))),
("has", crate::PayloadValue::Bool(true)),
];
if !has_only {
payload.push(("text", crate::PayloadValue::Str("hello".into())));
}
assert!(c.component_event(ROOT_ID, EventKind::Clipboard, &EventPayload::Map(payload)));
}
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("pasted h")));
assert_eq!(shown.last().unwrap(), "pasted hello");
}
#[test]
fn a_clipboard_of_the_embedders_own_answers_in_place_of_the_platform() {
use crate::clipboard::{ClipboardBackend, MemoryClipboard};
let clipboard = std::sync::Arc::new(MemoryClipboard::new(Some("hello".into())));
let mut c = core();
c.set_clipboard(Some(clipboard.clone()));
c.mount_root(&crate::element::Root::new::<Paster>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
// Nothing goes to the platform: the reads are answered from it.
let items = c.commit().map(|b| b.items).unwrap_or_default();
assert!(
!items.iter().any(|i| matches!(
i,
MountItem::Command {
command: Command::ReadClipboard { .. },
..
}
)),
"{items:?}"
);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("pasted h")));
assert_eq!(shown.last().unwrap(), "pasted hello");
clipboard.set_text(None);
assert_eq!(clipboard.text(), None);
}
/// Copies twice when pressed and shows what became of each write.
#[component]
fn Copier() -> impl IntoElement {
let results = signal(String::new());
view()
.child(text(move || format!("copied {}", results.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let (first, second) = (
set_clipboard("a"),
set_clipboard_item(ClipboardItem {
text: "b".into(),
html: Some("<b>b</b>".into()),
}),
);
spawn(async move {
let (first, second) = (first.await, second.await);
results.set(format!("{first:?} {second:?}"));
});
}))
}
fn press_copier(c: &mut Core<FakeEngine>) -> Vec<Command> {
c.mount_root(&crate::element::Root::new::<Copier>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.commit()
.map(|b| b.items)
.unwrap_or_default()
.into_iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command,
} => Some(command),
_ => None,
})
.collect()
}
#[test]
fn clipboard_writes_answer_requested_where_the_platform_cannot_tell() {
let mut c = core();
let sent = press_copier(&mut c);
assert_eq!(sent.len(), 2, "{sent:?}");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("copied R")));
assert_eq!(shown.last().unwrap(), "copied Requested Requested");
}
#[test]
fn clipboard_writes_answer_what_the_platform_reports_in_order() {
let mut c = core();
c.set_environment(crate::element::Environment {
clipboard_write_result: true,
..Default::default()
});
let sent = press_copier(&mut c);
assert!(matches!(
sent[..],
[Command::SetClipboard(_), Command::SetClipboardItem(_)]
));
for written in [true, false] {
let payload = EventPayload::Map(vec![("written", crate::PayloadValue::Bool(written))]);
assert!(c.component_event(ROOT_ID, EventKind::ClipboardWrite, &payload));
}
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("copied W")));
assert_eq!(shown.last().unwrap(), "copied Written Failed");
}
#[test]
fn clipboard_writes_to_the_embedders_clipboard_are_written() {
let clipboard = std::sync::Arc::new(crate::clipboard::MemoryClipboard::new(None));
let mut c = core();
c.set_clipboard(Some(clipboard.clone()));
let sent = press_copier(&mut c);
assert!(sent.is_empty(), "{sent:?}");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("copied W")));
assert_eq!(shown.last().unwrap(), "copied Written Written");
}
/// Pastes the clipboard's image and files when pressed.
#[component]
fn ImagePaster() -> impl IntoElement {
let pasted = signal(String::new());
view()
.child(text(move || format!("pasted {}", pasted.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let (has, image, files) =
(clipboard_has_image(), clipboard_image(), clipboard_files());
spawn(async move {
let has = has.await;
let image = image
.await
.map(|i| format!("{}x{} {}", i.size.width.0, i.size.height.0, i.url));
let files = files.await.join(",");
pasted.set(format!("{has} {image:?} {files}"));
});
}))
}
#[test]
fn components_read_images_and_files_from_the_clipboard() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<ImagePaster>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let reads: Vec<_> = c
.commit()
.unwrap()
.items
.into_iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command:
command @ (Command::ReadClipboardImage { .. }
| Command::ReadClipboardFiles { .. }),
} => Some(command),
_ => None,
})
.collect();
assert_eq!(
reads,
[
Command::ReadClipboardImage {
id: 1,
has_only: true
},
Command::ReadClipboardImage {
id: 2,
has_only: false
},
Command::ReadClipboardFiles { id: 3 },
]
);
use crate::PayloadValue::{Bool, Number, Str};
let answers = [
vec![("id", Number(1.0)), ("has", Bool(true))],
vec![
("id", Number(2.0)),
("has", Bool(true)),
("uri", Str("data:image/png;base64,AA==".into())),
("width", Number(4.0)),
("height", Number(3.0)),
],
vec![
("id", Number(3.0)),
("has", Bool(true)),
("files", Str("file:///tmp/a%20b.png\nfile:///tmp/c/".into())),
],
];
for payload in answers {
assert!(c.component_event(ROOT_ID, EventKind::Clipboard, &EventPayload::Map(payload)));
}
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("pasted t")));
assert_eq!(
shown.last().unwrap(),
"pasted true Some(\"4x3 data:image/png;base64,AA==\") file:///tmp/a%20b.png,file:///tmp/c/"
);
}
/// Renders a drawing offscreen when pressed (`Painter::render`).
#[component]
fn OffscreenRenderer() -> impl IntoElement {
let shown = signal(String::new());
view()
.child(text(move || format!("render {}", shown.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let image = crate::element::Painter::new()
.fill_color(crate::Color(0xff00_00ff))
.fill_rect(0.0, 0.0, 30.0, 20.0)
.render(
crate::Size::new(px(30.0), px(20.0)),
crate::canvas::render::RenderOptions {
scale: Some(2.0),
..Default::default()
},
);
spawn(async move {
shown.set(match image.await {
Ok(bytes) => format!("ok {}", bytes.len()),
Err(e) => format!("failed {}", e.code().unwrap_or("")),
});
});
}))
}
fn press_offscreen_renderer(canvas_render: bool) -> (Core<FakeEngine>, Vec<Command>) {
let mut c = core();
c.set_environment(crate::element::Environment {
canvas_render,
..Default::default()
});
c.mount_root(&crate::element::Root::new::<OffscreenRenderer>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let renders = c
.commit()
.map(|b| b.items)
.unwrap_or_default()
.into_iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command: command @ Command::RenderCanvas { .. },
} => Some(command),
_ => None,
})
.collect();
(c, renders)
}
#[test]
fn components_render_drawings_offscreen() {
let (mut c, renders) = press_offscreen_renderer(true);
let [
Command::RenderCanvas {
id,
drawing,
width,
height,
scale,
..
},
] = &renders[..]
else {
panic!("one render: {renders:?}");
};
assert_eq!((*width, *height, *scale), (60, 40, 2.0));
assert!(
drawing
.ops
.iter()
.any(|op| matches!(op, crate::canvas::CanvasOp::FillRect(_)))
);
assert!(c.component_event(
ROOT_ID,
EventKind::CanvasImage,
&EventPayload::CanvasImage {
id: *id,
result: Ok(vec![1, 2, 3, 4])
},
));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("render ok")));
assert_eq!(shown.last().unwrap(), "render ok 4");
}
fn render_id(renders: &[Command]) -> u32 {
match renders {
[Command::RenderCanvas { id, .. }] => *id,
_ => panic!("one render: {renders:?}"),
}
}
#[test]
fn offscreen_renders_take_ids_unique_in_the_process() {
// A replaced core's render may still be answered: the new core's
// requests must not share its number.
let (_old, old) = press_offscreen_renderer(true);
let (mut c, renders) = press_offscreen_renderer(true);
let (old, id) = (render_id(&old), render_id(&renders));
assert_ne!(old, id);
assert!(c.component_event(
ROOT_ID,
EventKind::CanvasImage,
&EventPayload::CanvasImage {
id: old,
result: Ok(vec![9]),
},
));
assert!(c.component_event(
ROOT_ID,
EventKind::CanvasImage,
&EventPayload::CanvasImage {
id,
result: Ok(vec![1, 2]),
},
));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("render ok")));
assert_eq!(shown.last().unwrap(), "render ok 2");
}
#[test]
fn offscreen_renders_too_large_for_the_platform_fail_with_the_quota_code() {
let (mut c, renders) = press_offscreen_renderer(true);
assert!(c.component_event(
ROOT_ID,
EventKind::CanvasImage,
&EventPayload::CanvasImage {
id: render_id(&renders),
result: Err(crate::canvas::render::RenderFailure::TooLarge(
"over the device's bitmap limit".into()
)),
},
));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("render failed")));
assert_eq!(
shown.last().unwrap(),
"render failed ERR_NSH_QUOTA_EXCEEDED"
);
}
#[test]
fn offscreen_renders_fail_by_their_deadline_and_drop_late_answers() {
let (mut c, renders) = press_offscreen_renderer(true);
let id = render_id(&renders);
c.timeout_canvas_render(id);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("render failed")));
assert_eq!(shown.last().unwrap(), "render failed ETIMEDOUT");
assert!(c.components.canvas_renders.is_empty());
assert!(c.component_event(
ROOT_ID,
EventKind::CanvasImage,
&EventPayload::CanvasImage {
id,
result: Ok(vec![1]),
},
));
c.run_component_tasks();
let shown = c.commit().map(|b| texts(&b)).unwrap_or_default();
assert!(
!shown.iter().any(|t| t.starts_with("render ok")),
"{shown:?}"
);
}
#[test]
fn components_render_nothing_offscreen_where_the_platform_renders_none() {
let (mut c, renders) = press_offscreen_renderer(false);
assert!(renders.is_empty(), "{renders:?}");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("render failed")));
assert_eq!(
shown.last().unwrap(),
"render failed ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"
);
}
/// An offscreen render checks its images as a canvas drawing does: a
/// source the app may not load is dropped before the platform sees it,
/// one it may is rewritten to what the check granted.
#[test]
fn offscreen_renders_check_their_images() {
let mut c = core();
c.set_environment(crate::element::Environment {
canvas_render: true,
..Default::default()
});
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "network": { "hosts": ["docs.example.com"] } }),
)
.unwrap(),
granted: None,
}));
let image = |uri: &str| crate::canvas::CanvasOp::DrawImage {
image: crate::canvas::CanvasImage { uri: uri.into() },
source: None,
dest: [crate::canvas::Num::Const(0.0); 4],
};
let (_answer, slot) = crate::element::task::Answer::new();
c.start_canvas_render(
crate::canvas::render::RenderRequest {
drawing: crate::canvas::Drawing {
ops: vec![
image("https://docs.example.com/a/../x.png"),
image("https://refused.example.com/x.png"),
],
..Default::default()
},
size: crate::Size::new(px(30.0), px(20.0)),
..Default::default()
},
slot,
);
let batch = c.commit().unwrap();
let uris: Vec<String> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Command {
command: Command::RenderCanvas { drawing, .. },
..
} => Some(drawing),
_ => None,
})
.flat_map(|d| d.ops.iter())
.filter_map(|op| match op {
crate::canvas::CanvasOp::DrawImage { image, .. } => Some(image.uri.to_string()),
_ => None,
})
.collect();
assert_eq!(uris, ["https://docs.example.com/x.png"]);
}
#[test]
fn components_read_images_over_the_limit_as_none() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<ImagePaster>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.commit().unwrap();
use crate::PayloadValue::{Bool, Number, Str};
let limit = crate::platform::clipboard::MAX_IMAGE_BYTES;
let answers = [
vec![("id", Number(1.0)), ("has", Bool(true))],
// The size of an image the platform left out.
vec![
("id", Number(2.0)),
("has", Bool(true)),
("tooLarge", Number((limit + 1) as f64)),
],
vec![
("id", Number(3.0)),
("has", Bool(false)),
("files", Str(String::new())),
],
];
for payload in answers {
assert!(c.component_event(ROOT_ID, EventKind::Clipboard, &EventPayload::Map(payload)));
}
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("pasted t")));
assert_eq!(shown.last().unwrap(), "pasted true None ");
}
#[test]
fn clipboard_images_need_the_capability() {
let mut c = core();
c.set_access(std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({})).unwrap(),
granted: None,
}));
c.mount_root(&crate::element::Root::new::<ImagePaster>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let items = c.commit().map(|b| b.items).unwrap_or_default();
assert!(
!items.iter().any(|i| matches!(i, MountItem::Command { .. })),
"nothing reaches the platform"
);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("pasted f")));
assert_eq!(shown.last().unwrap(), "pasted false None ");
}
/// Picks up to two photos when pressed and shows what came.
#[component]
fn PhotoPicker() -> impl IntoElement {
let picked = signal(String::new());
view()
.child(text(move || format!("picked {}", picked.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let files = pick_images(crate::picker::PickRequest::new(true, 2));
spawn(async move {
let files = files.await;
let shown: Vec<String> = files
.iter()
.map(|f| {
format!(
"{} {} {}x{} {}",
f.name,
f.mime,
f.size.width.0,
f.size.height.0,
f.data.len()
)
})
.collect();
picked.set(format!("{} [{}]", files.len(), shown.join(", ")));
});
}))
}
/// A 3×2 PNG's header.
fn png_header() -> Vec<u8> {
vec![
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, b'I', b'H', b'D', b'R', 0,
0, 0, 3, 0, 0, 0, 2, 8, 6, 0, 0, 0,
]
}
fn press_picker(c: &mut Core<FakeEngine>) -> Vec<MountItem> {
c.mount_root(&crate::element::Root::new::<PhotoPicker>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.commit().map(|b| b.items).unwrap_or_default()
}
#[test]
fn picked_files_answer_the_pick() {
let mut c = core();
let items = press_picker(&mut c);
let picks: Vec<_> = items
.into_iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command: Command::PickImages { id, request },
} => Some((id, request)),
_ => None,
})
.collect();
assert_eq!(picks.len(), 1);
let (id, request) = picks[0];
assert_eq!(request.limit, 2);
let file = |name: &str| crate::picker::PickedFile {
name: name.into(),
data: crate::ImageData::new(png_header()),
..Default::default()
};
// The platform's answer is completed (type, size, extension) and
// cut to the request's limit.
let files = vec![file("IMG_1"), file("b.png"), file("c.png")];
assert!(c.component_event(
ROOT_ID,
EventKind::Pick,
&EventPayload::Picked { id, files }
));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("picked 2")));
assert_eq!(
shown.last().unwrap(),
"picked 2 [IMG_1.png image/png 3x2 29, b.png image/png 3x2 29]"
);
}
struct TestPicker;
impl crate::picker::PickerBackend for TestPicker {
fn pick_images(&self, request: crate::picker::PickRequest) -> crate::picker::PickFuture {
assert_eq!(request.limit, 2);
Box::pin(async {
vec![crate::picker::PickedFile::new(
"x.png",
"",
crate::ImageData::new(png_header()),
)]
})
}
}
#[test]
fn a_picker_of_the_embedder_answers_in_place_of_the_platform() {
let mut c = core();
c.set_picker(Some(std::sync::Arc::new(TestPicker)));
let items = press_picker(&mut c);
assert!(
!items.iter().any(|i| matches!(i, MountItem::Command { .. })),
"nothing reaches the platform"
);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("picked 1")));
assert_eq!(shown.last().unwrap(), "picked 1 [x.png image/png 3x2 29]");
}
#[test]
fn picks_need_the_capability() {
let mut c = core();
c.set_access(std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({})).unwrap(),
granted: None,
}));
let items = press_picker(&mut c);
assert!(
!items.iter().any(|i| matches!(i, MountItem::Command { .. })),
"nothing reaches the platform"
);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("picked 0")));
assert_eq!(shown.last().unwrap(), "picked 0 []");
}
/// Asks whether the app's settings page opens here and opens it when
/// its button is pressed; shows both answers.
#[component]
fn SettingsOpener() -> impl IntoElement {
use crate::mobile::{app_settings_available, open_app_settings};
let shown = signal(String::new());
view()
.child(text(move || format!("settings{}", shown.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let available = app_settings_available();
let opened = open_app_settings();
spawn(async move {
let available = available.await;
let opened = match opened.await {
Ok(opened) => opened.to_string(),
Err(error) => format!("{error:?}"),
};
shown.set(format!(" {available} {opened}"));
});
}))
}
/// Mounts [`SettingsOpener`] in `environment` with `capabilities`
/// declared (`None`: none), presses its button and returns the requests
/// that reached the platform.
fn press_settings_opener(
environment: crate::element::Environment,
capabilities: Option<serde_json::Value>,
) -> (Core<FakeEngine>, Vec<u32>) {
let mut c = core();
if let Some(capabilities) = capabilities {
c.set_access(std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&capabilities).unwrap(),
granted: None,
}));
}
c.set_environment(environment);
c.mount_root(&crate::element::Root::new::<SettingsOpener>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let items = c.commit().map(|b| b.items).unwrap_or_default();
let requests = items
.into_iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command: Command::OpenAppSettings { id },
} => Some(id),
_ => None,
})
.collect();
(c, requests)
}
#[test]
fn app_settings_fail_at_once_where_the_platform_has_none() {
let (mut c, requests) = press_settings_opener(Default::default(), None);
assert!(requests.is_empty(), "nothing reaches the platform");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("settings ")));
assert_eq!(shown.last().unwrap(), "settings false Unavailable");
}
#[test]
fn app_settings_open_on_the_platform_and_answer_what_it_reports() {
let (mut c, requests) = press_settings_opener(
crate::element::Environment {
app_settings: true,
..Default::default()
},
Some(serde_json::json!({ "application": true })),
);
assert_eq!(requests.len(), 1, "one request reaches the platform");
// An answer of another request settles nothing.
let answer = |id: u32, opened: bool| {
EventPayload::Map(vec![
("id", crate::PayloadValue::Number(f64::from(id))),
("opened", crate::PayloadValue::Bool(opened)),
])
};
assert!(c.component_event(
ROOT_ID,
EventKind::OpenAppSettings,
&answer(requests[0].wrapping_add(1), false)
));
c.run_component_tasks();
assert!(c.commit().is_none_or(|b| texts(&b).is_empty()));
assert!(c.component_event(
ROOT_ID,
EventKind::OpenAppSettings,
&answer(requests[0], true)
));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("settings ")));
assert_eq!(shown.last().unwrap(), "settings true true");
}
#[test]
fn app_settings_need_the_application_capability_when_capabilities_are_declared() {
let (mut c, requests) = press_settings_opener(
crate::element::Environment {
app_settings: true,
..Default::default()
},
Some(serde_json::json!({ "share": true })),
);
assert!(requests.is_empty(), "nothing reaches the platform");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("settings ")));
assert_eq!(shown.last().unwrap(), "settings false Denied");
}
/// Turns launching at login on, reads it, turns it off and reads it
/// again when its button is pressed, all asked at once; shows each
/// answer in the order it was asked.
#[component]
fn LoginSwitch() -> impl IntoElement {
use crate::{
desktop::LaunchAtLoginError,
element::desktop::{launch_at_login, set_launch_at_login},
};
let shown = signal(String::new());
let add = move |line: String| shown.set(format!("{} {line}", untracked(|| shown.get())));
let said = |answer: Result<(), LaunchAtLoginError>| match answer {
Ok(()) => "ok".to_owned(),
Err(LaunchAtLoginError::System(e)) => {
format!("failed-{}", crate::element::io_code(&e).unwrap_or("none"))
}
Err(e) => format!("{e:?}"),
};
view()
.child(text(move || format!("login{}", shown.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let on = set_launch_at_login(true);
let read = launch_at_login();
let off = set_launch_at_login(false);
let again = launch_at_login();
spawn(async move {
add(said(on.await));
add(read.await.to_string());
add(said(off.await));
add(again.await.to_string());
});
}))
}
/// The login item of a test: the calls it got, in order.
#[derive(Default)]
struct FakeLoginItem {
calls: std::sync::Mutex<Vec<Option<bool>>>,
enabled: std::sync::Mutex<bool>,
/// Changes fail as the system's refusal does.
refuses: bool,
/// The platform has no login item for the app (a sandbox).
sandboxed: bool,
}
impl crate::desktop::LoginItemBackend for FakeLoginItem {
fn status(&self) -> std::io::Result<crate::desktop::LoginItemStatus> {
use crate::desktop::LoginItemStatus;
self.calls.lock().unwrap().push(None);
Ok(if self.sandboxed {
LoginItemStatus::Unavailable
} else if *self.enabled.lock().unwrap() {
LoginItemStatus::Enabled
} else {
LoginItemStatus::Disabled
})
}
fn set(&self, enabled: bool) -> std::io::Result<crate::desktop::LoginItemStatus> {
if self.refuses {
return Err(std::io::ErrorKind::PermissionDenied.into());
}
// A slow registration: what was asked after it still waits.
if enabled {
std::thread::sleep(std::time::Duration::from_millis(30));
}
if !self.sandboxed {
*self.enabled.lock().unwrap() = enabled;
}
self.calls.lock().unwrap().push(Some(enabled));
self.status()
}
}
/// Mounts [`LoginSwitch`] in `c`, presses it and gives what it showed
/// once the four answers came.
fn switch_login_item(
c: &mut Core<FakeEngine>,
backend: Option<std::sync::Arc<FakeLoginItem>>,
) -> String {
c.set_login_item(
backend.map(|b| b as std::sync::Arc<dyn crate::desktop::LoginItemBackend>),
);
c.mount_root(&crate::element::Root::new::<LoginSwitch>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let shown = run_until(c, |s| {
s.last()
.is_some_and(|t| t.starts_with("login") && t.split(' ').count() == 5)
});
shown.last().unwrap().clone()
}
#[test]
fn launch_at_login_needs_the_application() {
// It acts on the application as a whole, as quit and restart do:
// an app declaring capabilities needs `application`, and without it
// reads that it does not launch at login and cannot change it, the
// backend untouched.
let declared = |caps: serde_json::Value| {
std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&caps).unwrap(),
granted: None,
})
};
let backend = std::sync::Arc::new(FakeLoginItem::default());
let mut c = core();
c.set_access(declared(serde_json::json!({})));
let shown = switch_login_item(&mut c, Some(backend.clone()));
assert_eq!(shown, "login Denied false Denied false");
assert!(backend.calls.lock().unwrap().is_empty());
let mut c = core();
c.set_access(declared(serde_json::json!({ "application": true })));
let shown = switch_login_item(&mut c, Some(backend.clone()));
assert_eq!(shown, "login ok true ok false");
}
#[test]
fn without_a_backend_the_app_has_no_login_item() {
// Reading answers `false`; changing it fails.
let shown = switch_login_item(&mut core(), None);
assert_eq!(shown, "login Unavailable false Unavailable false");
}
#[test]
fn the_backend_reads_and_changes_the_login_item_in_order() {
let backend = std::sync::Arc::new(FakeLoginItem::default());
let shown = switch_login_item(&mut core(), Some(backend.clone()));
assert_eq!(shown, "login ok true ok false");
// Each change reads the status after it; the slow registration ran
// before what was asked after it.
assert_eq!(
*backend.calls.lock().unwrap(),
[Some(true), None, None, Some(false), None, None]
);
}
#[test]
fn the_systems_refusal_and_a_sandbox_reach_the_app() {
let refuses = std::sync::Arc::new(FakeLoginItem {
refuses: true,
..Default::default()
});
let shown = switch_login_item(&mut core(), Some(refuses));
assert_eq!(shown, "login failed-EACCES false failed-EACCES false");
// Where the platform has no login item for the app, a change fails
// as without a backend.
let sandboxed = std::sync::Arc::new(FakeLoginItem {
sandboxed: true,
..Default::default()
});
let shown = switch_login_item(&mut core(), Some(sandboxed));
assert_eq!(shown, "login Unavailable false Unavailable false");
}
/// Shows the later launches of the app it hears.
#[component]
fn Relaunched() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
loop {
let launch = next_second_instance().await;
let line = format!("{} in {}", launch.args.join(","), launch.cwd);
shown.set(format!("{} [{line}]", untracked(|| shown.get())));
}
});
view().child(text(move || format!("launches{}", shown.get())))
}
#[test]
fn later_launches_wait_for_the_app_and_come_in_order() {
use crate::single_instance::SecondInstance;
let mut c = core();
let launch = |c: &mut Core<FakeEngine>, args: &[&str]| {
let args = args.iter().map(|a| a.to_string()).collect();
c.component_event(
crate::ROOT_ID,
EventKind::SecondInstance,
&SecondInstance::new(args, "/home/u").to_payload(),
);
};
// Before the app listens: kept for it.
launch(&mut c, &["a.txt"]);
c.mount_root(&crate::element::Root::new::<Relaunched>(|| ()));
c.commit();
launch(&mut c, &["--new", "b.txt"]);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("b.txt")));
assert_eq!(
shown.last().unwrap(),
"launches [a.txt in /home/u] [--new,b.txt in /home/u]"
);
// Not a launch: dropped.
assert!(!c.component_event(
crate::ROOT_ID,
EventKind::SecondInstance,
&EventPayload::None
));
}
/// Adds `line` to what `shown` says.
fn say(shown: Signal<String>, line: String) {
shown.set(format!("{} {line}", untracked(|| shown.get())));
}
/// Reports `url` as a link the system handed the app.
fn open_link(c: &mut Core<FakeEngine>, url: &str) {
c.component_event(
crate::ROOT_ID,
EventKind::UrlScheme,
&EventPayload::Map(vec![(
crate::url_scheme::URL,
crate::PayloadValue::Str(url.to_owned()),
)]),
);
}
/// Hears the app's links as long as it runs, as an app does, and once
/// more in a second task that starts after it, as a module waiting for
/// one link does.
#[component]
fn TwoLinkListeners() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
loop {
say(shown, format!("app:{}", next_url_scheme_open().await));
}
});
spawn(async move {
say(shown, format!("once:{}", next_url_scheme_open().await));
});
view().child(text(move || format!("links{}", shown.get())))
}
#[test]
fn a_later_link_listener_leaves_the_earlier_listening() {
let mut c = core();
c.set_url_schemes(["myapp"]);
c.mount_root(&crate::element::Root::new::<TwoLinkListeners>(|| ()));
c.commit();
c.run_component_tasks();
c.commit();
open_link(&mut c, "myapp://a");
run_until(&mut c, |s| s.iter().any(|t| t.contains("once:")));
open_link(&mut c, "myapp://b");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("app:myapp://b")));
// Both heard the first; the app's listener still hears the next.
assert_eq!(
shown.last().unwrap(),
"links app:myapp://a once:myapp://a app:myapp://b"
);
}
/// Runs the tasks and commits for 100 ms, past the listeners' timers,
/// adding the texts shown.
fn settle(c: &mut Core<FakeEngine>, shown: &mut Vec<String>) {
let end = std::time::Instant::now() + std::time::Duration::from_millis(100);
while std::time::Instant::now() < end {
run_briefly(c, shown);
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
/// Runs the tasks and commits a few times, adding the texts shown: not
/// long enough for the listeners' timers.
fn run_briefly(c: &mut Core<FakeEngine>, shown: &mut Vec<String>) {
for _ in 0..5 {
c.run_component_tasks();
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
}
}
}
/// The last text shown that starts with `prefix`.
fn last_shown(shown: &[String], prefix: &str) -> String {
shown
.iter()
.rfind(|t| t.starts_with(prefix))
.cloned()
.unwrap_or_default()
}
/// The node that takes presses.
fn pressable(items: &[MountItem]) -> NodeId {
items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap()
}
/// Two listeners hearing the app's links as long as it runs, as the TS
/// runtime's and a Rust module's, each taking a while over a link; a
/// press starts a third.
#[component]
fn LinkLoops() -> impl IntoElement {
let a = signal(String::new());
let b = signal(String::new());
let c = signal(String::new());
let listen = move |heard: Signal<String>| {
spawn(async move {
loop {
say(heard, next_url_scheme_open().await);
timer(std::time::Duration::from_millis(20)).await;
}
});
};
listen(a);
listen(b);
view()
.child(text(move || format!("a:{}", a.get())))
.child(text(move || format!("b:{}", b.get())))
.child(text(move || format!("c:{}", c.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| listen(c)))
}
#[test]
fn listeners_in_a_loop_hear_every_link_of_a_burst() {
let mut c = core();
c.set_url_schemes(["myapp"]);
// The link that launched the app, before anything listened.
open_link(&mut c, "myapp://launch");
c.mount_root(&crate::element::Root::new::<LinkLoops>(|| ()));
let mut shown: Vec<String> = c.commit().map(|b| texts(&b)).unwrap_or_default();
settle(&mut c, &mut shown);
// Links in a burst, before the listeners run again.
open_link(&mut c, "myapp://1");
open_link(&mut c, "myapp://2");
open_link(&mut c, "myapp://3");
settle(&mut c, &mut shown);
// Each loop hears the links that came while it handled the one
// before; the one that came while nothing listened goes to the
// first listener only.
assert_eq!(
[last_shown(&shown, "a:"), last_shown(&shown, "b:")],
[
"a: myapp://launch myapp://1 myapp://2 myapp://3",
"b: myapp://1 myapp://2 myapp://3"
]
);
}
#[test]
fn a_new_listener_does_not_hear_links_that_came_while_others_listened() {
let mut c = core();
c.set_url_schemes(["myapp"]);
c.mount_root(&crate::element::Root::new::<LinkLoops>(|| ()));
let batch = c.commit().unwrap();
let button = pressable(&batch.items);
let mut shown = texts(&batch);
settle(&mut c, &mut shown);
// The second comes while both loops handle the first: theirs, not
// the third listener's, which starts after it and asks before they
// ask again.
open_link(&mut c, "myapp://1");
run_briefly(&mut c, &mut shown);
open_link(&mut c, "myapp://2");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
run_briefly(&mut c, &mut shown);
settle(&mut c, &mut shown);
open_link(&mut c, "myapp://3");
settle(&mut c, &mut shown);
assert_eq!(
[
last_shown(&shown, "a:"),
last_shown(&shown, "b:"),
last_shown(&shown, "c:")
],
[
"a: myapp://1 myapp://2 myapp://3",
"b: myapp://1 myapp://2 myapp://3",
"c: myapp://3"
]
);
}
/// Hears the app's links in a loop; a second task listens once, then
/// again only after a later launch of the app.
#[component]
fn OccasionalLinkListener() -> impl IntoElement {
let a = signal(String::new());
let once = signal(String::new());
spawn(async move {
loop {
say(a, next_url_scheme_open().await);
}
});
spawn(async move {
say(once, next_url_scheme_open().await);
next_second_instance().await;
say(once, next_url_scheme_open().await);
say(once, next_url_scheme_open().await);
});
view()
.child(text(move || format!("a:{}", a.get())))
.child(text(move || format!("once:{}", once.get())))
}
#[test]
fn a_task_that_listened_hears_what_came_since_at_its_next_call() {
use crate::single_instance::SecondInstance;
let mut c = core();
c.set_url_schemes(["myapp"]);
c.mount_root(&crate::element::Root::new::<OccasionalLinkListener>(|| ()));
let mut shown: Vec<String> = c.commit().map(|b| texts(&b)).unwrap_or_default();
settle(&mut c, &mut shown);
for url in ["myapp://1", "myapp://2", "myapp://3"] {
open_link(&mut c, url);
settle(&mut c, &mut shown);
}
c.component_event(
crate::ROOT_ID,
EventKind::SecondInstance,
&SecondInstance::new(Vec::new(), "/").to_payload(),
);
settle(&mut c, &mut shown);
// The task listens as long as it lives: its next calls get the
// links that came since its last, which the loop handled long ago.
assert_eq!(
[last_shown(&shown, "a:"), last_shown(&shown, "once:")],
[
"a: myapp://1 myapp://2 myapp://3",
"once: myapp://1 myapp://2 myapp://3"
]
);
}
/// Hears the app's links as long as it runs; a press starts a sign-in
/// session that waits for one link of `auth`, and a second press one
/// it drops before the link comes.
#[component]
fn LinksAndSession() -> impl IntoElement {
let shown = signal(String::new());
let presses = std::rc::Rc::new(std::cell::Cell::new(0));
spawn(async move {
loop {
say(shown, format!("app:{}", next_url_scheme_open().await));
}
});
view()
.child(text(move || format!("links{}", shown.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
presses.set(presses.get() + 1);
if presses.get() == 1 {
spawn(async move {
say(shown, "waits".into());
let callback = next_url_scheme_open_for("Auth");
say(shown, format!("session:{}", callback.await));
});
} else {
spawn(async move {
drop(next_url_scheme_open_for("auth"));
say(shown, "gave-up".into());
});
}
}))
}
#[test]
fn a_wait_for_a_scheme_takes_its_link_and_leaves_the_app_listening() {
let mut c = core();
c.set_url_schemes(["myapp", "auth"]);
// Came before the session: the app's.
open_link(&mut c, "auth://early");
c.mount_root(&crate::element::Root::new::<LinksAndSession>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap();
run_until(&mut c, |s| s.iter().any(|t| t.contains("app:auth://early")));
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
run_until(&mut c, |s| s.iter().any(|t| t.contains("waits")));
open_link(&mut c, "myapp://orders/1");
open_link(&mut c, "AUTH://cb?code=1");
open_link(&mut c, "myapp://orders/2");
open_link(&mut c, "auth://after");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("app:auth://after")));
// The session took its callback alone; the app heard the rest, the
// scheme's links after the session ended included.
assert_eq!(
shown.last().unwrap(),
"links app:auth://early waits app:myapp://orders/1 session:AUTH://cb?code=1 \
app:myapp://orders/2 app:auth://after"
);
// The callback is not the app's address.
assert_eq!(c.app_url_cell().get().as_deref(), Some("auth://after"));
// A session that gave up takes nothing.
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
run_until(&mut c, |s| s.iter().any(|t| t.contains("gave-up")));
open_link(&mut c, "auth://late");
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("app:auth://late")));
assert!(shown.last().unwrap().ends_with("gave-up app:auth://late"));
}
/// Waits for a link and drops the wait before it comes (as the losing
/// branch of a `select!`), then, on a press, listens.
#[component]
fn DroppedLinkWait() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
drop(next_url_scheme_open());
say(shown, "dropped".into());
});
view()
.child(text(move || format!("links{}", shown.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
spawn(async move {
say(shown, format!("heard:{}", next_url_scheme_open().await));
});
}))
}
#[test]
fn a_dropped_link_wait_leaves_the_link_for_the_next_listener() {
let mut c = core();
c.set_url_schemes(["myapp"]);
c.mount_root(&crate::element::Root::new::<DroppedLinkWait>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap();
c.run_component_tasks();
c.commit();
// Nothing listens: kept for the next listener, not given to the
// dropped wait.
open_link(&mut c, "myapp://kept");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("heard:")));
assert_eq!(shown.last().unwrap(), "links dropped heard:myapp://kept");
}
/// Asks for the permission, shows a notification and sets the badge when
/// its button is pressed; shows the answers and the presses.
#[component]
fn Notifier() -> impl IntoElement {
let shown = signal(String::new());
let add = move |line: String| shown.set(format!("{} {line}", untracked(|| shown.get())));
spawn(async move {
loop {
add(format!("pressed {}", next_notification_press().await));
}
});
view()
.child(text(move || format!("said{}", shown.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
set_badge(3);
close_notification("a");
close_all_notifications();
spawn(async move {
let permission = request_notification_permission().await;
add(permission.as_str().to_owned());
let shown = show_notification(crate::notifications::Notification::new(
"a", "Title", "Body",
))
.await;
add(format!("shown {shown}"));
});
}))
}
/// Mounts [`Notifier`] and presses its button: the commands sent.
fn notify(c: &mut Core<FakeEngine>) -> Vec<crate::notifications::NotificationCommand> {
c.mount_root(&crate::element::Root::new::<Notifier>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap();
let mut commands = notification_commands(&batch.items);
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
commands.extend(notification_commands(
&c.commit().map(|b| b.items).unwrap_or_default(),
));
commands
}
/// Runs the tasks: the commands they and what came before them sent.
fn tasks_commands(c: &mut Core<FakeEngine>) -> Vec<crate::notifications::NotificationCommand> {
c.run_component_tasks();
notification_commands(&c.commit().map(|b| b.items).unwrap_or_default())
}
fn notification_commands(
items: &[MountItem],
) -> Vec<crate::notifications::NotificationCommand> {
items
.iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command: Command::Notification(command),
} => Some(command.clone()),
_ => None,
})
.collect()
}
fn notification_event(c: &mut Core<FakeEngine>, fields: Vec<(&'static str, PayloadValue)>) {
assert!(c.component_event(ROOT_ID, EventKind::Notification, &EventPayload::Map(fields)));
}
#[test]
fn notifications_go_through_the_platform() {
use crate::notifications::{NotificationCommand as N, NotificationEvent as Field};
let mut c = core();
c.set_environment(crate::element::Environment {
notifications: true,
..Default::default()
});
let mut commands = notify(&mut c);
commands.extend(tasks_commands(&mut c));
assert_eq!(
commands[..],
[
N::SetBadge(3),
N::Close("a".into()),
N::CloseAll,
N::Listen,
N::Permission { id: 0, ask: true }
]
);
notification_event(
&mut c,
vec![
(Field::ID, PayloadValue::Number(0.0)),
(Field::PERMISSION, PayloadValue::Str("granted".into())),
],
);
let commands = tasks_commands(&mut c);
let [
N::Show {
id: 1,
notification,
},
] = &commands[..]
else {
panic!("one notification: {commands:?}");
};
assert_eq!(
*notification,
crate::notifications::Notification::new("a", "Title", "Body")
);
notification_event(
&mut c,
vec![
(Field::ID, PayloadValue::Number(1.0)),
(Field::SHOWN, PayloadValue::Bool(true)),
],
);
run_until(&mut c, |s| s.iter().any(|t| t.contains("shown true")));
// One after the other: the second waits for the listener to come back.
notification_event(
&mut c,
vec![(Field::PRESSED, PayloadValue::Str("a".into()))],
);
notification_event(
&mut c,
vec![(Field::PRESSED, PayloadValue::Str("b".into()))],
);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("pressed b")));
assert_eq!(
shown.last().unwrap(),
"said granted shown true pressed a pressed b"
);
}
#[test]
fn notifications_answer_at_once_where_the_platform_shows_none() {
use crate::notifications::NotificationCommand as N;
let mut c = core();
// The badge is the platform's to do or ignore.
assert_eq!(notify(&mut c), vec![N::SetBadge(3)]);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("shown")));
assert_eq!(shown.last().unwrap(), "said unavailable shown false");
}
#[test]
fn notifications_need_the_capability() {
let mut c = core();
c.set_environment(crate::element::Environment {
notifications: true,
..Default::default()
});
c.set_access(std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({})).unwrap(),
granted: None,
}));
assert_eq!(notify(&mut c), vec![]);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.contains("shown")));
assert_eq!(shown.last().unwrap(), "said unavailable shown false");
}
/// Shows whether a web view's ref gives trusted input here.
#[component]
fn WebInputCheck() -> impl IntoElement {
let available = signal(String::from("asking"));
spawn(async move {
available.set(format!("web input {}", web_input_available().await));
});
text(move || available.get())
}
/// What [`WebInputCheck`] shows on a platform that does (`platform`)
/// or does not deliver trusted web input, with the capabilities
/// `declared` (`None`: none declared).
fn web_input_available_with(platform: bool, declared: Option<serde_json::Value>) -> String {
let mut c = core();
c.set_environment(crate::element::Environment {
web_input: platform,
..Default::default()
});
if let Some(declared) = declared {
c.set_access(std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&declared).unwrap(),
granted: None,
}));
}
c.mount_root(&crate::element::Root::new::<WebInputCheck>(|| ()));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("web input")));
shown.last().unwrap().clone()
}
/// Evaluates a script that never answers in a web view, with a short
/// timeout, and shows whether the platform evaluates and how it ended.
#[component]
fn EvaluateCheck() -> impl IntoElement {
let shown = signal(String::from("asking"));
let page = element_ref();
spawn(async move {
let available = web_evaluate_available().await;
let options = EvaluateOptions {
timeout: std::time::Duration::from_millis(5),
};
let code = match page.evaluate("new Promise(() => {})", options).await {
Ok(evaluation) => format!("value {}", evaluation.value),
Err(error) => error.code().unwrap_or("none").to_owned(),
};
shown.set(format!("evaluate {available} {code}"));
});
view()
.child(web_view("about:blank").element_ref(&page))
.child(text(move || shown.get()))
}
#[test]
fn evaluate_answers_by_its_timeout_where_the_platform_evaluates() {
let shown = |platform: bool| {
let mut c = core();
c.set_environment(crate::element::Environment {
web_evaluate: platform,
..Default::default()
});
c.mount_root(&crate::element::Root::new::<EvaluateCheck>(|| ()));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("evaluate ")));
shown.last().unwrap().clone()
};
assert_eq!(shown(true), "evaluate true ETIMEDOUT");
assert_eq!(
shown(false),
"evaluate false ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"
);
}
#[test]
fn web_input_is_available_where_the_platform_delivers_it_and_the_app_holds_the_grant() {
let granted = || Some(serde_json::json!({ "webview": { "hosts": [], "input": true } }));
assert_eq!(web_input_available_with(true, granted()), "web input true");
// The platform does not deliver it.
assert_eq!(
web_input_available_with(false, granted()),
"web input false"
);
// Web views without `input`, or no declaration at all: not granted.
assert_eq!(
web_input_available_with(
true,
Some(serde_json::json!({ "webview": { "hosts": [] } }))
),
"web input false"
);
assert_eq!(web_input_available_with(true, None), "web input false");
assert_eq!(web_input_available_with(false, None), "web input false");
}
/// Shows whether a web view shows a page here.
#[component]
fn WebViewCheck() -> impl IntoElement {
let available = signal(String::from("asking"));
spawn(async move {
available.set(format!("web views {}", web_view_available().await));
});
text(move || available.get())
}
/// What [`WebViewCheck`] shows on a platform that does (`platform`) or
/// does not show web views, with the capabilities `declared` (`None`:
/// none declared).
fn web_view_available_with(platform: bool, declared: Option<serde_json::Value>) -> String {
let mut c = core();
c.set_environment(crate::element::Environment {
web_views: platform,
..Default::default()
});
if let Some(declared) = declared {
c.set_access(std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&declared).unwrap(),
granted: None,
}));
}
c.mount_root(&crate::element::Root::new::<WebViewCheck>(|| ()));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("web views")));
shown.last().unwrap().clone()
}
#[test]
fn web_views_are_available_where_the_platform_shows_them_and_the_app_holds_the_grant() {
assert_eq!(web_view_available_with(true, None), "web views true");
assert_eq!(web_view_available_with(false, None), "web views false");
let hosts = || Some(serde_json::json!({ "webview": { "hosts": [] } }));
assert_eq!(web_view_available_with(true, hosts()), "web views true");
assert_eq!(web_view_available_with(false, hosts()), "web views false");
// Capabilities without `webview`: not granted.
assert_eq!(
web_view_available_with(true, Some(serde_json::json!({}))),
"web views false"
);
}
/// A web view that says when the platform shows none.
#[component]
fn UnavailableWeb() -> impl IntoElement {
let heard = signal(String::from("waiting"));
view().child(text(move || heard.get())).child(
web_view("https://example.com/")
.on_unavailable(move |message: &str| heard.set(format!("unavailable: {message}"))),
)
}
/// What [`UnavailableWeb`] shows once the core's events reached it,
/// on a platform that does (`platform`) or does not show web views.
fn unavailable_web_with(platform: bool) -> Vec<String> {
let mut c = core();
c.set_environment(crate::element::Environment {
web_views: platform,
..Default::default()
});
c.mount_root(&crate::element::Root::new::<UnavailableWeb>(|| ()));
let mut shown = texts(&c.commit().unwrap());
let mut events = Vec::new();
c.take_events(&mut events);
for event in events {
if let crate::element::JsEvent::Event(id, kind, payload) = event {
c.component_event(id, kind, &payload);
}
}
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
}
shown
}
#[test]
fn a_web_view_where_the_platform_shows_none_fails_at_once() {
let shown = unavailable_web_with(false);
assert!(
shown.last().unwrap().starts_with("unavailable: "),
"{shown:?}"
);
assert_eq!(unavailable_web_with(true), ["waiting"]);
}
/// A web view that says when its page's process ended.
#[component]
fn TerminatedWeb() -> impl IntoElement {
let heard = signal(String::from("waiting"));
view().child(text(move || heard.get())).child(
web_view("https://example.com/")
.on_unavailable(move |_: &str| heard.set("unavailable".into()))
.on_process_terminated(move |message: &str| {
heard.set(format!("terminated: {message}"))
}),
)
}
/// What [`TerminatedWeb`] shows after the platform reports `error`.
fn terminated_web_after(error: EventPayload) -> String {
let mut c = core();
c.mount_root(&crate::element::Root::new::<TerminatedWeb>(|| ()));
let batch = c.commit().unwrap();
let web = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Create { id, kind, .. } if *kind == ViewKind::WebView => Some(*id),
_ => None,
})
.unwrap();
c.component_event(web, EventKind::Error, &error);
texts(&c.commit().unwrap()).last().unwrap().clone()
}
#[test]
fn a_web_view_hears_when_its_page_process_ended() {
let error = |code: Option<&str>| {
let mut fields = vec![("message", PayloadValue::Str("gone".into()))];
if let Some(code) = code {
fields.push(("code", PayloadValue::Str(code.into())));
}
EventPayload::Map(fields)
};
assert_eq!(
terminated_web_after(error(Some(crate::element::codes::WEBVIEW_TERMINATED))),
"terminated: gone"
);
assert_eq!(
terminated_web_after(error(Some(crate::element::codes::UNAVAILABLE))),
"unavailable"
);
}
/// Shows whether the platform draws shader views, and picks a branch
/// by it as an app picks a shader or its own drawing.
#[component]
fn ShaderCheck() -> impl IntoElement {
view()
.child(text(move || format!("shaders {}", shaders_available())))
.child(when(shaders_available, || text("shader")).otherwise(|| text("canvas")))
}
#[test]
fn shaders_available_follows_what_the_platform_reports() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<ShaderCheck>(|| ()));
// The default environment, as headless runs have it.
assert_eq!(texts(&c.commit().unwrap()), ["shaders true", "shader"]);
// The platform found no GPU: what read it shows the change.
c.set_environment(crate::element::Environment {
shaders: false,
..Default::default()
});
assert_eq!(texts(&c.commit().unwrap()), ["shaders false", "canvas"]);
}
/// Picks Markdown files, then trashes the first one picked and opens a
/// relative path, when pressed; shows what each answered.
#[component]
fn PathActions() -> impl IntoElement {
let shown = signal(String::new());
view()
.child(text(move || format!("paths {}", shown.get())))
.child(view().h(px(10.0)).on_press(move |_: &()| {
let picked = pick_paths(
crate::file_dialog::OpenDialog::files()
.multiple(true)
.filter(crate::file_dialog::FileFilter::new(
"Markdown",
[".MD", "markdown"],
)),
);
spawn(async move {
let picked = picked.await;
let paths = picked.as_ref().ok().cloned().flatten().unwrap_or_default();
let trashed = match paths.first() {
Some(first) => Some(move_to_trash(first.clone()).await),
None => None,
};
let opened = open_path("notes.md").await;
shown.set(format!("{picked:?} {trashed:?} {opened:?}"));
});
}))
}
fn press_path_actions(c: &mut Core<FakeEngine>) -> Vec<MountItem> {
c.mount_root(&crate::element::Root::new::<PathActions>(|| ()));
let batch = c.commit().unwrap();
let button = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the button");
assert!(c.component_event(button, EventKind::Press, &EventPayload::None));
c.commit().map(|b| b.items).unwrap_or_default()
}
fn file_requests(items: Vec<MountItem>) -> Vec<(u32, crate::file_dialog::FileRequest)> {
items
.into_iter()
.filter_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command: Command::FileRequest { id, request },
} => Some((id, *request)),
_ => None,
})
.collect()
}
#[test]
fn the_platform_answers_file_requests() {
use crate::file_dialog::{FileFilter, FileRequest, OpenDialog};
let mut c = core();
c.set_environment(crate::element::Environment {
file_requests: true,
..Default::default()
});
let requests = file_requests(press_path_actions(&mut c));
// The dialog gets the extensions as it takes them.
let expected = OpenDialog::files()
.multiple(true)
.filter(FileFilter::new("Markdown", ["md", "markdown"]));
assert_eq!(requests.len(), 1);
let (pick, request) = requests.into_iter().next().unwrap();
assert_eq!(request, FileRequest::OpenDialog(expected));
let picked = vec![note_path("a.md"), note_path("b.md")];
assert!(c.component_event(
ROOT_ID,
EventKind::FileRequest,
&EventPayload::file_answer(pick, picked.clone())
));
// The task goes on to the trash.
let mut trash = None;
let end = std::time::Instant::now() + std::time::Duration::from_secs(5);
while trash.is_none() && std::time::Instant::now() < end {
c.run_component_tasks();
let items = c.commit().map(|b| b.items).unwrap_or_default();
trash = file_requests(items).into_iter().next();
}
let (trash, request) = trash.expect("the trash request");
assert_eq!(request, FileRequest::MoveToTrash(note_path("a.md")));
assert!(c.component_event(
ROOT_ID,
EventKind::FileRequest,
&EventPayload::file_failed(trash, "no trash on this volume")
));
// A relative path never reaches the platform.
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("paths O")));
assert_eq!(
shown.last().unwrap(),
&format!(
r#"paths Ok(Some({picked:?})) Some(Err("no trash on this volume")) Err("`notes.md` is not an absolute path")"#
)
);
}
/// A picked note's path, absolute where the tests run: the platform
/// refuses a rooted path without a drive on Windows.
fn note_path(name: &str) -> std::path::PathBuf {
let notes = if cfg!(windows) { r"C:\notes" } else { "/notes" };
std::path::Path::new(notes).join(name)
}
#[test]
fn a_cancelled_dialog_is_no_error() {
let mut c = core();
c.set_environment(crate::element::Environment {
file_requests: true,
..Default::default()
});
let (pick, _) = file_requests(press_path_actions(&mut c))
.into_iter()
.next()
.expect("the dialog");
assert!(c.component_event(
ROOT_ID,
EventKind::FileRequest,
&EventPayload::file_answer(pick, Vec::new())
));
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("paths O")));
assert_eq!(
shown.last().unwrap(),
r#"paths Ok(None) None Err("`notes.md` is not an absolute path")"#
);
}
#[test]
fn file_requests_fail_at_once_without_file_dialogs() {
let mut c = core();
let items = press_path_actions(&mut c);
assert!(
file_requests(items).is_empty(),
"nothing reaches the platform"
);
let shown = run_until(&mut c, |s| s.iter().any(|t| t.starts_with("paths E")));
assert_eq!(
shown.last().unwrap(),
r#"paths Err("this platform has no file dialogs, file manager or trash") None Err("this platform has no file dialogs, file manager or trash")"#
);
}
/// Shows a fallback while a component below it failed; a press tries
/// again.
#[component]
fn Boundary(props: WithChildren) -> impl IntoElement {
let retry = stored(None::<crate::element::Reset>);
view()
.on_press(move |_: &()| {
if let Some(reset) = retry.replace(None) {
reset.reset();
}
})
.child(catch_error(
move || props.children,
move |e, reset| {
retry.replace(Some(reset));
text(format!("oops: {} ({})", e.component, e.message))
},
))
}
/// Panics when pressed, and in a binding once `explode` is set.
#[derive(Clone, Copy, PartialEq, Props)]
struct FaultyProps {
#[prop(default)]
explode: crate::element::Prop<bool>,
}
#[component]
fn Faulty(props: FaultyProps) -> impl IntoElement {
view()
.on_press(|_: &()| panic!("pressed"))
.child(text(move || {
assert!(!props.explode.get(), "exploded");
"fine"
}))
}
#[test]
fn errors_of_components_go_to_the_nearest_boundary() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Boundary>().register::<Faulty>();
c.set_components(registry);
let host = |id, name: &str| {
vec![
Op::Create { id, tag: Tag::View },
Op::SetProp {
id,
prop: Prop::Component(name.into()),
},
]
};
let mut ops = host(2, std::any::type_name::<Boundary>());
ops.push(Op::Create {
id: 4,
tag: Tag::View,
});
ops.extend(host(6, std::any::type_name::<Faulty>()));
for (parent, child) in [(4, 6), (2, 4), (ROOT_ID, 2)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
apply(&mut c, ops);
assert_eq!(texts(&c.commit().unwrap()), ["fine"]);
// A listener panics: the boundary shows its fallback.
assert!(c.component_event(6, EventKind::Press, &EventPayload::None));
assert_eq!(
texts(&c.commit().unwrap()),
[format!(
"oops: {} (pressed)",
std::any::type_name::<Faulty>()
)]
);
// Again: the content is back.
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
c.commit();
// A binding panics: the same.
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: rust_prop::<FaultyProps>("explode", Some(serde_json::json!(true))),
}],
);
assert_eq!(
texts(&c.commit().unwrap()),
[format!(
"oops: {} (exploded)",
std::any::type_name::<Faulty>()
)]
);
}
/// A sentence with a link, a bold span and a badge inside it.
#[component]
fn Sentence() -> impl IntoElement {
let taps = signal(0);
let long = signal(false);
view().child(
text(move || format!("Tapped {} ", taps.get()))
.text_size(px(16.0))
.child(text("the link").underline().on_press(move |_: &()| {
taps.update(|t| *t += 1);
long.set(true);
}))
.child(", ")
.child(text("bold").font_weight(FontWeight::BOLD))
.child(when(long, || " and more"))
.child(view().size(px(10.0)).bg(rgb(0xff0000))),
)
}
#[test]
fn rust_texts_nest_spans_links_and_inline_views() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Sentence>(|| ()));
let batch = c.commit().unwrap();
let text = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::Text { text, .. } => Some(text.clone()),
_ => None,
})
};
let t = text(&batch).expect("one paragraph");
assert_eq!(t.text, "Tapped 0 the link, bold\u{fffc}");
assert_eq!(t.attachments.len(), 1, "the view sits in the text");
assert!(t.spans.iter().any(|s| s.style.font_weight == 700));
let link = t.links[0];
assert_eq!((link.start, link.end), (9, 17));
// Only the block and the inline view have native views.
let views = batch
.items
.iter()
.filter(|i| matches!(i, MountItem::Create { .. }))
.count();
assert_eq!(views, 3, "the root's host, the text and the view");
// The link takes the press; the content changes in place.
assert!(c.component_event(link.node, EventKind::Press, &EventPayload::None));
let t = text(&c.commit().unwrap()).expect("built again");
// A piece added between a span and the view goes in its place.
assert_eq!(t.text, "Tapped 1 the link, bold and more\u{fffc}");
}
/// A sentence with a link going somewhere (as `TextView` gives its
/// links their URL), a link that is only pressed, and a span with an
/// `href` that takes no presses. Each press on the second link moves
/// the first one's `href` on: another URL, then none.
#[component]
fn LinksGoingSomewhere() -> impl IntoElement {
let presses = signal(0);
let href = move || match presses.get() {
0 => Some(SharedString::from("https://example.com/a")),
1 => Some(SharedString::from("https://example.com/b")),
_ => None,
};
view().child(
text("Read ")
.child(text("the docs").on_press(|_: &()| {}).__link_href(href))
.child(" or ")
.child(
text("this")
.on_press(move |_: &()| presses.update(|p| *p += 1))
.__link_href(|| None::<SharedString>),
)
.child(" and ")
.child(text("that").__link_href(|| Some(SharedString::from("/that")))),
)
}
#[test]
fn a_links_href_is_in_its_blocks_text_as_metadata() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<LinksGoingSomewhere>(|| ()));
let text = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::Text { text, .. } => Some(text.clone()),
_ => None,
})
};
let t = text(&c.commit().unwrap()).expect("one paragraph");
assert_eq!(t.text, "Read the docs or this and that");
// Two links: "the docs" goes somewhere, "this" nowhere; "that"
// takes no presses, so it is no link and its `href` is not kept.
assert_eq!(
t.links.iter().map(|l| (l.start, l.end)).collect::<Vec<_>>(),
[(5, 13), (17, 21)]
);
assert_eq!(
t.link_hrefs,
[crate::LinkHref::new(0, "https://example.com/a")]
);
assert_eq!(t.link_href(0), Some("https://example.com/a"));
assert_eq!(t.link_href(1), None);
// A new `href` is metadata: the text is mounted again with it, its
// typesetting and layout kept.
let this = t.links[1].node;
let prepares = c.text_engine.prepares.get();
let layouts = c.text_engine.layouts.get();
assert!(c.component_event(this, EventKind::Press, &EventPayload::None));
let t = text(&c.commit().unwrap()).expect("mounted again");
assert_eq!(
t.link_hrefs,
[crate::LinkHref::new(0, "https://example.com/b")]
);
assert_eq!(c.text_engine.prepares.get(), prepares);
assert_eq!(c.text_engine.layouts.get(), layouts);
// None: the link stays a link, going nowhere.
assert!(c.component_event(this, EventKind::Press, &EventPayload::None));
let t = text(&c.commit().unwrap()).expect("mounted again");
assert_eq!(t.links.len(), 2);
assert_eq!(t.link_hrefs, []);
assert_eq!(c.text_engine.layouts.get(), layouts);
}
/// A sentence whose link has a hint (as `nsh-base` gives a link its
/// URL): an overlay inside the span.
#[component]
fn HintedLink() -> impl IntoElement {
view().child(
text("Read ")
.child(
text("the docs").on_press(|_: &()| {}).child(
crate::element::overlay()
.hint(std::time::Duration::from_millis(500))
.pointer_events(crate::props::PointerEvents::None)
.child(text("https://example.com/docs")),
),
)
.child(" today"),
)
}
#[test]
fn a_link_of_a_text_is_its_hints_anchor_where_the_pointer_came() {
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
c.mount_root(&crate::element::Root::new::<HintedLink>(|| ()));
let mut paragraph = None;
for _ in 0..2 {
if let Some(batch) = c.commit() {
for item in &batch.items {
if let MountItem::Text { text, .. } = item
&& text.text.starts_with("Read")
{
paragraph = Some(text.clone());
}
}
}
}
let t = paragraph.expect("the paragraph");
assert_eq!(t.text, "Read the docs today", "the hint is no text of it");
let link = t.links[0];
// The platforms tell the link when the pointer comes over its
// characters and leaves them.
assert!(link.events.contains(EventKind::MouseEnter));
assert!(link.events.contains(EventKind::MouseLeave));
let at = crate::geometry::point(px(60.0), px(8.0));
let mouse = EventPayload::Mouse(crate::MouseEvent::new(
crate::geometry::point(px(20.0), px(8.0)),
at,
crate::keymap::Modifiers::default(),
None,
));
c.component_event(link.node, EventKind::MouseEnter, &mouse);
c.run_component_tasks();
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(500));
c.run_component_tasks();
let batch = c.commit().expect("the hint shows");
assert!(
texts(&batch)
.iter()
.any(|t| t == "https://example.com/docs"),
"{:?}",
texts(&batch)
);
// Below where the pointer came (the default placement), not
// against the whole paragraph.
let overlay = inserts(&batch)
.into_iter()
.find(|&(p, ..)| p == ROOT_ID)
.map(|(_, child, _)| child)
.expect("the hint in the root view");
let frame = frame_of(&batch, overlay).expect("placed");
assert!(frame.origin.y >= px(8.0), "{frame:?}");
// Leaving the link hides it.
c.component_event(link.node, EventKind::MouseLeave, &mouse);
let batch = c.commit().expect("the hint hides");
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == overlay))
);
}
/// A link of a text that takes no presses (as a `RichEditor`'s link
/// mark: the editor's touches place the caret), in a scroll view, with
/// a hint; beside a span taking presses with one inside it.
#[component]
fn HoverOnlyLink() -> impl IntoElement {
let hint = |url: &'static str| {
crate::element::overlay()
.hint(std::time::Duration::from_millis(500))
.pointer_events(crate::props::PointerEvents::None)
.child(text(url))
};
scroll().h(px(100.0)).child(
view().h(px(1000.0)).child(
text("Read ")
.child(text("the docs").child(hint("https://example.com/docs")))
.child(" or ")
.child(
text("pressed ")
.on_press(|_: &()| {})
.child(text("inner").child(hint("https://example.com/inner"))),
),
),
)
}
#[test]
fn a_link_taking_no_presses_hears_the_pointer_for_its_hint_only() {
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
c.mount_root(&crate::element::Root::new::<HoverOnlyLink>(|| ()));
let mut paragraph = None;
let mut scroller = None;
// The hint's watch comes after the first merge: the span is a
// link of its text from the next.
for _ in 0..3 {
if let Some(batch) = c.commit() {
for item in &batch.items {
match item {
MountItem::Text { text, .. } if text.text.starts_with("Read") => {
paragraph = Some(text.clone());
}
MountItem::Create { id, kind } if *kind == ViewKind::Scroll => {
scroller = Some(*id);
}
_ => {}
}
}
}
}
let t = paragraph.expect("the paragraph");
let scroller = scroller.expect("the scroll view");
assert_eq!(t.text, "Read the docs or pressed inner");
let docs = *t
.links
.iter()
.find(|l| (l.start, l.end) == (5, 13))
.expect("the hinted span is a link of its text");
// The pointer only: no press, no stop of Tab.
assert!(docs.events.contains(EventKind::MouseEnter));
assert!(docs.events.contains(EventKind::MouseLeave));
assert!(!docs.events.contains(EventKind::Press));
assert!(!docs.focus_stop);
// Inside a span taking presses, a hinted span is no link: the
// pressable one stays the innermost link of those characters.
let inner = t.link_at(26).expect("a link there");
assert!(inner.events.contains(EventKind::Press), "{inner:?}");
assert_eq!((inner.start, inner.end), (17, 30));
let at = crate::geometry::point(px(60.0), px(8.0));
let mouse = EventPayload::Mouse(crate::MouseEvent::new(
crate::geometry::point(px(20.0), px(8.0)),
at,
crate::keymap::Modifiers::default(),
None,
));
c.component_event(docs.node, EventKind::MouseEnter, &mouse);
c.run_component_tasks();
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(500));
c.run_component_tasks();
let batch = c.commit().expect("the hint shows");
assert!(
texts(&batch)
.iter()
.any(|t| t == "https://example.com/docs"),
"{:?}",
texts(&batch)
);
let overlay = inserts(&batch)
.into_iter()
.find(|&(p, ..)| p == ROOT_ID)
.map(|(_, child, _)| child)
.expect("the hint in the root view");
// Placed where the pointer came, against the span, not the block.
let frame = frame_of(&batch, overlay).expect("placed");
assert!(frame.origin.y >= px(8.0), "{frame:?}");
// The content scrolls under a still pointer: the link moved away
// from where the hint points, so it hides.
c.set_scroll_offset(
scroller,
crate::geometry::point(px(0.0), px(40.0)),
u32::MAX,
);
let batch = c.commit().expect("the hint hides");
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == overlay)),
"{:?}",
batch.items
);
// The pointer coming over the link again shows it there.
c.component_event(docs.node, EventKind::MouseEnter, &mouse);
c.run_component_tasks();
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(500));
c.run_component_tasks();
let batch = c.commit().expect("shown again");
assert!(
texts(&batch)
.iter()
.any(|t| t == "https://example.com/docs")
|| inserts(&batch)
.iter()
.any(|&(p, child, _)| p == ROOT_ID && child == overlay),
"{:?}",
batch.items
);
}
/// A sentence whose spans style their hover and press, a link and a
/// span that takes no presses, and one inside the link.
#[component]
fn StatefulSpans() -> impl IntoElement {
view().child(
text("Read ")
.child(
text("the docs")
.on_press(|_: &()| {})
.hover(|s| s.underline())
.active(|s| s.text_color(rgb(0xff0000))),
)
.child(" or ")
.child(text("this").hover(|s| s.underline()))
.child(" and ")
.child(
text("pressed ")
.on_press(|_: &()| {})
.child(text("inner").hover(|s| s.underline())),
),
)
}
#[test]
fn a_span_takes_its_hover_and_press_styles_where_the_pointer_is() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
c.mount_root(&crate::element::Root::new::<StatefulSpans>(|| ()));
let paragraph = |c: &mut Core<_>| {
let batch = c.commit()?;
batch.items.iter().find_map(|i| match i {
MountItem::Text { text, .. } => Some(text.clone()),
_ => None,
})
};
let style_at = |t: &crate::AttributedText, at: u32| {
t.spans
.iter()
.find(|s| s.start <= at && at < s.end)
.expect("a run there")
.style
};
let t = paragraph(&mut c).expect("the paragraph");
assert_eq!(t.text, "Read the docs or this and pressed inner");
let docs = *t.link_at(5).expect("the link");
let this = *t
.link_at(17)
.expect("a span with hover styles hears the pointer");
// The platforms tell a span when the pointer comes over its
// characters and leaves them, and when a press goes in and out.
for link in [docs, this] {
assert!(link.events.contains(EventKind::MouseEnter), "{link:?}");
assert!(link.events.contains(EventKind::MouseLeave), "{link:?}");
}
assert!(docs.events.contains(EventKind::PressDown));
assert!(docs.events.contains(EventKind::PressUp));
// A span that only hovers takes no press and no stop of Tab.
assert!(!this.events.contains(EventKind::Press));
assert!(!this.events.contains(EventKind::PressDown));
assert!(!this.focus_stop);
// Inside a span taking presses, the pressable one stays the link.
let inner = t.link_at(34).expect("a link there");
assert_eq!((inner.start, inner.end), (26, 39));
assert!(!style_at(&t, 5).decoration.underline);
let color = style_at(&t, 5).color;
let mouse = EventPayload::Mouse(crate::MouseEvent::new(
crate::geometry::point(px(20.0), px(8.0)),
crate::geometry::point(px(60.0), px(8.0)),
crate::keymap::Modifiers::default(),
None,
));
c.component_event(docs.node, EventKind::MouseEnter, &mouse);
let t = paragraph(&mut c).expect("the span hovered");
assert!(style_at(&t, 5).decoration.underline);
assert!(!style_at(&t, 4).decoration.underline, "only the span's run");
assert!(!style_at(&t, 17).decoration.underline);
let press = EventPayload::Press(crate::PressEvent::default());
c.component_event(docs.node, EventKind::PressDown, &press);
let t = paragraph(&mut c).expect("the span pressed");
assert_ne!(style_at(&t, 5).color, color);
assert!(style_at(&t, 5).decoration.underline);
c.component_event(docs.node, EventKind::PressUp, &press);
let t = paragraph(&mut c).expect("the press ended");
assert_eq!(style_at(&t, 5).color, color);
c.component_event(docs.node, EventKind::MouseLeave, &mouse);
c.component_event(this.node, EventKind::MouseEnter, &mouse);
let t = paragraph(&mut c).expect("the pointer moved on");
assert!(!style_at(&t, 5).decoration.underline);
assert!(style_at(&t, 17).decoration.underline);
c.component_event(this.node, EventKind::MouseLeave, &mouse);
let t = paragraph(&mut c).expect("the pointer left");
assert!(!style_at(&t, 17).decoration.underline);
}
}
/// Rust components' touches and responder (`touch.rs`).
mod touch {
use super::*;
use crate::{
TouchEvent, TouchPhase, TouchPoint,
element::{ClaimRequest, ResponderEvent, TouchClaim},
prelude::*,
};
#[derive(Clone, PartialEq, Props)]
struct PadProps {
#[prop(default)]
keep: bool,
}
/// An outer view taking horizontal swipes from an inner one that claims
/// touches on start.
#[component]
fn Pad(props: PadProps) -> impl IntoElement {
let log = signal(Vec::<String>::new());
let note = move |what: &'static str, f: fn(&ResponderEvent) -> String| {
move |e: &ResponderEvent| log.update(|l| l.push(format!("{what}{}", f(e))))
};
let none = |_: &ResponderEvent| String::new();
view()
.on_touch(move |t: &TouchEvent| log.update(|l| l.push(format!("touch {:?}", t.phase))))
.claim_touches(TouchClaim::on_move().capture().ask(|r: &ClaimRequest| {
if r.event.gesture.delta.x.abs() > px(50.0) {
r.claim();
}
}))
.on_responder_grant(note("outer grant", none))
.on_responder_reject(note("outer reject", none))
.child(
view()
.size(px(100.0))
.claim_touches(TouchClaim::on_start())
.keep_touches(props.keep)
.on_responder_grant(note("grant at ", |e| {
format!("{},{}", e.location.x.0, e.location.y.0)
}))
.on_responder_move(note("move ", |e| {
format!("{},{}", e.gesture.delta.x.0, e.gesture.delta.y.0)
}))
.on_responder_release(note("release ", |e| format!("{:.2}", e.gesture.vx)))
.on_responder_terminate(note("terminate", none)),
)
.child(text(move || log.with(|l| l.join("|"))))
}
fn touch(phase: TouchPhase, path: &[NodeId], x: f32, t: f64) -> EventPayload {
EventPayload::Touch(Box::new(TouchEvent {
phase,
timestamp: t,
modifiers: Default::default(),
activated: None,
points: vec![TouchPoint {
id: 7,
target: path[0],
path: if phase == TouchPhase::Start {
path.to_vec()
} else {
Vec::new()
},
page: point(px(x), px(100.0)),
location: point(px(x - 10.0), px(5.0)),
changed: true,
pointer_type: crate::PointerType::Touch,
pressure: 0.5,
tilt_x: 0.0,
tilt_y: 0.0,
coalesced: Vec::new(),
eraser: false,
barrel: false,
}],
}))
}
fn log(batch: &MountBatch) -> Option<String> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.clone()),
_ => None,
})
}
fn commands(batch: &MountBatch) -> Vec<(NodeId, Command)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Command { id, command } => Some((*id, command.clone())),
_ => None,
})
.collect()
}
/// The pad mounted: the core, the outer node and the inner one (both
/// listen to touches).
fn mount_pad(keep: bool) -> (Core<FakeEngine>, NodeId, NodeId) {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Pad>(move || PadProps { keep }));
let batch = c.commit().unwrap();
let listening: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Touch) => Some(*id),
_ => None,
})
.collect();
let [outer, inner] = listening[..] else {
panic!("two listening views: {listening:?}");
};
(c, outer, inner)
}
thread_local! {
static SLOT_TOUCH_LOG: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
}
fn note_slot_touch(s: &'static str) {
SLOT_TOUCH_LOG.with(|log| log.borrow_mut().push(s));
}
#[derive(Clone, Copy, PartialEq, Props)]
struct TouchSlotProps {
trigger: crate::element::Prop<Option<Slot>>,
}
#[component]
fn TouchSlot(props: TouchSlotProps) -> impl IntoElement {
view().child(props.trigger.place(|t| {
t.on_touch(|_: &TouchEvent| note_slot_touch("slot touch"))
.claim_touches(TouchClaim::on_move().capture())
.on_responder_grant(|_: &ResponderEvent| note_slot_touch("slot grant"))
}))
}
#[component]
fn TouchTrigger() -> impl IntoElement {
view()
.on_touch(|_: &TouchEvent| note_slot_touch("trigger touch"))
.claim_touches(TouchClaim::on_start())
.on_responder_grant(|_: &ResponderEvent| note_slot_touch("trigger grant"))
.on_responder_terminate(|_: &ResponderEvent| note_slot_touch("trigger terminate"))
}
#[test]
fn a_slotted_component_and_its_slot_both_receive_touches_and_negotiate() {
SLOT_TOUCH_LOG.with(|log| log.borrow_mut().clear());
let mut c = core();
let mut registry = Registry::new();
registry.register::<TouchSlot>();
registry.register::<TouchTrigger>();
c.set_components(registry);
let component = |id, name: &str| Op::SetProp {
id,
prop: super::Prop::Component(name.into()),
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
component(2, std::any::type_name::<TouchSlot>()),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: super::Prop::ComponentSlot("trigger".into()),
},
Op::Create {
id: 6,
tag: Tag::View,
},
component(6, std::any::type_name::<TouchTrigger>()),
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
c.commit();
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Start, &[6], 0.0, 0.0),
);
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Move, &[6], 20.0, 16.0),
);
SLOT_TOUCH_LOG.with(|log| {
assert_eq!(
&*log.borrow(),
&[
"trigger touch",
"slot touch",
"trigger grant",
"trigger touch",
"slot touch",
"trigger terminate",
"slot grant",
]
)
});
}
#[test]
fn an_element_claims_the_touches_on_start_and_blocks_scrolling() {
let (mut c, outer, inner) = mount_pad(false);
let path = [inner, outer];
// The root's touches: the components hear theirs, JS still gets
// the event for its own nodes.
assert!(!c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Start, &path, 20.0, 0.0)
));
let batch = c.commit().unwrap();
assert_eq!(log(&batch).unwrap(), "touch Start|grant at 10,5");
assert_eq!(
commands(&batch),
[(inner, Command::SetJsResponder { block: true })]
);
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Move, &path, 40.0, 16.0),
);
let batch = c.commit().unwrap();
assert_eq!(
log(&batch).unwrap(),
"touch Start|grant at 10,5|touch Move|move 20,0"
);
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::End, &path, 40.0, 32.0),
);
let batch = c.commit().unwrap();
assert!(log(&batch).unwrap().ends_with("|touch End|release 875.00"));
assert_eq!(commands(&batch), [(ROOT_ID, Command::ClearJsResponder)]);
}
#[test]
fn a_capturing_claim_takes_the_touches_over_unless_they_are_kept() {
let (mut c, outer, inner) = mount_pad(false);
let path = [inner, outer];
let send = |c: &mut Core<FakeEngine>, phase, x, t| {
c.component_event(ROOT_ID, EventKind::Touch, &touch(phase, &path, x, t));
};
send(&mut c, TouchPhase::Start, 0.0, 0.0);
send(&mut c, TouchPhase::Move, 30.0, 16.0);
// Far enough sideways: the outer view asks and claims.
send(&mut c, TouchPhase::Move, 80.0, 32.0);
let batch = c.commit().unwrap();
let text = log(&batch).unwrap();
assert!(
text.ends_with("move 30,0|touch Move|terminate|outer grant"),
"{text}"
);
assert_eq!(
commands(&batch).last(),
Some(&(outer, Command::SetJsResponder { block: true }))
);
// An inner responder that keeps the touches rejects the claim.
let (mut c, outer, inner) = mount_pad(true);
let path = [inner, outer];
let send = |c: &mut Core<FakeEngine>, phase, x, t| {
c.component_event(ROOT_ID, EventKind::Touch, &touch(phase, &path, x, t));
};
send(&mut c, TouchPhase::Start, 0.0, 0.0);
send(&mut c, TouchPhase::Move, 80.0, 16.0);
let text = log(&c.commit().unwrap()).unwrap();
assert!(text.ends_with("|outer reject|move 80,0"), "{text}");
// A cancel (a native gesture took over) terminates it.
send(&mut c, TouchPhase::Cancel, 80.0, 32.0);
let batch = c.commit().unwrap();
assert!(log(&batch).unwrap().ends_with("|terminate"));
assert_eq!(commands(&batch), [(ROOT_ID, Command::ClearJsResponder)]);
}
#[test]
fn js_and_component_responders_share_the_native_block() {
let (mut c, outer, inner) = mount_pad(false);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Command {
id: 2,
command: Command::SetJsResponder { block: true },
},
],
);
assert_eq!(
commands(&c.commit().unwrap()),
[(2, Command::SetJsResponder { block: true })]
);
// A component's responder blocks around itself while it has the
// touches; when it lets go, JS's block is back.
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Start, &[inner, outer], 0.0, 0.0),
);
assert_eq!(
commands(&c.commit().unwrap()),
[(inner, Command::SetJsResponder { block: true })]
);
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::End, &[inner, outer], 0.0, 16.0),
);
assert_eq!(
commands(&c.commit().unwrap()),
[(2, Command::SetJsResponder { block: true })]
);
apply(
&mut c,
vec![Op::Command {
id: ROOT_ID,
command: Command::ClearJsResponder,
}],
);
assert_eq!(
commands(&c.commit().unwrap()),
[(ROOT_ID, Command::ClearJsResponder)]
);
}
/// A view scrubbed sideways: it waits for the platform's pan (its
/// start claim is not asked meanwhile).
#[component]
fn Scrub() -> impl IntoElement {
let log = signal(Vec::<String>::new());
view()
.child(
view()
.size(px(100.0))
.claim_touches(TouchClaim::on_start())
.claim_touches(TouchClaim::on_pan(crate::PanActivation::horizontal(
px(10.0),
px(10.0),
)))
.on_responder_grant(move |_: &ResponderEvent| {
log.update(|l| l.push("grant".into()));
}),
)
.child(text(move || log.with(|l| l.join("|"))))
}
#[test]
fn a_pan_claim_waits_for_the_platform_to_activate_it() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Scrub>(|| ()));
let batch = c.commit().unwrap();
let (id, activation) = batch
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } => props.pan_activation.map(|a| (*id, a)),
_ => None,
})
.expect("the activation is mounted");
assert_eq!(
activation,
crate::PanActivation::horizontal(px(10.0), px(10.0))
);
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Start, &[id], 0.0, 0.0),
);
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Move, &[id], 5.0, 16.0),
);
// Nothing to mount: no claim before the activation.
assert!(c.commit().is_none_or(|b| commands(&b).is_empty()));
let mut activated = touch(TouchPhase::Move, &[id], 14.0, 32.0);
if let EventPayload::Touch(t) = &mut activated {
t.activated = Some(id);
}
c.component_event(ROOT_ID, EventKind::Touch, &activated);
let batch = c.commit().unwrap();
assert_eq!(log(&batch), Some("grant".into()), "{batch:?}");
assert_eq!(
commands(&batch),
[(id, Command::SetJsResponder { block: true })]
);
}
/// A band dragged by its touches, dimmed while pressed.
#[component]
fn Band() -> impl IntoElement {
view()
.size(px(40.0))
.opacity(0.9)
.active(|s| s.opacity(0.5))
.claim_touches(TouchClaim::on_start())
}
#[test]
fn the_responder_stays_pressed_until_its_touches_end() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Band>(|| ()));
let batch = c.commit().unwrap();
let id = batch
.items
.iter()
.find_map(|i| match i {
MountItem::ViewStyle { id, style } if style.opacity == 0.9 => Some(*id),
_ => None,
})
.expect("the band is mounted");
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::Start, &[id], 0.0, 0.0),
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, id).unwrap().opacity, 0.5);
// The drag left the band: the platform reports it no longer pressed.
c.set_states(id, 0);
assert!(c.commit().is_none_or(|b| view_style_of(&b, id).is_none()));
c.component_event(
ROOT_ID,
EventKind::Touch,
&touch(TouchPhase::End, &[id], 80.0, 16.0),
);
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, id).unwrap().opacity, 0.9);
}
#[test]
fn a_pan_activation_decides_by_axis() {
let pan = crate::PanActivation::horizontal(px(10.0), px(8.0));
assert_eq!(pan.decide(px(4.0), px(3.0)), None);
assert_eq!(pan.decide(px(-11.0), px(3.0)), Some(true));
assert_eq!(pan.decide(px(4.0), px(-9.0)), Some(false));
// Both passed by one move: the fail offset wins.
assert_eq!(pan.decide(px(20.0), px(9.0)), Some(false));
let any = crate::PanActivation::default();
assert_eq!(any.decide(px(6.0), px(6.0)), None);
assert_eq!(any.decide(px(8.0), px(8.0)), Some(true));
}
#[test]
fn a_pan_activation_with_a_direction_takes_only_that_way() {
use crate::{PanActivation, PanDirection};
let right = PanActivation::default().direction(PanDirection::Right);
assert_eq!(right.decide(px(6.0), px(2.0)), None);
assert_eq!(right.decide(px(11.0), px(4.0)), Some(true));
// The other way, or mostly across, fails: the views around keep it.
assert_eq!(right.decide(px(-11.0), px(0.0)), Some(false));
assert_eq!(right.decide(px(3.0), px(12.0)), Some(false));
assert_eq!(right.decide(px(3.0), px(-12.0)), Some(false));
assert_eq!(right.axis(), Some(true));
// Its axis's active offset; a fail offset across decides across.
let up = PanActivation::vertical(px(20.0), px(30.0)).direction(PanDirection::Up);
assert_eq!(up.decide(px(0.0), px(-15.0)), None);
assert_eq!(up.decide(px(0.0), px(-21.0)), Some(true));
assert_eq!(up.decide(px(0.0), px(21.0)), Some(false));
assert_eq!(up.decide(px(25.0), px(-5.0)), None);
assert_eq!(up.decide(px(31.0), px(-5.0)), Some(false));
assert_eq!(up.axis(), Some(false));
// Judged along the line: a move that swings back still fails.
assert_eq!(
right.decide_move(point(px(0.0), px(0.0)), point(px(-12.0), px(0.0))),
Some(false)
);
}
#[test]
fn an_edge_pan_starts_at_its_edge_and_moves_away_from_it() {
use crate::{PanActivation, PanDirection, PanEdge};
let screen = crate::geometry::size(px(390.0), px(844.0));
let at = |x: f32, y: f32| point(px(x), px(y));
let left = PanActivation::default().edge(PanEdge::Left);
assert!(left.starts_at(at(0.0, 400.0), screen));
assert!(left.starts_at(at(20.0, 400.0), screen));
assert!(!left.starts_at(at(21.0, 400.0), screen));
assert_eq!(left.way(), Some(PanDirection::Right));
assert_eq!(left.decide(px(12.0), px(1.0)), Some(true));
assert_eq!(left.decide(px(-12.0), px(1.0)), Some(false));
// The edge decides the way, whatever `direction` says.
let both = left.direction(PanDirection::Left);
assert_eq!(both.decide(px(12.0), px(1.0)), Some(true));
let right = PanActivation::default().edge(PanEdge::Right);
assert!(right.starts_at(at(380.0, 10.0), screen));
assert!(!right.starts_at(at(360.0, 10.0), screen));
let bottom = PanActivation::default().edge(PanEdge::Bottom);
assert!(bottom.starts_at(at(200.0, 830.0), screen));
assert!(!bottom.starts_at(at(200.0, 800.0), screen));
assert_eq!(bottom.decide(px(0.0), px(-11.0)), Some(true));
let top = PanActivation::default().edge(PanEdge::Top);
assert!(top.starts_at(at(200.0, 5.0), screen) && !top.starts_at(at(200.0, 40.0), screen));
// Without an edge, anywhere.
assert!(PanActivation::default().starts_at(at(200.0, 400.0), screen));
}
#[test]
fn a_pan_activation_judges_a_move_along_its_line() {
use crate::geometry::point;
let pan = crate::PanActivation::horizontal(px(10.0), px(10.0));
let start = point(px(0.0), px(0.0));
// One move past both offsets: the one passed first decides.
assert_eq!(
pan.decide_move(start, point(px(-16.6), px(-11.1))),
Some(true)
);
assert_eq!(
pan.decide_move(start, point(px(-11.1), px(16.6))),
Some(false)
);
// Small moves decide as `decide` does.
assert_eq!(pan.decide_move(start, point(px(8.0), px(0.0))), None);
assert_eq!(
pan.decide_move(point(px(8.0), px(0.0)), point(px(10.5), px(1.0))),
Some(true)
);
assert_eq!(
pan.decide_move(point(px(0.0), px(9.0)), point(px(2.0), px(10.5))),
Some(false)
);
// A finger that came back is still undecided.
assert_eq!(pan.decide_move(point(px(8.0), px(0.0)), start), None);
}
/// A card scaled and turned by two-finger gestures.
#[component]
fn Card() -> impl IntoElement {
let (scale, angle) = (animated_value(1.0), animated_value(0.0));
view()
.pinch_value(&scale)
.rotation_value(&angle)
.bind_scale(&scale)
.bind_rotate(&angle)
}
#[test]
fn pinches_and_rotations_drive_animated_values() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Card>(|| ()));
let batch = c.commit().unwrap();
let values = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Gestures { values, .. } => Some(*values),
_ => None,
})
.expect("gesture values");
let created: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Animation(AnimationOp::CreateValue { node, .. }) => Some(*node),
_ => None,
})
.collect();
assert_eq!(values.pinch, Some(created[0]));
assert_eq!(values.rotation, Some(created[1]));
}
}
/// Rust components' drawings (`ui::Painter`).
mod painter {
use super::*;
use crate::{
canvas::{CanvasGradient, CanvasOp, FillRule, GradientShape, Num, Paint, svg_path},
geometry::{bounds, percentage, point, px, radians, size},
prelude::*,
};
#[test]
fn painters_hit_test_what_they_drew() {
// A slice drawn moved by 10, a line along the top, a rectangle as
// the current path.
let slice = svg_path("M0 0 L40 0 L0 40 Z");
let p = Painter::new()
.save()
.translate(10.0, 10.0)
.fill_path(&slice, FillRule::NonZero)
.restore()
.line_width(4.0)
.stroke_svg("M0 2 L100 2")
.begin_path()
.rect(bounds(point(px(60.0), px(60.0)), size(px(20.0), px(20.0))));
let at = |x, y| point(px(x), px(y));
// Paths given are tested with the transform at the end: drawn
// translated, the slice is hit where it shows only with the same
// transform recorded.
assert!(p.path_contains(&slice, at(5.0, 5.0), FillRule::NonZero));
assert!(!p.path_contains(&slice, at(45.0, 45.0), FillRule::NonZero));
let moved = Painter::new().translate(10.0, 10.0);
assert!(moved.path_contains(&slice, at(15.0, 15.0), FillRule::NonZero));
assert!(!moved.path_contains(&slice, at(5.0, 5.0), FillRule::NonZero));
// The current path, and strokes with the line width.
assert!(p.is_point_in_path(at(70.0, 70.0), FillRule::EvenOdd));
assert!(!p.is_point_in_path(at(50.0, 70.0), FillRule::NonZero));
assert!(p.is_point_in_stroke(at(60.0, 70.0)));
assert!(!p.is_point_in_stroke(at(70.0, 70.0)));
let top = svg_path("M0 2 L100 2");
assert!(p.stroke_contains(&top, at(50.0, 3.5)));
assert!(!p.stroke_contains(&top, at(50.0, 5.0)));
}
/// A drawing painting with its view's style: the stroke, width and
/// dashes of the canvas's own style, the fill `currentColor`, the text
/// color the canvas inherits.
#[component]
fn ViewPainted() -> impl IntoElement {
use crate::{StyleDecl, StyleKey, StyleValue, SvgPaint};
let set = |key: StyleKey, value: &str| {
StyleDecl::Set(key, key.parse_value(StyleValue::Str(value)).unwrap())
};
let p = Painter::new()
.fill_style_from_view(SvgPaint::CurrentColor)
.stroke_style_from_view(SvgPaint::None)
.line_width_from_view()
.line_dash_from_view()
.fill_rect(0.0, 0.0, 10.0, 10.0);
view()
.inline_style(crate::element::Style::from_decls([set(
StyleKey::Color,
"#00ff00",
)]))
.child(canvas(p).inline_style(crate::element::Style::from_decls([
set(StyleKey::Stroke, "#ff0000"),
set(StyleKey::StrokeWidth, "3"),
set(StyleKey::StrokeDasharray, "2 1"),
])))
.child(canvas(
Painter::new()
.fill_style_from_view(SvgPaint::None)
.stroke_style_from_view(SvgPaint::CurrentColor)
.line_width_from_view()
.line_dash_from_view(),
))
}
#[test]
fn drawings_paint_with_their_views_style() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<ViewPainted>(|| ()));
let batch = c.commit().unwrap();
let drawings: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Canvas { drawing, .. } => Some(drawing.clone()),
_ => None,
})
.collect();
let [styled, plain] = &drawings[..] else {
panic!("{drawings:?}")
};
let green = crate::style::Color(0x00ff_00ff);
assert_eq!(styled.ops[0], CanvasOp::FillStyle(Paint::Color(green)));
assert_eq!(
styled.ops[1],
CanvasOp::StrokeStyle(Paint::Color(crate::style::Color(0xff00_00ff)))
);
assert_eq!(styled.ops[2], CanvasOp::LineWidth(Num::Const(3.0)));
assert_eq!(styled.ops[3], CanvasOp::LineDash([px(2.0), px(1.0)].into()));
// Nothing set: the drawing's initial paints, CSS's width of 1 and a
// solid line.
assert_eq!(
plain.ops[0],
CanvasOp::FillStyle(Paint::Color(crate::style::Color::TRANSPARENT))
);
assert_eq!(plain.ops[1], CanvasOp::StrokeStyle(Paint::Color(green)));
assert_eq!(plain.ops[2], CanvasOp::LineWidth(Num::Const(1.0)));
assert_eq!(plain.ops[3], CanvasOp::LineDash([].into()));
}
/// A canvas filling a shape with its view's background: a color and a
/// gradient, which the view does not draw behind it.
#[component]
fn BackgroundFilled() -> impl IntoElement {
use crate::{StyleDecl, StyleKey, StyleValue};
let set = |key: StyleKey, value: &str| {
StyleDecl::Set(key, key.parse_value(StyleValue::Str(value)).unwrap())
};
let area = bounds(point(px(0.0), px(0.0)), size(px(40.0), px(20.0)));
let p = Painter::new()
.begin_path()
.rect(area)
.fill_background_from_view(area);
canvas(p).inline_style(crate::element::Style::from_decls([
set(StyleKey::BackgroundColor, "#00ff00"),
set(
StyleKey::BackgroundImage,
"linear-gradient(to bottom, #ff0000, #0000ff)",
),
]))
}
#[test]
fn drawings_fill_with_their_views_background() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<BackgroundFilled>(|| ()));
let batch = c.commit().unwrap();
let (canvas, drawing) = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Canvas { id, drawing } => Some((*id, drawing.clone())),
_ => None,
})
.unwrap();
// The fill: the color, then the gradient over the area, top to
// bottom.
let fills: Vec<_> = drawing
.ops
.iter()
.filter_map(|op| match op {
CanvasOp::FillStyle(paint) => Some(paint.clone()),
_ => None,
})
.collect();
assert_eq!(fills[0], Paint::Color(crate::style::Color(0x00ff_00ff)));
let Paint::Gradient(g) = &fills[1] else {
panic!("{fills:?}")
};
assert_eq!(
g.shape,
crate::canvas::GradientShape::Linear {
start: point(px(20.0), px(0.0)),
end: point(px(20.0), px(20.0)),
}
);
// The view draws no background of its own.
let style = batch
.items
.iter()
.find_map(|i| match i {
MountItem::ViewStyle { id, style } if *id == canvas => Some(style.clone()),
_ => None,
})
.unwrap();
assert!(style.background_color.is_transparent());
assert!(
style
.effects
.as_deref()
.is_none_or(|e| e.background_images.is_empty())
);
}
/// An icon stroked with `currentColor`, 24 points with a 12 point
/// view box.
#[cfg(feature = "svg")]
const ICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 12 12"><path d="M0 0h12v12H0z" fill="none" stroke="currentColor"/></svg>"##;
/// SVGs in a view of a text color: one at its natural size, one given
/// only a width.
#[cfg(feature = "svg")]
#[component]
fn Icons() -> impl IntoElement {
view()
.items_start()
.text_color(rgb(0x00ff00))
.child(svg(crate::element::ImageSrc::svg_markup(ICON)))
.child(svg(crate::element::ImageSrc::svg_markup(ICON)).w(px(48.0)))
.child(svg(crate::element::ImageSrc::svg_markup(ICON)).w(relative(0.25)))
}
/// An SVG file, read by the shared loader.
#[cfg(feature = "svg")]
#[component]
fn FileIcon() -> impl IntoElement {
let path = std::env::temp_dir().join(format!("nsh-svg-icon-{}.svg", std::process::id()));
view()
.items_start()
.child(svg(path.to_string_lossy().into_owned()))
}
#[cfg(feature = "svg")]
#[test]
fn svg_files_load_off_the_engine_thread_and_lay_out_when_drawn() {
let path = std::env::temp_dir().join(format!("nsh-svg-icon-{}.svg", std::process::id()));
std::fs::write(&path, ICON).unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_time()
.build()
.unwrap();
let mut c = core();
c.set_task_runtime(runtime.handle().clone());
c.mount_root(&crate::element::Root::new::<FileIcon>(|| ()));
let first = c.commit().unwrap();
assert!(
!first
.items
.iter()
.any(|i| matches!(i, MountItem::Canvas { drawing, .. } if !drawing.ops.is_empty())),
"nothing to draw before it loads"
);
let end = std::time::Instant::now() + std::time::Duration::from_secs(5);
let (id, batch) = loop {
assert!(std::time::Instant::now() < end, "never drawn");
c.run_component_tasks();
if let Some(batch) = c.commit()
&& let Some(id) = batch.items.iter().find_map(|i| match i {
MountItem::Canvas { id, drawing } if !drawing.ops.is_empty() => Some(*id),
_ => None,
})
{
break (id, batch);
}
std::thread::sleep(std::time::Duration::from_millis(2));
};
// Drawn, it lays out at its natural size.
assert_eq!(frame_of(&batch, id).unwrap().size, size(px(24.0), px(24.0)));
let _ = std::fs::remove_file(&path);
}
#[cfg(feature = "svg")]
#[test]
fn svgs_lay_out_as_images_and_stroke_with_the_text_color() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Icons>(|| ()));
let batch = c.commit().unwrap();
let drawings: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Canvas { id, drawing } => Some((*id, drawing.clone())),
_ => None,
})
.collect();
// Each sent once, after the layout.
let [(natural, small), (wide, large), (quarter, _)] = &drawings[..] else {
panic!("{drawings:?}")
};
let size_of = |id| frame_of(&batch, id).unwrap().size;
assert_eq!(size_of(*natural), size(px(24.0), px(24.0)));
assert_eq!(size_of(*wide), size(px(48.0), px(48.0)));
// The view box onto the box: 2 and 4 times.
let scale = |d: &crate::canvas::Drawing| match d.ops[0] {
CanvasOp::Transform([Num::Const(a), _, _, Num::Const(d), ..]) => (a, d),
ref op => panic!("{op:?}"),
};
assert_eq!(scale(small), (2.0, 2.0));
assert_eq!(scale(large), (4.0, 4.0));
let green = crate::style::Color(0x00ff_00ff);
assert!(
small
.ops
.contains(&CanvasOp::StrokeStyle(Paint::Color(green)))
);
assert!(small.view_paints.is_empty());
// Given another size by the layout, it is sent again for it.
c.set_viewport(size(px(192.0), px(480.0)));
let batch = c.commit().unwrap();
let resized: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Canvas { id, drawing } => Some((*id, drawing.clone())),
_ => None,
})
.collect();
let [(id, drawing)] = &resized[..] else {
panic!("{resized:?}")
};
assert_eq!(id, quarter);
assert_eq!(scale(drawing), (4.0, 4.0));
}
#[cfg(feature = "svg")]
#[test]
fn svg_renders_inline_image_src_bytes() {
#[component]
fn BlobSvg() -> impl IntoElement {
let first = crate::ImageSource::default()
.with_bytes("image/svg+xml", ICON.as_bytes().to_vec().into());
let second = crate::ImageSource::default().with_bytes(
"image/svg+xml",
ICON.replace(r#"fill="none""#, r#"fill="red""#)
.into_bytes()
.into(),
);
let first = crate::element::ImageSrc {
uri: first.uri.into(),
size: None,
scales: crate::ImageScales::NONE,
data: first.data,
};
let second = crate::element::ImageSrc {
uri: second.uri.into(),
size: None,
scales: crate::ImageScales::NONE,
data: second.data,
};
let current = signal(first);
view()
.items_start()
.on_press(move || current.set(second.clone()))
.child(svg(move || current.get()))
}
let mut c = core();
c.mount_root(&crate::element::Root::new::<BlobSvg>(|| ()));
let batch = c.commit().unwrap();
let (canvas_id, drawing) = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Canvas { id, drawing } if !drawing.ops.is_empty() => {
Some((*id, drawing.clone()))
}
_ => None,
})
.expect("svg(ImageSrc) with inline bytes should parse and emit drawing ops");
assert_eq!(
frame_of(&batch, canvas_id).unwrap().size,
size(px(24.0), px(24.0))
);
assert!(!drawing.ops.is_empty());
let trigger = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap();
assert!(c.component_event(trigger, EventKind::Press, &EventPayload::None));
let next = c.commit().unwrap();
let updated = next
.items
.iter()
.find_map(|i| match i {
MountItem::Canvas { drawing, .. } if !drawing.ops.is_empty() => Some(drawing),
_ => None,
})
.expect("replacing svg(ImageSrc) inline bytes should emit updated drawing ops");
assert_ne!(updated.ops, drawing.ops);
}
/// An app that sets its own design tokens while it runs.
#[component]
fn Themed() -> impl IntoElement {
let mut tokens = crate::element::Tokens::default();
tokens.set_color("popover", AdaptiveColor::rgb(0xffffff, 0x18181b));
set_tokens(tokens);
view()
}
/// Tokens an app sets reach what reads them and the platform, which
/// colors its own controls with them; tokens that did not change send
/// nothing.
#[test]
fn app_tokens_reach_the_platform() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Themed>(|| ()));
let mut sent = Vec::new();
while let Some(batch) = c.commit() {
sent.extend(batch.items.into_iter().filter_map(|i| match i {
MountItem::Command {
id: crate::ROOT_ID,
command: Command::Tokens(tokens),
} => Some(tokens),
_ => None,
}));
}
// The sample tokens `core()` set, then the app's.
let [_, tokens] = &sent[..] else {
panic!("{sent:?}")
};
assert_eq!(
tokens.color("popover"),
Some(AdaptiveColor::rgb(0xffffff, 0x18181b))
);
assert_eq!(c.tokens(), tokens);
let same = (**tokens).clone();
c.set_tokens(same);
assert!(c.commit().is_none_or(|b| !b.items.iter().any(|i| matches!(
i,
MountItem::Command {
command: Command::Tokens(_),
..
}
))));
}
/// A canvas that has drawn nothing and records an empty drawing (a
/// component's canvas before its first layout) sends nothing; one
/// that has drawn sends what it draws.
#[component]
fn EmptyAndDrawn() -> impl IntoElement {
view()
.child(canvas(Painter::new()))
.child(canvas(Painter::new().fill_rect(0.0, 0.0, 10.0, 10.0)))
}
#[test]
fn an_empty_first_drawing_sends_nothing() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<EmptyAndDrawn>(|| ()));
let batch = c.commit().unwrap();
let drawings: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Canvas { drawing, .. } => Some(drawing.clone()),
_ => None,
})
.collect();
assert_eq!(drawings.len(), 1, "{drawings:?}");
assert!(!drawings[0].ops.is_empty());
}
/// A label placed by its measured width, gradients, a stroked SVG path
/// and an operation built by hand reading an animated value.
#[component]
fn Label() -> impl IntoElement {
let offset = animated_value(3.0);
let width = crate::prelude::measure_text("600 20px system-ui", "100%");
let mut p = Painter::new()
.stroke_style(
CanvasGradient::conic(radians(0.0), point(px(50.0), px(50.0)))
.add_color_stop(percentage(1.0), rgb(0x6366f1))
.add_color_stop(percentage(0.0), rgb(0x22d3ee)),
)
.stroke_path(&svg_path("M20 6L9 17l-5-5"))
.fill_style(CanvasGradient::radial(
point(px(0.0), px(0.0)),
px(4.0),
point(px(0.0), px(0.0)),
px(40.0),
))
.fill_path(&svg_path("M0 0h10v10z"), FillRule::EvenOdd)
.fill_text("100%", 50.0 - width.0, 20.0);
let x = p.num(&offset);
p = p.op(CanvasOp::LineDashOffset(x));
view().child(canvas(p))
}
#[test]
fn rust_drawings_measure_text_and_use_every_paint() {
let mut c = core();
c.mount_root(&crate::element::Root::new::<Label>(|| ()));
let batch = c.commit().unwrap();
let drawing = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Canvas { drawing, .. } => Some(drawing.clone()),
_ => None,
})
.expect("a drawing");
let ops = &drawing.ops;
// Stops sorted by offset, whatever order they came in.
let CanvasOp::StrokeStyle(Paint::Gradient(ring)) = &ops[0] else {
panic!("{:?}", ops[0])
};
assert_eq!(
ring.shape,
GradientShape::Conic {
start_angle: radians(0.0),
center: point(px(50.0), px(50.0)),
}
);
assert_eq!(ring.stops[0], (percentage(0.0), Color::from(rgb(0x22d3ee))));
assert!(matches!(&ops[1], CanvasOp::Stroke(Some(path)) if path.len() == 3));
assert!(matches!(
&ops[2],
CanvasOp::FillStyle(Paint::Gradient(g)) if matches!(g.shape, GradientShape::Radial { .. })
));
assert!(matches!(
&ops[3],
CanvasOp::Fill(Some(_), FillRule::EvenOdd)
));
// 8pt per character in the fake engine.
assert!(matches!(
&ops[4],
CanvasOp::FillText {
x: Num::Const(18.0),
..
}
));
// The animated value is a slot of the drawing.
assert_eq!(ops[5], CanvasOp::LineDashOffset(Num::Slot(0)));
assert_eq!(drawing.slots.len(), 1);
}
}
/// A row (2) holding a field (3) whose absolutely placed menu (4) hangs
/// below it, inside a card (5): row and card get the menu's area, the
/// field does not reach out of the card, a clipping card stops it.
#[test]
fn overflowing_children_mount_their_area() {
let mut c = core();
let create = |id| Op::Create { id, tag: Tag::View };
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
apply(
&mut c,
vec![
create(5),
create(2),
create(4),
style_op(5, &[("padding", StyleValue::Number(10.0))]),
style_op(2, &[("height", StyleValue::Number(40.0))]),
style_op(
4,
&[
("position", StyleValue::Str("absolute")),
("top", StyleValue::Number(40.0)),
("left", StyleValue::Number(0.0)),
("width", StyleValue::Number(100.0)),
("height", StyleValue::Number(120.0)),
],
),
insert(2, 4),
insert(5, 2),
insert(ROOT_ID, 5),
],
);
let batch = c.commit().unwrap();
let overflow = |batch: &MountBatch, id: NodeId| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Overflow { id: i, extent } if *i == id => Some(*extent),
_ => None,
})
};
// The row is 300 wide (the card's padding), 40 tall: the menu reaches
// 120 below it.
assert_eq!(
overflow(&batch, 2),
Some(Some(rect(0.0, 0.0, 300.0, 160.0)))
);
// In the card (60 tall: 40 + padding) at (10, 10): down to 170.
assert_eq!(
overflow(&batch, 5),
Some(Some(rect(0.0, 0.0, 320.0, 170.0)))
);
// Leaves have nothing to report, and nothing is sent again unchanged.
assert_eq!(overflow(&batch, 4), None);
c.apply(style_op(2, &[("height", StyleValue::Number(40.0))]))
.unwrap();
if let Some(batch) = c.commit() {
assert_eq!(overflow(&batch, 2), None);
}
// A clipping card has no area (what is outside is not drawn), and the
// menu inside the row now fits: the row's area goes away.
c.apply(style_op(
5,
&[
("padding", StyleValue::Number(10.0)),
("overflow", StyleValue::Str("hidden")),
],
))
.unwrap();
c.apply(style_op(2, &[("height", StyleValue::Number(200.0))]))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(overflow(&batch, 5), Some(None));
assert_eq!(overflow(&batch, 2), Some(None));
}
/// A row (2) as tall as its 24pt button (4), whose hit slop of 10 reaches
/// out of the row, in a card (5) with padding 20: the row's area takes in
/// the slop, so a touch above the row, in the slop, reaches the button;
/// the card holds it inside, and a clipping row keeps it.
#[test]
fn hit_slop_outside_the_parent_reaches_the_child() {
use crate::{geometry::size, input::hit_area};
let mut c = core();
let create = |id| Op::Create { id, tag: Tag::View };
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let slop = |value: f32| Op::SetProp {
id: 4,
prop: Prop::HitSlop(EdgeInsets::all(Points(value))),
};
apply(
&mut c,
vec![
create(5),
create(2),
create(4),
style_op(5, &[("padding", StyleValue::Number(20.0))]),
style_op(
2,
&[
("flexDirection", StyleValue::Str("row")),
("height", StyleValue::Number(24.0)),
],
),
style_op(
4,
&[
("width", StyleValue::Number(24.0)),
("height", StyleValue::Number(24.0)),
],
),
slop(10.0),
insert(2, 4),
insert(5, 2),
insert(ROOT_ID, 5),
],
);
let batch = c.commit().unwrap();
let overflow = |batch: &MountBatch, id: NodeId| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Overflow { id: i, extent } if *i == id => Some(*extent),
_ => None,
})
};
// The row is 280 wide (the card's padding): the button's slop reaches
// 10 above, left of and below it.
let row = rect(-10.0, -10.0, 290.0, 44.0);
assert_eq!(overflow(&batch, 2), Some(Some(row)));
// At (20, 20) in the card, the slop stays inside it.
assert_eq!(overflow(&batch, 5), None);
let (row_size, button_size) = (
size(Points(280.0), Points(24.0)),
size(Points(24.0), Points(24.0)),
);
let none = EdgeInsets::default();
let ten = EdgeInsets::all(Points(10.0));
// 5pt above the row, over the button: the row looks into its children,
// and the button is hit in its slop.
let at = point(Points(12.0), Points(-5.0));
assert!(hit_area(at, row_size, none, Some(row), false, true).children);
let button = hit_area(at, button_size, ten, None, false, true);
assert!(!button.inside && button.in_slop);
// Past the slop, nothing is looked into.
let past = point(Points(12.0), Points(-12.0));
assert!(!hit_area(past, row_size, none, Some(row), false, true).children);
// The slop going away takes the area with it, without a new layout.
c.apply(slop(0.0)).unwrap();
let batch = c.commit().unwrap();
assert_eq!(overflow(&batch, 2), Some(None));
// Coming back, it reaches through the card too when it is larger
// than the card's padding.
c.apply(slop(30.0)).unwrap();
let batch = c.commit().unwrap();
assert_eq!(
overflow(&batch, 2),
Some(Some(rect(-30.0, -30.0, 310.0, 84.0)))
);
assert_eq!(
overflow(&batch, 5),
Some(Some(rect(-10.0, -10.0, 330.0, 84.0)))
);
// A row that clips its overflow has no area: a touch outside it is
// not looked into, as what is outside does not show.
c.apply(style_op(
2,
&[
("flexDirection", StyleValue::Str("row")),
("height", StyleValue::Number(24.0)),
("overflow", StyleValue::Str("hidden")),
],
))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(overflow(&batch, 2), Some(None));
assert_eq!(overflow(&batch, 5), Some(None));
assert!(!hit_area(at, row_size, none, None, true, true).children);
}
/// A view that loses its only, absolutely placed child lays out again:
/// taffy keeps the children it hoisted out of flow while the view has no
/// children to lay out, so the freed child must not stay listed there.
#[test]
fn a_view_that_loses_its_absolute_child_lays_out() {
let mut c = core();
for (id, absolute) in [(2, false), (4, true), (6, false)] {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
let mut props = vec![("height", StyleValue::Number(20.0))];
if absolute {
props.push(("position", StyleValue::Str("absolute")));
}
c.apply(style_op(id, &props)).unwrap();
}
for (parent, child) in [(2, 4), (ROOT_ID, 2), (ROOT_ID, 6)] {
c.apply(Op::Insert {
parent,
child,
before: None,
})
.unwrap();
}
c.commit().unwrap();
c.apply(Op::Release { id: 4 }).unwrap();
// A new node takes the freed one's slot.
c.apply(Op::Create {
id: 8,
tag: Tag::View,
})
.unwrap();
c.apply(Op::Insert {
parent: 6,
child: 8,
before: None,
})
.unwrap();
c.apply(style_op(2, &[("height", StyleValue::Number(30.0))]))
.unwrap();
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Frame { id: 6, frame, .. } if frame.origin.y.0 == 30.0
)));
}
/// An absolutely placed view leaving a block that is not laid out again (in
/// a `display: none` subtree, which taffy hides without renewing the
/// blocks' lists of the out-of-flow boxes they placed) lays out: the freed
/// view must not stay listed there. Its sibling stays and keeps the block
/// from being childless.
#[test]
fn an_absolute_view_leaving_a_hidden_block_lays_out() {
let mut c = core();
// 2 (hidden later) > 4 (relative: the block) > 6 (absolute), 8.
for (id, absolute) in [(2, false), (4, false), (6, true), (8, false)] {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
let mut props = vec![("height", StyleValue::Number(20.0))];
if absolute {
props.push(("position", StyleValue::Str("absolute")));
}
if id == 4 {
props.push(("position", StyleValue::Str("relative")));
}
c.apply(style_op(id, &props)).unwrap();
}
for (parent, child) in [(4, 6), (4, 8), (2, 4), (ROOT_ID, 2)] {
c.apply(Op::Insert {
parent,
child,
before: None,
})
.unwrap();
}
c.commit().unwrap();
c.apply(style_op(
2,
&[
("height", StyleValue::Number(20.0)),
("display", StyleValue::Str("none")),
],
))
.unwrap();
c.commit().unwrap();
// Out while hidden, and a new view takes the freed one's slot.
c.apply(Op::Release { id: 6 }).unwrap();
c.apply(Op::Create {
id: 10,
tag: Tag::View,
})
.unwrap();
c.apply(Op::Insert {
parent: ROOT_ID,
child: 10,
before: None,
})
.unwrap();
c.commit().unwrap();
// Shown again: the block lays its children out.
c.apply(style_op(2, &[("height", StyleValue::Number(30.0))]))
.unwrap();
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Frame { id: 10, frame, .. } if frame.origin.y.0 == 30.0
)));
}
/// As above, with the block absolutely placed itself: its fresh layout node
/// must not leave its old one listed by the block that placed it.
#[test]
fn an_absolute_view_leaving_a_hidden_absolute_block_lays_out() {
let mut c = core();
// 2 (hidden later) > 4 (absolute: the block) > 6 (absolute), 8.
for (id, absolute) in [(2, false), (4, true), (6, true), (8, false)] {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
let mut props = vec![("height", StyleValue::Number(20.0))];
if absolute {
props.push(("position", StyleValue::Str("absolute")));
}
c.apply(style_op(id, &props)).unwrap();
}
for (parent, child) in [(4, 6), (4, 8), (2, 4), (ROOT_ID, 2)] {
c.apply(Op::Insert {
parent,
child,
before: None,
})
.unwrap();
}
c.commit().unwrap();
c.apply(style_op(
2,
&[
("height", StyleValue::Number(20.0)),
("display", StyleValue::Str("none")),
],
))
.unwrap();
c.commit().unwrap();
// Out while hidden, and new views take the freed ones' slots.
c.apply(Op::Release { id: 6 }).unwrap();
for id in [10, 12] {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
c.apply(Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
})
.unwrap();
}
c.commit().unwrap();
// Shown again: the blocks lay their children out.
c.apply(style_op(2, &[("height", StyleValue::Number(30.0))]))
.unwrap();
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Frame { id: 10, frame, .. } if frame.origin.y.0 == 30.0
)));
}
/// `measure` gives the frame in the parent and the position in the root
/// view, minus the offsets of the scroll views around.
#[test]
fn measures_in_root_coordinates() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(
2,
&[
("marginTop", StyleValue::Number(50.0)),
("height", StyleValue::Number(300.0)),
],
),
style_op(
4,
&[
("padding", StyleValue::Number(20.0)),
("height", StyleValue::Number(1000.0)),
],
),
style_op(
6,
&[
("marginTop", StyleValue::Number(500.0)),
("height", StyleValue::Number(30.0)),
],
),
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
let m = c.measure(6).unwrap();
assert_eq!(m.frame, rect(20.0, 520.0, 280.0, 30.0));
assert_eq!(m.page, point(px(20.0), px(570.0)));
c.set_scroll_offset(2, point(px(0.0), px(400.0)), u32::MAX);
let m = c.measure(6).unwrap();
assert_eq!(m.page, point(px(20.0), px(170.0)));
// Detached or unknown: nothing to measure.
c.apply(Op::Remove {
parent: 4,
child: 6,
})
.unwrap();
c.commit();
assert_eq!(c.measure(6), None);
assert_eq!(c.measure(1000), None);
}
/// Outside a view's `clipPath` a press reaches neither the view nor the
/// views in it: the view under it is pressed (CSS's `clip-path`).
#[test]
fn presses_outside_a_clip_path_pass_through() {
let mut c = core();
let listen = |id| Op::Listen {
id,
event: EventKind::Press,
enabled: true,
};
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let size = |id| {
style_op(
id,
&[
("width", StyleValue::Number(100.0)),
("height", StyleValue::Number(100.0)),
],
)
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Create {
id: 6,
tag: Tag::View,
},
size(2),
size(4),
style_op(
4,
&[
("position", StyleValue::Str("absolute")),
("clipPath", StyleValue::Str("inset(0 0 50% 50% round 10px)")),
],
),
size(6),
listen(2),
listen(6),
insert(4, 6),
insert(2, 4),
insert(ROOT_ID, 2),
],
);
c.commit().unwrap();
// Inside the clip (the top right quarter): the view in the clipped one.
assert_eq!(
c.press_target(2, point(px(75.0), px(25.0))),
Some((6, point(px(75.0), px(25.0))))
);
// Clipped out, and in its rounded corner: the view behind.
for at in [point(px(25.0), px(75.0)), point(px(51.0), px(1.0))] {
assert_eq!(c.press_target(2, at), Some((2, at)));
}
}
/// A press passed on into an element (`ElementRef::press_at`) goes to the
/// innermost view under it that hears presses, in a subtree that takes no
/// pointer itself, and skips views that take none.
#[test]
fn presses_passed_on_reach_the_innermost_pressable_view() {
use crate::props::PointerEvents;
let mut c = core();
let listen = |id| Op::Listen {
id,
event: EventKind::Press,
enabled: true,
};
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(
2,
&[
("marginTop", StyleValue::Number(40.0)),
("height", StyleValue::Number(100.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::PointerEvents(PointerEvents::None),
},
style_op(
4,
&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(50.0)),
("flexDirection", StyleValue::Str("row")),
],
),
style_op(
6,
&[
("marginLeft", StyleValue::Number(50.0)),
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(20.0)),
],
),
style_op(
8,
&[
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(20.0)),
],
),
Op::SetProp {
id: 8,
prop: Prop::PointerEvents(PointerEvents::None),
},
listen(4),
listen(6),
listen(8),
insert(4, 6),
insert(4, 8),
insert(2, 4),
insert(ROOT_ID, 2),
],
);
c.commit().unwrap();
// On 6 (at 50..70 in 4, which is at 40 in the root).
assert_eq!(
c.press_target(2, point(px(55.0), px(45.0))),
Some((6, point(px(5.0), px(5.0))))
);
// On 8, which takes no pointer: 4 under it.
assert_eq!(
c.press_target(2, point(px(75.0), px(45.0))),
Some((4, point(px(75.0), px(5.0))))
);
// Past every view that hears presses.
assert_eq!(c.press_target(2, point(px(10.0), px(120.0))), None);
// The commit passes it on as the platforms report a press.
c.components.presses.push((
2,
crate::PressEvent {
page_position: point(px(55.0), px(45.0)),
clicks: 2,
..Default::default()
},
crate::element::Answer::<bool>::new().1,
));
c.commit();
let pressed: Vec<_> = js_events(&mut c)
.into_iter()
.filter(|(_, kind, _)| *kind == EventKind::Press)
.collect();
assert!(matches!(
&pressed[..],
[(6, _, EventPayload::Press(p))] if p.position == point(px(5.0), px(5.0)) && p.clicks == 2
));
}
/// A pointer passed on into an element (`ElementRef::hover_at`) hovers
/// the views under it in a subtree that takes no pointer itself: their
/// `hover:` and `group-hover:` classes apply, the views that listen hear
/// the mouse enter, move and leave, and its leaving undoes it.
#[test]
fn hovers_passed_on_reach_the_views_under_the_pointer() {
use crate::props::PointerEvents;
let mut c = core();
let listen = |id, event| Op::Listen {
id,
event,
enabled: true,
};
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let create = |id| Op::Create { id, tag: Tag::View };
let size = |id, w: f32, h: f32, more: &[(&'static str, StyleValue)]| {
let mut style = vec![
("width", StyleValue::Number(w)),
("height", StyleValue::Number(h)),
];
style.extend_from_slice(more);
style_op(id, &style)
};
apply(
&mut c,
vec![
create(2),
create(4),
create(6),
create(8),
style_op(
2,
&[
("marginTop", StyleValue::Number(40.0)),
("height", StyleValue::Number(100.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::PointerEvents(PointerEvents::None),
},
size(4, 200.0, 50.0, &[("flexDirection", StyleValue::Str("row"))]),
class_op(4, "group"),
size(6, 20.0, 20.0, &[("marginLeft", StyleValue::Number(50.0))]),
class_op(6, "hover:opacity-50"),
listen(6, EventKind::MouseEnter),
listen(6, EventKind::MouseLeave),
listen(6, EventKind::MouseMove),
size(8, 20.0, 20.0, &[]),
class_op(8, "group-hover:opacity-25"),
insert(4, 6),
insert(4, 8),
insert(2, 4),
insert(ROOT_ID, 2),
],
);
c.commit().unwrap();
js_events(&mut c);
let mouse = |x: f32, y: f32| crate::MouseEvent {
page_position: point(px(x), px(y)),
..Default::default()
};
let mouse_events = |c: &mut Core<FakeEngine>| -> Vec<(NodeId, EventKind, Point<Points>)> {
js_events(c)
.into_iter()
.filter_map(|(id, kind, payload)| match payload {
EventPayload::Mouse(m) => Some((id, kind, m.position)),
_ => None,
})
.collect()
};
let opacity = |batch: &MountBatch, id| view_style_of(batch, id).map(|s| s.opacity);
// Over 6 (at 50..70 in 4, which is at 40 in the root).
c.components.hovers.push((2, Some(mouse(55.0, 45.0))));
let batch = c.commit().unwrap();
assert_eq!(opacity(&batch, 6), Some(0.5), "hover:");
assert_eq!(opacity(&batch, 8), Some(0.25), "group-hover:");
assert_eq!(
mouse_events(&mut c),
vec![
(6, EventKind::MouseEnter, point(px(5.0), px(5.0))),
(6, EventKind::MouseMove, point(px(5.0), px(5.0))),
]
);
// A move inside 6 only moves.
c.components.hovers.push((2, Some(mouse(56.0, 46.0))));
c.commit();
assert_eq!(
mouse_events(&mut c),
vec![(6, EventKind::MouseMove, point(px(6.0), px(6.0)))]
);
// Off 6, still in the group: 6 is left, the group stays hovered.
c.components.hovers.push((2, Some(mouse(150.0, 45.0))));
let batch = c.commit().unwrap();
assert_eq!(opacity(&batch, 6), Some(1.0));
assert_eq!(opacity(&batch, 8), None, "unchanged");
assert_eq!(
mouse_events(&mut c),
vec![(6, EventKind::MouseLeave, point(px(100.0), px(5.0)))]
);
// The pointer leaves.
c.components.hovers.push((2, None));
let batch = c.commit().unwrap();
assert_eq!(opacity(&batch, 8), Some(1.0));
assert!(mouse_events(&mut c).is_empty());
assert!(c.passed_hovers.is_empty());
}
/// `reveal` becomes a `ScrollTo` of the scroll view around, placed
/// as its alignment says, and nothing when the view is where it would go.
#[test]
fn reveals_a_view() {
let mut c = scroll_around_view(500.0, 30.0);
let scroll = |c: &mut Core<FakeEngine>, vertical| {
c.apply(Op::Command {
id: 6,
command: Command::Reveal(crate::RevealOptions {
vertical,
animated: false,
..Default::default()
}),
})
.unwrap();
c.commit().and_then(|batch| {
batch.items.iter().find_map(|item| match item {
MountItem::Command {
id: 2,
command: Command::ScrollTo { y, animated, .. },
} => {
assert!(!animated);
Some(y.0)
}
MountItem::Command { command, .. } => {
panic!("only the scroll view scrolls: {command:?}")
}
_ => None,
})
})
};
use crate::ScrollAlignment::*;
assert_eq!(scroll(&mut c, Start), Some(520.0));
c.set_scroll_offset(2, point(px(0.0), px(520.0)), u32::MAX);
assert_eq!(scroll(&mut c, Nearest), None);
assert_eq!(scroll(&mut c, Center), Some(385.0));
assert_eq!(scroll(&mut c, End), Some(250.0));
c.set_scroll_offset(2, point(px(0.0), px(0.0)), u32::MAX);
assert_eq!(scroll(&mut c, Nearest), Some(250.0));
}
#[test]
fn revealing_an_inline_attachment_first_lays_out_its_culled_text() {
for nested in [false, true] {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
class_op(2, "h-[100px]"),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for row in 0..60 {
let id = 10 + row * 2;
ops.extend([
Op::Create { id, tag: Tag::Text },
Op::CreateText {
id: id + 1,
text: format!("Row {row}"),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
ops.extend([
Op::Create {
id: 200,
tag: Tag::View,
},
class_op(200, "w-[1px] h-[1px]"),
Op::Insert {
parent: 128,
child: 200,
before: None,
},
]);
let target = if nested {
ops.extend([
Op::Create {
id: 201,
tag: Tag::View,
},
class_op(201, "w-[1px] h-[1px]"),
Op::Insert {
parent: 200,
child: 201,
before: None,
},
]);
201
} else {
200
};
apply(&mut c, ops);
c.commit().unwrap();
assert!(c.measure(target).is_none());
c.apply(Op::Command {
id: target,
command: Command::Reveal(crate::RevealOptions::default()),
})
.unwrap();
let batch = c.commit().unwrap();
let offset = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Command {
id: 2,
command: Command::ScrollTo { y, .. },
} => Some(*y),
_ => None,
})
.expect("the containing scroll view reveals the attachment");
c.set_scroll_offset(2, point(Points::ZERO, offset), u32::MAX);
c.commit();
let shown = c.measure(target).unwrap();
assert!((0.0..=100.0).contains(&shown.page.y.0), "{shown:?}");
}
}
/// A scroll view 300pt high (2) over content 1000pt high with a padding of
/// 20 (4), holding view 6 at `top` below the padding, `height` high.
fn scroll_around_view(top: f32, height: f32) -> Core<FakeEngine> {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(2, &[("height", StyleValue::Number(300.0))]),
style_op(
4,
&[
("padding", StyleValue::Number(20.0)),
("height", StyleValue::Number(1000.0)),
],
),
style_op(
6,
&[
("marginTop", StyleValue::Number(top)),
("height", StyleValue::Number(height)),
],
),
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
c
}
/// The offsets the commit's `ScrollTo` commands send scroll view 2 to.
fn scrolls_of_scroll_view(c: &mut Core<FakeEngine>) -> Vec<f32> {
c.commit().map_or(Vec::new(), |batch| {
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
id: 2,
command: Command::ScrollTo { y, .. },
} => Some(y.0),
_ => None,
})
.collect()
})
}
fn nearest_into_view() -> Op {
Op::Command {
id: 6,
command: Command::Reveal(crate::RevealOptions {
vertical: crate::ScrollAlignment::Nearest,
animated: false,
..Default::default()
}),
}
}
/// `"nearest"` leaves a view longer than the viewport where it is while it
/// covers the viewport; past one edge, it brings its other edge to the
/// viewport's other edge, as CSSOM View does.
#[test]
fn nearest_keeps_the_viewport_inside_a_longer_view() {
let mut c = scroll_around_view(0.0, 800.0);
c.set_scroll_offset(2, point(px(0.0), px(100.0)), u32::MAX);
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), Vec::<f32>::new());
c.set_scroll_offset(2, point(px(0.0), px(0.0)), u32::MAX);
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![20.0]);
c.set_scroll_offset(2, point(px(0.0), px(600.0)), u32::MAX);
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![520.0]);
}
/// `reveal` starts from where the commit's earlier scroll commands
/// put the scroll view, not from where the platform last reported it.
#[test]
fn reveal_follows_earlier_scroll_commands() {
let mut c = scroll_around_view(0.0, 30.0);
c.apply(Op::Command {
id: 2,
command: Command::ScrollTo {
x: px(0.0),
y: px(500.0),
animated: false,
},
})
.unwrap();
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![500.0, 20.0]);
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![700.0, 20.0]);
c.set_scroll_offset(2, point(px(0.0), px(500.0)), u32::MAX);
c.apply(nearest_into_view()).unwrap();
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![20.0]);
}
/// A scroll from an earlier commit counts until the platform reports it
/// applied: `reveal` starts from where it goes.
#[test]
fn reveal_follows_unreported_scrolls() {
let mut c = scroll_around_view(0.0, 30.0);
c.apply(Op::Command {
id: 2,
command: Command::ScrollTo {
x: px(0.0),
y: px(500.0),
animated: true,
},
})
.unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![500.0]);
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![20.0]);
// Reported applied: the report is where it is.
c.set_scroll_offset(2, point(px(0.0), px(20.0)), u32::MAX);
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), Vec::<f32>::new());
}
/// With content insets, a view already in view stays put, at the offsets
/// the insets add past either end.
#[test]
fn reveal_keeps_still_within_content_insets() {
let inset = |c: &mut Core<FakeEngine>, insets: EdgeInsets| {
c.apply(Op::SetProp {
id: 2,
prop: Prop::Scroll(crate::ops::ScrollProp::ContentInset(insets)),
})
.unwrap();
c.commit().unwrap();
};
let mut c = scroll_around_view(0.0, 30.0);
inset(
&mut c,
EdgeInsets {
top: px(50.0),
..EdgeInsets::default()
},
);
c.set_scroll_offset(2, point(px(0.0), px(-50.0)), u32::MAX);
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), Vec::<f32>::new());
let mut c = scroll_around_view(900.0, 60.0);
inset(
&mut c,
EdgeInsets {
bottom: px(100.0),
..EdgeInsets::default()
},
);
c.set_scroll_offset(2, point(px(0.0), px(800.0)), u32::MAX);
c.apply(nearest_into_view()).unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), Vec::<f32>::new());
// As far as the bottom inset lets the platform scroll.
c.set_scroll_offset(2, point(px(0.0), px(0.0)), u32::MAX);
c.apply(Op::Command {
id: 6,
command: Command::Reveal(crate::RevealOptions {
vertical: crate::ScrollAlignment::Start,
animated: false,
..Default::default()
}),
})
.unwrap();
assert_eq!(scrolls_of_scroll_view(&mut c), vec![800.0]);
}
/// `desktop={{ windowDrag }}` reaches the platform in the view's props, and
/// clearing it sends them again.
#[test]
fn window_drag_is_a_view_prop() {
let mut c = core();
let drag = |value| Op::SetProp {
id: 2,
prop: Prop::WindowDrag(value),
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
drag(Some(true)),
Op::Insert {
parent: crate::ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(
|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.window_drag == Some(true))
));
apply(&mut c, vec![drag(None)]);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(
|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.window_drag.is_none())
));
}
/// `web={{ element }}` reaches the platform in the view's props (the web
/// draws the view as that HTML element), and clearing it sends the props
/// again.
#[test]
fn web_element_is_a_view_prop() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::WebElement(Some(crate::WebElement::Nav)),
},
Op::Insert {
parent: crate::ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::ViewProps { id: 2, props } if props.web_element == Some(crate::WebElement::Nav)
)));
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::WebElement(None),
}],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::ViewProps { id: 2, props } if props.web_element.is_none()
)));
}
/// `focusable={false}` reaches the platform in the view's props.
#[test]
fn focusable_is_a_view_prop() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Focusable(Some(false)),
},
Op::Insert {
parent: crate::ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(
|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.focusable == Some(false))
));
// Cleared (JS's `undefined`): the default, sent again.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Focusable(None),
}],
);
let batch = c.commit().unwrap();
assert!(
batch.items.iter().any(
|i| matches!(i, MountItem::ViewProps { id: 2, props } if props.focusable.is_none())
)
);
}
/// The keyboard focus's stops, decided from what is mounted: views that
/// take presses, unless `focusable={false}`, and any view that is
/// `focusable={true}`, without taking presses (a chart in a pressable
/// card); never a disabled one. Tab goes through them in tree order.
#[test]
fn focusable_views_are_stops_without_taking_presses() {
let mut c = core();
let view = |id: NodeId, parent: NodeId| {
[
Op::Create { id, tag: Tag::View },
Op::Insert {
parent,
child: id,
before: None,
},
]
};
let listen = |id: NodeId, event: EventKind| Op::Listen {
id,
event,
enabled: true,
};
let focusable = |id: NodeId, on: bool| Op::SetProp {
id,
prop: Prop::Focusable(Some(on)),
};
let (card, chart, plain, backdrop, button, off) = (2, 4, 6, 8, 10, 12);
let mut ops = Vec::new();
ops.extend(view(card, crate::ROOT_ID));
ops.push(listen(card, EventKind::Press));
ops.extend(view(chart, card));
ops.push(focusable(chart, true));
ops.push(listen(chart, EventKind::Focus));
ops.push(listen(chart, EventKind::Blur));
ops.extend(view(plain, crate::ROOT_ID));
ops.extend(view(backdrop, crate::ROOT_ID));
ops.push(listen(backdrop, EventKind::Press));
ops.push(focusable(backdrop, false));
ops.extend(view(button, crate::ROOT_ID));
ops.push(listen(button, EventKind::Press));
ops.extend(view(off, crate::ROOT_ID));
ops.push(focusable(off, true));
ops.push(Op::SetProp {
id: off,
prop: Prop::Native(NativeProp::Disabled(true)),
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
let props = |id: NodeId| {
batch
.items
.iter()
.rev()
.find_map(|i| match i {
MountItem::ViewProps { id: i, props } if *i == id => Some(props.clone()),
_ => None,
})
.unwrap_or_default()
};
let events = |id: NodeId| {
batch
.items
.iter()
.rev()
.find_map(|i| match i {
MountItem::Events { id: i, events } if *i == id => Some(*events),
_ => None,
})
.unwrap_or_default()
};
// Focusable takes no presses: the card around it keeps them.
assert!(!events(chart).contains(EventKind::Press));
assert!(events(chart).contains(EventKind::Focus));
let order = [card, chart, plain, backdrop, button, off];
let stops: Vec<NodeId> = order
.into_iter()
.filter(|&id| props(id).focus_stop(events(id).contains(EventKind::Press)))
.collect();
assert_eq!(stops, [card, chart, button]);
// Tab from nowhere, then on and around.
let mut at = None;
let mut visited = Vec::new();
for _ in 0..4 {
at = crate::input::tab_stop(at, stops.len(), false, true);
visited.push(stops[at.unwrap()]);
}
assert_eq!(visited, [card, chart, button, card]);
// Unset again: the chart takes no presses, so it is no stop.
apply(
&mut c,
vec![Op::SetProp {
id: chart,
prop: Prop::Focusable(None),
}],
);
let batch = c.commit().unwrap();
let props = batch
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { id, props } if *id == chart => Some(props.clone()),
_ => None,
})
.expect("the chart's props, sent again");
assert!(!props.focus_stop(false));
assert!(props.focus_stop(true));
}
/// Components that run once: their views mounted with bindings.
mod views {
use std::{cell::Cell, rc::Rc};
use serde_json::json;
use super::*;
use crate::{
Prop,
element::{Component, Props, Registry, Root, Scope},
prelude::*,
};
pub(super) fn texts(batch: &MountBatch) -> Vec<String> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.clone()),
_ => None,
})
.collect()
}
pub(super) fn root_host(batch: &MountBatch) -> NodeId {
batch
.items
.iter()
.find_map(|i| match i {
MountItem::Insert {
parent: ROOT_ID,
child,
..
} => Some(*child),
_ => None,
})
.expect("the root's host is in the root view")
}
/// The node showing text `content`.
fn text_node(batch: &MountBatch, content: &str) -> NodeId {
batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id, text, .. } if text.text == content => Some(*id),
_ => None,
})
.unwrap_or_else(|| panic!("no text {content:?}"))
}
/// The native parent of node `id`.
fn native_parent<M: TextEngine>(c: &Core<M>, id: NodeId) -> Option<NodeId> {
let key = c.key(id).expect("a node");
let parent = c.nodes[key as usize].parent;
(parent != NO_KEY).then(|| c.nodes[parent as usize].id)
}
/// Counts presses: the text is a binding, nothing renders again.
#[derive(Default)]
struct Counter;
#[derive(Clone, PartialEq, Props)]
struct CounterProps {
#[prop(default = "Taps".into())]
label: crate::element::Prop<SharedString>,
}
#[derive(Event)]
enum CounterEvent {
Tap(u32),
}
impl Component for Counter {
type Props = CounterProps;
type Event = CounterEvent;
fn view(props: CounterProps, cx: Scope<CounterEvent>) -> impl IntoElement {
let count = signal(0);
view()
.p_2()
.on_press(move |_: &()| {
count.update(|n| *n += 1);
cx.emit(CounterEvent::Tap(count.get_untracked()));
})
.child(text(move || {
format!("{} {}", props.label.get(), count.get())
}))
.child(text("static"))
}
}
#[test]
fn a_view_runs_once_and_its_bindings_send_only_what_changed() {
let mut c = core();
c.mount_root(&Root::new::<Counter>(|| CounterProps {
label: "Hits".into(),
}));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Hits 0", "static"]);
let host = root_host(&batch);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Hits 1"], "one text changed");
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { .. } | MountItem::Delete { .. })),
"no node made or freed: {:?}",
batch.items
);
}
/// Two listeners of one event on one element, and of a nested
/// component's events, each noting itself.
#[component]
fn Twice() -> impl IntoElement {
let log = signal(String::new());
let note = move |c: char| log.update(|l| l.push(c));
view()
.on_press(move || note('a'))
.on_press(move || note('b'))
.child(
Counter::element(CounterProps::default())
.on_event(move |_: &CounterEvent| note('c'))
.on_event(move |_: &CounterEvent| note('d')),
)
.child(text(move || format!("log {}", log.get())))
}
#[test]
fn every_listener_of_an_event_runs_in_order() {
let mut c = core();
c.mount_root(&Root::new::<Twice>(|| ()));
let batch = c.commit().unwrap();
let host = root_host(&batch);
let counter = native_parent(&c, text_node(&batch, "Taps 0")).unwrap();
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["log ab"]);
assert!(c.component_event(counter, EventKind::Press, &EventPayload::None));
assert!(texts(&c.commit().unwrap()).contains(&"log abcd".to_owned()));
}
#[derive(Event)]
enum ChooserEvent {
Press,
Pick(u32),
Placed { at: u32 },
}
/// Emits each of its events on a press: a press, the pick 7, the
/// placement at 9.
#[component]
fn Chooser(cx: Scope<ChooserEvent>) -> impl IntoElement {
view().child(text("choose")).on_press(move || {
cx.emit(ChooserEvent::Press);
cx.emit(ChooserEvent::Pick(7));
cx.emit(ChooserEvent::Placed { at: 9 });
})
}
/// A [`Chooser`] heard through its events' listener methods.
#[component]
fn Chosen() -> impl IntoElement {
let log = signal(String::new());
let note = move |s: String| log.update(|l| l.push_str(&s));
view()
.child(
chooser()
.on_press(move || note("press ".into()))
.on_press(move |_: &()| note("again ".into()))
.on_pick(move |index: &u32| note(format!("pick {index} ")))
.on_placed(move |event: &ChooserEvent| {
if let ChooserEvent::Placed { at } = event {
note(format!("placed {at}"));
}
}),
)
.child(text(move || format!("log {}", log.get())))
}
#[test]
fn a_components_listener_methods_hear_their_event_and_its_data() {
let mut c = core();
c.mount_root(&Root::new::<Chosen>(|| ()));
let batch = c.commit().unwrap();
let chooser = native_parent(&c, text_node(&batch, "choose")).unwrap();
assert!(c.component_event(chooser, EventKind::Press, &EventPayload::None));
assert_eq!(
texts(&c.commit().unwrap()),
["log press again pick 7 placed 9"]
);
}
/// A region made again with what it read: its pressable text is kept
/// (the same node), its listener the new run's.
#[component]
fn Rerun() -> impl IntoElement {
let log = signal(String::new());
let run = signal(0);
view()
.child(dynamic(move || {
let at = run.get();
text("tap").on_press(move || log.update(|l| l.push_str(&at.to_string())))
}))
.child(text("again").on_press(move || run.update(|r| *r += 1)))
.child(text(move || format!("log {}", log.get())))
}
#[test]
fn a_node_made_again_hears_only_its_new_listeners() {
let mut c = core();
c.mount_root(&Root::new::<Rerun>(|| ()));
let batch = c.commit().unwrap();
let (tap, again) = (text_node(&batch, "tap"), text_node(&batch, "again"));
for _ in 0..3 {
assert!(c.component_event(again, EventKind::Press, &EventPayload::None));
let _ = c.commit();
}
assert!(c.component_event(tap, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["log 3"]);
}
/// Rebuilds a text with fresh bindings, then with static values, then
/// without its optional style and label.
#[component]
fn ReboundText() -> impl IntoElement {
let run = signal(0_u8);
let current = signal(None::<Signal<bool>>);
view()
.child(text("break").on_press(move || {
current.get_untracked().unwrap().set(true);
}))
.child(text("switch").on_press(move || run.update(|n| *n += 1)))
.child(dynamic(move || {
let at = run.get();
if at >= 4 {
return text("fine").into_element();
}
if at == 3 {
return text("fine")
.text_color(rgb(0x808080))
.label("fine")
.into_element();
}
let bad = signal(false);
current.set(Some(bad));
text(move || if bad.get() { "bad" } else { "fine" })
.text_color(move || {
if bad.get() {
rgb(0xff0000)
} else {
rgb(0x808080)
}
})
.style_when(bad, |s| s.opacity(0.5))
.label(move || if bad.get() { "bad" } else { "fine" })
.into_element()
}))
}
#[test]
fn reused_nodes_diff_against_their_latest_bound_values() {
let mut c = core();
c.mount_root(&Root::of::<ReboundText>());
let batch = c.commit().unwrap();
let (break_it, switch, line) = (
text_node(&batch, "break"),
text_node(&batch, "switch"),
text_node(&batch, "fine"),
);
assert!(c.component_event(switch, EventKind::Press, &EventPayload::None));
assert!(
c.commit().is_none(),
"unchanged bindings send no mount items"
);
for _ in 0..2 {
assert!(c.component_event(break_it, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::Text { id, text, .. }
if *id == line && text.text == "bad" && text.spans[0].style.color == crate::Color(0xff0000ff)
)));
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::AccessibilityLabel { id, label } if *id == line && label.as_deref() == Some("bad")
)));
assert!(c.component_event(switch, EventKind::Press, &EventPayload::None));
let batch = c.commit().expect("the new run resets the bound values");
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::Text { id, text, .. }
if *id == line && text.text == "fine" && text.spans[0].style.color == crate::Color(0x808080ff)
)), "the reused text resets its content and color: {:?}", batch.items);
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::AccessibilityLabel { id, label } if *id == line && label.as_deref() == Some("fine")
)));
assert_eq!(view_style_of(&batch, line).unwrap().opacity, 1.0);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { .. } | MountItem::Delete { .. })),
"the node is reused"
);
}
// Static values remain cheap, including after the binding was removed.
assert!(c.component_event(switch, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(i,
MountItem::AccessibilityLabel { id, label } if *id == line && label.is_none()
)));
assert!(c.component_event(switch, EventKind::Press, &EventPayload::None));
assert!(c.commit().is_none(), "unchanged values send no mount items");
}
#[test]
fn a_prop_from_js_reaches_only_what_reads_it() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Counter>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Counter>().into()),
},
Op::SetProp {
id: 2,
prop: rust_prop::<CounterProps>("label", Some(json!("Hits"))),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
assert_eq!(texts(&c.commit().unwrap()), ["Hits 0", "static"]);
c.apply(Op::SetProp {
id: 2,
prop: rust_prop::<CounterProps>("label", Some(json!("Runs"))),
})
.unwrap();
assert_eq!(texts(&c.commit().unwrap()), ["Runs 0"]);
// Its events reach JS.
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
c.commit();
let events = js_events(&mut c);
assert!(events.iter().any(|(id, kind, payload)| *id == 2
&& *kind == EventKind::NativeEvent
&& matches!(payload, EventPayload::Native { name, data } if &**name == "tap" && *data == json!({ "value": 1 }))));
}
/// Shows one branch or the other.
#[derive(Default)]
struct Toggle;
#[derive(Clone, PartialEq, Props)]
struct ToggleProps {}
thread_local! {
static CLEANED: Cell<u32> = const { Cell::new(0) };
}
impl Component for Toggle {
type Props = ToggleProps;
type Event = NoEvent;
fn view(_: ToggleProps, _: Scope<NoEvent>) -> impl IntoElement {
let on = signal(false);
view()
.on_press(move |_: &()| on.update(|v| *v = !*v))
.child(text("before"))
.child(
when(on, || {
cleanup(|| CLEANED.with(|c| c.set(c.get() + 1)));
text("on")
})
.otherwise(|| text("off")),
)
.child(text("after"))
}
}
/// The texts under `parent`, in order (by the inserts of `batch` and
/// those before).
fn order(c: &Core<FakeEngine>, parent: NodeId) -> Vec<String> {
let key = c.key(parent).unwrap();
c.nodes[key as usize]
.children
.iter()
.filter_map(|&k| {
let node = &c.nodes[k as usize];
node.children
.first()
.map(|&raw| c.nodes[raw as usize].text.clone())
.or_else(|| c.folded_text(c.key(node.id).unwrap()).map(str::to_owned))
})
.collect()
}
#[test]
fn if_makes_the_branch_it_flips_to_in_place_and_drops_the_other() {
let mut c = core();
c.mount_root(&Root::new::<Toggle>(|| ToggleProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
assert_eq!(order(&c, host), ["before", "off", "after"]);
c.component_event(host, EventKind::Press, &EventPayload::None);
c.commit();
assert_eq!(order(&c, host), ["before", "on", "after"]);
c.component_event(host, EventKind::Press, &EventPayload::None);
c.commit();
assert_eq!(order(&c, host), ["before", "off", "after"]);
assert_eq!(CLEANED.with(Cell::get), 1, "the branch's cleanup ran");
}
/// Flips its branch there and back in one listener: each branch is a
/// component with a prop.
#[derive(Default)]
struct Flicker;
#[derive(Clone, PartialEq, Props)]
struct FlickerProps {}
impl Component for Flicker {
type Props = FlickerProps;
type Event = NoEvent;
fn view(_: FlickerProps, _: Scope<NoEvent>) -> impl IntoElement {
let on = signal(false);
view()
.on_press(move |_: &()| {
on.set(true);
on.set(false);
})
.child(
when(on, || Counter::element(CounterProps { label: "On".into() })).otherwise(
|| {
Counter::element(CounterProps {
label: "Off".into(),
})
},
),
)
}
}
#[test]
fn a_region_run_replaced_before_it_applied_is_never_applied() {
let mut c = core();
c.mount_root(&Root::new::<Flicker>(|| FlickerProps {}));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Off 0", "static"]);
let host = root_host(&batch);
// The "on" run's props went with it before the core applied it:
// only the "off" run applies, to the same counter.
c.component_event(host, EventKind::Press, &EventPayload::None);
let texts = c.commit().map(|batch| texts(&batch)).unwrap_or_default();
assert!(!texts.iter().any(|t| t.starts_with("On")), "{texts:?}");
}
#[component]
fn RetainedLayoutListener() -> impl IntoElement {
let count = signal(0_u32);
let listener: Listener<Bounds<Points>> =
(move |_: &Bounds<Points>| count.update(|n| *n += 1)).into();
view().child(dynamic(move || {
let current = count.get();
let measured = signal(0.0_f32);
view()
.w(px(100.0))
.h(px(40.0))
.on_layout(listener.clone())
.on_layout(move |frame: &Bounds<Points>| measured.set(frame.size.width.0))
.child(text(move || {
format!("count {current} width {}", measured.get())
}))
}))
}
#[test]
fn a_retained_layout_listener_is_not_reinitialized_with_a_new_runs_listener() {
let mut c = core();
c.mount_root(&Root::new::<RetainedLayoutListener>(|| ()));
c.commit().unwrap();
let mut shown = Vec::new();
// Bounded: a replay to the retained listener would keep increasing
// count and queueing another run, despite an unchanged frame.
for _ in 0..8 {
for (id, kind, payload) in js_events(&mut c) {
c.component_event(id, kind, &payload);
}
if let Some(batch) = c.commit() {
shown.extend(texts(&batch));
}
}
assert_eq!(last_with(&shown, "count"), "count 1 width 100");
assert!(js_events(&mut c).is_empty());
assert!(c.commit().is_none());
}
/// A box whose layout flips a region in it; the region's node writes a
/// signal of its own run as it lays out, and logs the run.
#[component]
fn LayoutRerun() -> impl IntoElement {
let width = signal(100.0_f32);
let wide = signal(false);
let log = signal(String::new());
view()
.child(text("grow").on_press(move || width.update(|w| *w += 100.0)))
.child(
view()
.w(move || px(width.get()))
.h(px(40.0))
.on_layout(move |b: &Bounds<Points>| wide.set(b.size.width.0 > 150.0))
.child(dynamic(move || {
let is_wide = wide.get();
let size = signal(0.0_f32);
view()
.w_full()
.h(px(20.0))
.on_layout(move |b: &Bounds<Points>| {
log.update(|l| l.push_str(if is_wide { "W" } else { "n" }));
size.set(b.size.width.0);
})
.child(text(move || format!("wide {is_wide} inner {}", size.get())))
})),
)
.child(text(move || format!("log {}", log.get())))
}
/// Hands the core's events to the components and commits, as the
/// engine does, until nothing changes: the texts the batches set, in
/// order.
fn settle(c: &mut Core<FakeEngine>) -> Vec<String> {
let mut texts_set = Vec::new();
loop {
for (id, kind, payload) in js_events(c) {
c.component_event(id, kind, &payload);
}
let Some(batch) = c.commit() else {
return texts_set;
};
texts_set.extend(texts(&batch));
}
}
/// The last of `texts` starting with `prefix`.
fn last_with<'a>(texts: &'a [String], prefix: &str) -> &'a str {
texts
.iter()
.rev()
.find(|t| t.starts_with(prefix))
.unwrap_or_else(|| panic!("no {prefix:?} in {texts:?}"))
}
#[test]
fn a_layout_queued_for_a_replaced_runs_node_does_not_reach_its_listener() {
let mut c = core();
c.mount_root(&Root::new::<LayoutRerun>(|| ()));
let batch = c.commit().unwrap();
let grow = text_node(&batch, "grow");
let set = settle(&mut c);
assert_eq!(last_with(&set, "wide"), "wide false inner 100");
assert_eq!(last_with(&set, "log"), "log n");
// The box's layout and the region's node's come in one pass: the
// box's flips the region, whose old run goes (its `size` with it)
// before the old node's layout is handed out. That listener no
// longer runs; the new run's hears the node's frame once it is
// mounted.
assert!(c.component_event(grow, EventKind::Press, &EventPayload::None));
let set = settle(&mut c);
assert_eq!(last_with(&set, "wide"), "wide true inner 200");
assert_eq!(last_with(&set, "log"), "log nW");
}
/// A list of rows by key.
#[derive(Default)]
struct Rows;
#[derive(Clone, PartialEq, Props)]
struct RowsProps {}
thread_local! {
static MADE: Cell<u32> = const { Cell::new(0) };
static ITEMS: Cell<Option<Signal<Vec<u32>>>> = const { Cell::new(None) };
}
impl Component for Rows {
type Props = RowsProps;
type Event = NoEvent;
fn view(_: RowsProps, _: Scope<NoEvent>) -> impl IntoElement {
let items = signal(vec![1, 2, 3]);
ITEMS.with(|i| i.set(Some(items)));
view().child(each(
items,
|n| *n,
|item, index| {
MADE.with(|m| m.set(m.get() + 1));
text(move || format!("{}@{}", item.get(), index.get()))
},
))
}
}
#[test]
fn each_keeps_the_rows_that_stay_and_makes_only_new_ones() {
let mut c = core();
c.mount_root(&Root::new::<Rows>(|| RowsProps {}));
let batch = c.commit().unwrap();
// The rows are the root view's children: the host's.
let list = root_host(&batch);
assert_eq!(order(&c, list), ["1@0", "2@1", "3@2"]);
let one = text_node(&batch, "1@0");
let items = ITEMS.with(Cell::get).unwrap();
{
let _entered = c.components.runtime.enter();
items.set(vec![3, 1, 4]);
}
let batch = c.commit().unwrap();
assert_eq!(order(&c, list), ["3@0", "1@1", "4@2"]);
assert_eq!(MADE.with(Cell::get), 4, "one new row");
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { id, .. } if *id == one)),
"row 1 kept its node"
);
}
/// A list whose rows are regions: row 2 shows nothing until `LATE`.
#[derive(Default)]
struct RegionRows;
thread_local! {
static REGION_ITEMS: Cell<Option<Signal<Vec<u32>>>> = const { Cell::new(None) };
static LATE: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
impl Component for RegionRows {
type Props = RowsProps;
type Event = NoEvent;
fn view(_: RowsProps, _: Scope<NoEvent>) -> impl IntoElement {
let items = signal(vec![1, 2]);
let late = signal(false);
REGION_ITEMS.with(|i| i.set(Some(items)));
LATE.with(|l| l.set(Some(late)));
view().child(each(
items,
|n| *n,
move |item, index| {
dynamic(move || {
let n = item.get();
(n != 2 || late.get()).then(|| text(format!("{n}@{}", index.get())))
})
},
))
}
}
#[test]
fn each_keeps_rows_whose_root_is_a_region() {
let mut c = core();
c.mount_root(&Root::new::<RegionRows>(|| RowsProps {}));
let batch = c.commit().unwrap();
let list = root_host(&batch);
assert_eq!(order(&c, list), ["1@0"]);
let items = REGION_ITEMS.with(Cell::get).unwrap();
let late = LATE.with(Cell::get).unwrap();
// Row 1 stays and its region runs again (its index moved); row 2
// stays, still empty.
{
let _entered = c.components.runtime.enter();
items.set(vec![3, 1, 2]);
}
c.commit();
assert_eq!(order(&c, list), ["3@0", "1@1"]);
// Row 2's region, kept empty, shows its row now.
{
let _entered = c.components.runtime.enter();
late.set(true);
}
c.commit();
assert_eq!(order(&c, list), ["3@0", "1@1", "2@2"]);
// Rows kept as they are, a new one after them.
{
let _entered = c.components.runtime.enter();
items.set(vec![3, 1, 2, 4]);
}
c.commit();
assert_eq!(order(&c, list), ["3@0", "1@1", "2@2", "4@3"]);
}
thread_local! {
static GROUP: Cell<Option<Signal<Vec<u32>>>> = const { Cell::new(None) };
static OTHERS: Cell<Option<Signal<Vec<u32>>>> = const { Cell::new(None) };
/// How often the core asked the order watch for its elements.
static LOOKS: Cell<u32> = const { Cell::new(0) };
static HEARD: std::cell::RefCell<Vec<Vec<usize>>> =
const { std::cell::RefCell::new(Vec::new()) };
}
/// A group of three keyed rows whose order a watch follows, beside
/// three keyed rows of no group.
#[component]
fn WatchedRows() -> impl IntoElement {
let refs: Rc<Vec<crate::element::ElementRef>> =
Rc::new((0..3).map(|_| element_ref()).collect());
let group = signal(vec![1u32, 2, 3]);
let others = signal(vec![1u32, 2, 3]);
GROUP.with(|g| g.set(Some(group)));
OTHERS.with(|o| o.set(Some(others)));
let listed = refs.clone();
let _ = crate::element::watch_order(
move || {
LOOKS.with(|l| l.set(l.get() + 1));
listed.to_vec()
},
|order| HEARD.with(|h| h.borrow_mut().push(order.to_vec())),
);
view()
.child(view().child(each(
group,
|n| *n,
move |item, _| view().element_ref(&refs[item.get_untracked() as usize - 1]),
)))
.child(view().child(each(
others,
|n| *n,
|item, _| text(move || item.get().to_string()),
)))
}
#[test]
fn an_order_watch_looks_again_only_at_moves_among_its_elements() {
let mut c = core();
c.mount_root(&Root::new::<WatchedRows>(|| ()));
c.commit().unwrap();
let looks = LOOKS.with(Cell::get);
assert!(looks >= 1, "looked at as it is made");
assert!(HEARD.with(|h| h.borrow().is_empty()), "in order already");
let (group, others) = (
GROUP.with(Cell::get).unwrap(),
OTHERS.with(Cell::get).unwrap(),
);
// Rows of no group reordered: the watch is not asked.
{
let _entered = c.components.runtime.enter();
others.set(vec![3, 1, 2]);
}
c.commit().unwrap();
assert_eq!(LOOKS.with(Cell::get), looks, "a move outside the group");
assert!(HEARD.with(|h| h.borrow().is_empty()));
// The group's rows reordered: the handler hears the tree's order.
{
let _entered = c.components.runtime.enter();
group.set(vec![3, 1, 2]);
}
c.commit().unwrap();
assert_eq!(LOOKS.with(Cell::get), looks + 1, "a move inside the group");
assert_eq!(HEARD.with(|h| h.borrow().clone()), [vec![2, 0, 1]]);
}
thread_local! {
static ACTIVE_ROW: Cell<Option<Signal<Option<usize>>>> = const { Cell::new(None) };
static ROWS: Cell<Option<Signal<Vec<u32>>>> = const { Cell::new(None) };
}
/// A field naming the row of a list that is active, by the rows'
/// refs, the rows rendered after it.
#[component]
fn ActiveRow() -> impl IntoElement {
let refs: Rc<Vec<crate::element::ElementRef>> =
Rc::new((0..3).map(|_| element_ref()).collect());
let list = element_ref();
let active = signal(Some(0usize));
let rows = signal(vec![0u32, 1, 2]);
ACTIVE_ROW.with(|a| a.set(Some(active)));
ROWS.with(|r| r.set(Some(rows)));
let named = refs.clone();
view()
.child(
view()
.label("field")
.accessibility_active_descendant(move || active.get().map(|i| named[i]))
.accessibility_controls(Some(list)),
)
.child(view().label("list").element_ref(&list).child(each(
rows,
|n| *n,
move |item, _| {
let n = item.get_untracked();
view()
.label(format!("row{n}"))
.element_ref(&refs[n as usize])
},
)))
}
/// The ids of the views by their labels, as `batch` gives them.
fn ids_by_label(batch: &MountBatch) -> std::collections::HashMap<String, NodeId> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ViewProps { id, props } => {
Some((props.accessibility.label.as_deref()?.to_owned(), *id))
}
_ => None,
})
.collect()
}
#[test]
fn rust_refs_name_active_descendants() {
let mut c = core();
c.mount_root(&Root::new::<ActiveRow>(|| ()));
let batch = c.commit().unwrap();
let ids = ids_by_label(&batch);
let field = ids["field"];
assert_eq!(
super::relations_in(&batch, field),
Some((Some(ids["row0"]), Some(ids["list"]))),
"rows rendered after the field are named in the same batch"
);
let (active, rows) = (
ACTIVE_ROW.with(Cell::get).unwrap(),
ROWS.with(Cell::get).unwrap(),
);
{
let _entered = c.components.runtime.enter();
active.set(Some(2));
}
let batch = c.commit().unwrap();
assert_eq!(
super::relations_in(&batch, field),
Some((Some(ids["row2"]), Some(ids["list"])))
);
// The row named goes: the field names none, with no change of its
// own.
{
let _entered = c.components.runtime.enter();
rows.set(vec![0, 1]);
}
let batch = c.commit().unwrap();
assert_eq!(
super::relations_in(&batch, field),
Some((None, Some(ids["list"])))
);
{
let _entered = c.components.runtime.enter();
active.set(None);
}
assert_eq!(
c.commit().and_then(|b| super::relations_in(&b, field)),
None
);
}
/// Made with `#[component]`: reads the appearance and a timer.
#[component]
fn Clock(_props: (), cx: Scope<NoEvent>) -> impl IntoElement {
let ticks = signal(0);
set_timeout(std::time::Duration::ZERO, move || ticks.set(1));
let _ = cx.insets();
view().child(text(move || {
format!(
"{} {} {}",
if dark() { "dark" } else { "light" },
ticks.get(),
tokens().number("radius").unwrap()
)
}))
}
#[test]
fn a_function_component_reads_the_environment_and_its_timers_run() {
let mut c = core();
c.mount_root(&Root::new::<Clock>(|| ()));
let batch = c.commit().unwrap();
let shown = texts(&batch);
assert!(shown[0].starts_with("light 0 "), "{shown:?}");
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
dark: true,
..Default::default()
});
let batch = c.commit().unwrap();
assert!(
texts(&batch)[0].starts_with("dark 0 "),
"{:?}",
texts(&batch)
);
}
thread_local! {
static SIZE_CLASS_RUNS: Cell<u32> = const { Cell::new(0) };
}
#[component]
fn SizeClasses() -> impl IntoElement {
effect(move || {
horizontal_size_class();
SIZE_CLASS_RUNS.with(|n| n.set(n.get() + 1));
});
text(move || format!("{:?} {:?}", horizontal_size_class(), vertical_size_class()))
}
#[test]
fn size_classes_follow_each_axis_and_native_traits_without_redundant_notifications() {
SIZE_CLASS_RUNS.with(|n| n.set(0));
let mut c = core();
let mut environment = crate::element::Environment {
window: crate::geometry::size_pt(390.0, 844.0),
..Default::default()
};
c.set_environment(environment);
c.mount_root(&Root::new::<SizeClasses>(|| ()));
assert_eq!(texts(&c.commit().unwrap()), ["Compact Regular"]);
environment.window.width = px(599.0);
c.set_environment(environment);
c.commit();
assert_eq!(SIZE_CLASS_RUNS.with(Cell::get), 1);
environment.window = crate::geometry::size_pt(600.0, 599.0);
c.set_environment(environment);
assert_eq!(texts(&c.commit().unwrap()), ["Regular Compact"]);
assert_eq!(SIZE_CLASS_RUNS.with(Cell::get), 2);
// UIKit's classes win even when the size would classify differently.
environment.horizontal_size_class = Some(SizeClass::Compact);
environment.vertical_size_class = Some(SizeClass::Regular);
c.set_environment(environment);
assert_eq!(texts(&c.commit().unwrap()), ["Compact Regular"]);
environment.window = crate::geometry::size_pt(900.0, 900.0);
c.set_environment(environment);
c.commit();
assert_eq!(SIZE_CLASS_RUNS.with(Cell::get), 3);
environment.horizontal_size_class = None;
c.set_environment(environment);
assert_eq!(texts(&c.commit().unwrap()), ["Regular Regular"]);
}
thread_local! {
static WAKE_RUNS: Cell<u32> = const { Cell::new(0) };
}
/// Shows how many times the system woke; its effect counts its runs.
#[component]
fn Waker() -> impl IntoElement {
effect(move || {
wake_count();
WAKE_RUNS.with(|n| n.set(n.get() + 1));
});
text(move || format!("woke {}", wake_count()))
}
#[test]
fn an_effect_reading_the_wake_count_runs_again_on_each_wake_only() {
WAKE_RUNS.with(|n| n.set(0));
let mut c = core();
c.mount_root(&Root::new::<Waker>(|| ()));
assert_eq!(texts(&c.commit().unwrap()), ["woke 0"]);
assert_eq!(WAKE_RUNS.with(Cell::get), 1);
// Another part of the environment changes: the effect stays.
c.set_environment(crate::element::Environment {
dark: true,
..Default::default()
});
c.commit();
assert_eq!(WAKE_RUNS.with(Cell::get), 1);
c.set_environment(crate::element::Environment {
dark: true,
wake_count: 1,
..Default::default()
});
assert_eq!(texts(&c.commit().unwrap()), ["woke 1"]);
assert_eq!(WAKE_RUNS.with(Cell::get), 2);
}
thread_local! {
static RESERVED_RUNS: Cell<u32> = const { Cell::new(0) };
}
/// Shows the regions the device reserves; its effect counts its runs.
#[component]
fn Reserved() -> impl IntoElement {
effect(move || {
reserved_regions();
RESERVED_RUNS.with(|n| n.set(n.get() + 1));
});
text(move || {
let regions = reserved_regions();
let shown: Vec<String> = regions
.iter()
.map(|r| format!("{} {}", r.kind.name(), r.bounds.right().0))
.collect();
format!("reserved [{}]", shown.join(", "))
})
}
#[test]
fn the_reserved_regions_reach_components_and_notify_only_when_they_change() {
use crate::platform::{ReservedRegion, ReservedRegionKind, ReservedRegions};
RESERVED_RUNS.with(|n| n.set(0));
let mut c = core();
c.mount_root(&Root::new::<Reserved>(|| ()));
assert_eq!(texts(&c.commit().unwrap()), ["reserved []"]);
// Another part of the environment changes: the effect stays.
let mut environment = crate::element::Environment {
dark: true,
..Default::default()
};
c.set_environment(environment);
c.commit();
assert_eq!(RESERVED_RUNS.with(Cell::get), 1);
// A partly folded display: its fold down the middle.
let fold = ReservedRegion::new(
ReservedRegionKind::Division,
crate::geometry::Bounds::new(
crate::geometry::point(px(460.0), px(0.0)),
crate::geometry::size(px(31.0), px(669.0)),
),
);
environment.reserved_regions = ReservedRegions::new([fold]);
c.set_environment(environment);
assert_eq!(texts(&c.commit().unwrap()), ["reserved [division 491]"]);
assert_eq!(RESERVED_RUNS.with(Cell::get), 2);
// Fully open again.
environment.reserved_regions = ReservedRegions::NONE;
c.set_environment(environment);
assert_eq!(texts(&c.commit().unwrap()), ["reserved []"]);
assert_eq!(RESERVED_RUNS.with(Cell::get), 3);
}
#[test]
fn reserved_regions_keep_the_first_eight() {
use crate::platform::{ReservedRegion, ReservedRegions};
let regions = ReservedRegions::new((0..10).map(|i| ReservedRegion {
bounds: crate::geometry::Bounds::new(
crate::geometry::point(px(i as f32), px(0.0)),
crate::geometry::size(px(1.0), px(1.0)),
),
..Default::default()
}));
assert_eq!(regions.len(), ReservedRegions::CAPACITY);
assert_eq!(regions.as_slice()[7].bounds.origin.x, px(7.0));
assert!(ReservedRegions::default().is_empty());
}
thread_local! {
static NETWORK_RUNS: Cell<u32> = const { Cell::new(0) };
}
/// Shows how the device reaches the network; its effect counts its runs.
#[component]
fn NetworkLabel() -> impl IntoElement {
effect(move || {
network();
NETWORK_RUNS.with(|n| n.set(n.get() + 1));
});
text(move || {
let n = network();
format!(
"{} {} expensive={} constrained={} cellular={}",
if n.online() { "online" } else { "offline" },
n.kind.name(),
n.expensive,
n.constrained,
n.cellular_data.name()
)
})
}
#[test]
fn an_effect_reading_the_network_runs_again_when_the_route_changes_only() {
use crate::platform::{CellularData, Network, NetworkKind};
NETWORK_RUNS.with(|n| n.set(0));
let mut c = core();
c.mount_root(&Root::new::<NetworkLabel>(|| ()));
// Before the platform says: unknown, which counts as online.
assert_eq!(
texts(&c.commit().unwrap()),
["online unknown expensive=false constrained=false cellular=unknown"]
);
assert_eq!(NETWORK_RUNS.with(Cell::get), 1);
// Another part of the environment changes: the effect stays.
c.set_environment(crate::element::Environment {
dark: true,
..Default::default()
});
c.commit();
assert_eq!(NETWORK_RUNS.with(Cell::get), 1);
let offline = crate::element::Environment {
dark: true,
network: Network::new(NetworkKind::None).cellular_data(CellularData::Unknown),
..Default::default()
};
c.set_environment(offline);
assert_eq!(
texts(&c.commit().unwrap()),
["offline none expensive=false constrained=false cellular=unknown"]
);
assert_eq!(NETWORK_RUNS.with(Cell::get), 2);
// The same route reported again changes nothing.
c.set_environment(offline);
c.commit();
assert_eq!(NETWORK_RUNS.with(Cell::get), 2);
// The user allowed wireless data, and the phone joined cellular in
// Low Data Mode.
c.set_environment(crate::element::Environment {
dark: true,
network: Network::new(NetworkKind::Cellular)
.expensive(true)
.constrained(true)
.cellular_data(CellularData::NotRestricted),
..Default::default()
});
assert_eq!(
texts(&c.commit().unwrap()),
["online cellular expensive=true constrained=true cellular=notRestricted"]
);
assert_eq!(NETWORK_RUNS.with(Cell::get), 3);
}
thread_local! {
static INTROS: Cell<u32> = const { Cell::new(0) };
}
#[derive(Clone, PartialEq, Props)]
struct IntroProps {
label: SharedString,
}
/// Counts its views: what a component does as it is made (an entrance)
/// happens each time.
#[component]
fn Intro(props: IntroProps) -> impl IntoElement {
INTROS.with(|n| n.set(n.get() + 1));
text(props.label)
}
/// Shows an `Intro` for the tab chosen; a press switches tabs.
#[component]
fn Tabs() -> impl IntoElement {
let first = signal(true);
view()
.on_press(move |_: &()| first.update(|f| *f = !*f))
.child(dynamic(move || {
intro().label(if first.get() { "one" } else { "two" })
}))
}
#[test]
fn a_component_a_region_makes_again_runs_again() {
INTROS.with(|n| n.set(0));
let mut c = core();
c.mount_root(&Root::new::<Tabs>(|| ()));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["one"]);
let host = root_host(&batch);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["two"]);
assert_eq!(INTROS.with(Cell::get), 2);
}
/// Shows "late" 10 ms after it is made.
#[component]
fn Later() -> impl IntoElement {
let shown = signal("soon");
set_timeout(std::time::Duration::from_millis(10), move || {
shown.set("late")
});
text(move || shown.get())
}
#[test]
fn the_core_keeps_its_tasks_timers() {
// No tokio runtime: the core fires its tasks' timers itself, and
// tells the engine when to wake for the next.
let mut c = core();
c.mount_root(&Root::new::<Later>(|| ()));
assert_eq!(texts(&c.commit().unwrap()), ["soon"]);
c.run_component_tasks();
let due = c.next_task_timer().expect("a timer waits");
assert!(due > std::time::Instant::now());
std::thread::sleep(due.saturating_duration_since(std::time::Instant::now()));
c.run_component_tasks();
assert_eq!(texts(&c.commit().unwrap()), ["late"]);
assert_eq!(c.next_task_timer(), None);
}
/// A timeout days away, cleared by a press.
#[component]
fn Reminder() -> impl IntoElement {
let pending = stored(Some(set_timeout(
std::time::Duration::from_secs(3 * 24 * 60 * 60),
|| {},
)));
view().size_10().on_press(move |_: &()| {
if let Some(timeout) = pending.with(Option::take) {
timeout.cancel();
}
})
}
#[test]
fn a_cleared_timeout_leaves_the_cores_timers() {
// The engine would otherwise wake for it days later, and an app that
// keeps setting and clearing such timeouts would pile them up.
let mut c = core();
c.mount_root(&Root::new::<Reminder>(|| ()));
let host = root_host(&c.commit().unwrap());
c.run_component_tasks();
assert!(c.next_task_timer().is_some());
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
c.run_component_tasks();
assert_eq!(c.next_task_timer(), None);
}
/// A waker that counts its wakes.
#[derive(Default)]
struct Probe(std::sync::atomic::AtomicU32);
impl Probe {
fn wakes(&self) -> u32 {
self.0.load(std::sync::atomic::Ordering::Relaxed)
}
}
impl std::task::Wake for Probe {
fn wake(self: std::sync::Arc<Self>) {
self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
}
#[test]
fn a_dropped_delay_lets_go_of_its_waker() {
use std::{future::Future, sync::Arc, task::Context};
let c = core();
let _entered = c.components.runtime.enter();
let first = Arc::new(Probe::default());
let second = Arc::new(Probe::default());
let mut delay = Box::pin(timer(std::time::Duration::from_secs(3 * 24 * 60 * 60)));
let waker = std::task::Waker::from(first.clone());
assert!(
delay
.as_mut()
.poll(&mut Context::from_waker(&waker))
.is_pending()
);
drop(waker);
let due = c.next_task_timer().expect("the delay waits");
assert_eq!(Arc::strong_count(&first), 2);
// Polled again by another waker (a `select`): that one is woken.
let waker = std::task::Waker::from(second.clone());
assert!(
delay
.as_mut()
.poll(&mut Context::from_waker(&waker))
.is_pending()
);
drop(waker);
assert_eq!(Arc::strong_count(&first), 1);
assert_eq!(Arc::strong_count(&second), 2);
assert_eq!(c.next_task_timer(), Some(due));
drop(delay);
assert_eq!(c.next_task_timer(), None);
assert_eq!(Arc::strong_count(&second), 1);
// Nothing is left to wake when its time comes.
c.components.executor.fire_timers(due);
assert_eq!((first.wakes(), second.wakes()), (0, 0));
// Still awaited in `background` too.
fn send<T: Send>() {}
send::<crate::element::Delay>();
}
#[test]
fn a_delay_wakes_the_last_waker_it_was_polled_with() {
use std::{future::Future, sync::Arc, task::Context};
let c = core();
let _entered = c.components.runtime.enter();
let first = Arc::new(Probe::default());
let second = Arc::new(Probe::default());
let mut delay = Box::pin(timer(std::time::Duration::from_secs(60)));
for probe in [&first, &second] {
let waker = std::task::Waker::from(probe.clone());
assert!(
delay
.as_mut()
.poll(&mut Context::from_waker(&waker))
.is_pending()
);
}
let due = c.next_task_timer().expect("the delay waits");
c.components.executor.fire_timers(due);
assert_eq!((first.wakes(), second.wakes()), (0, 1));
assert_eq!(c.next_task_timer(), None);
}
/// A box bordered while a signal holds.
#[component]
fn Framed() -> impl IntoElement {
let on = signal(false);
view()
.size_10()
.on_press(move |_: &()| on.set(true))
.style_when(on, |s| s.border_1().border_color(rgb(0xff0000)))
}
#[test]
fn a_bound_style_layer_draws_its_border() {
let mut c = core();
c.mount_root(&Root::new::<Framed>(|| ()));
let host = root_host(&c.commit().unwrap());
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let style = batch.items.iter().find_map(|i| match i {
MountItem::ViewStyle { style, .. } if style.borders.widths.top > Points::ZERO => {
Some(style.clone())
}
_ => None,
});
assert!(style.is_some(), "{:#?}", batch.items);
}
#[component]
fn OptionalGlassTint() -> impl IntoElement {
let step = stored(0_u8);
let tint = signal(Some(AdaptiveColor::rgb(0xff0000, 0x00ff00)));
view()
.size_10()
.glass_effect(crate::GlassEffect::Regular)
.backdrop_blur(px(12.0))
.glass_tint_color(rgb(0xaabbcc))
.glass_tint_color(tint)
.on_press(move |_: &()| {
step.with(|value| *value += 1);
tint.set(match step.get() {
1 => None,
2 => Some(AdaptiveColor::TRANSPARENT),
_ => Some(AdaptiveColor::rgb(0x0000ff, 0xffff00)),
});
})
}
#[test]
fn an_optional_tint_restores_native_default_without_losing_glass() {
for dark in [false, true] {
let mut c = core();
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark,
..Default::default()
});
c.mount_root(&Root::new::<OptionalGlassTint>(|| ()));
let mut batch = c.commit().unwrap();
let host = root_host(&batch);
let expected = [
Some(if dark {
Color(0x00ff00ff)
} else {
Color(0xff0000ff)
}),
None,
Some(Color::TRANSPARENT),
Some(if dark {
Color(0xffff00ff)
} else {
Color(0x0000ffff)
}),
];
for (step, tint) in expected.into_iter().enumerate() {
if step != 0 {
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
batch = c.commit().unwrap();
}
let style = view_style_of(&batch, host).unwrap();
assert_eq!(style.glass_tint_color, tint, "dark={dark}, step={step}");
assert_eq!(style.glass_effect, crate::GlassEffect::Regular);
assert_eq!(
style.effects.as_ref().unwrap().backdrop_filters,
[crate::Filter::Blur(px(12.0))]
);
}
}
}
/// A track whose color moves between two theme colors natively.
#[component]
fn Track() -> impl IntoElement {
let on = animated_value(0.0);
let off_color = AdaptiveColor {
light: rgb(0xeeeeee).into(),
dark: rgb(0x222222).into(),
};
view().size_10().bind_background(&on.interpolate_colors(
&[0.0, 1.0],
&[off_color, AdaptiveColor::from(rgb(0x00ff00))],
))
}
#[test]
fn interpolated_theme_colors_follow_the_appearance() {
let colors = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::Animation(
crate::animation::AnimationOp::CreateInterpolate { output, .. }
| crate::animation::AnimationOp::SetOutput { output, .. },
) => Some(output.clone()),
_ => None,
})
};
let mut c = core();
c.mount_root(&Root::new::<Track>(|| ()));
assert_eq!(
colors(&c.commit().unwrap()),
Some(crate::animation::Output::Colors(vec![
0xeeeeeeff, 0x00ff00ff
]))
);
c.set_environment(crate::element::Environment {
dark: true,
..Default::default()
});
// The same node, the dark colors: no view is made again.
let batch = c.commit().unwrap();
assert_eq!(
colors(&batch),
Some(crate::animation::Output::Colors(vec![
0x222222ff, 0x00ff00ff
]))
);
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::Animation(crate::animation::AnimationOp::CreateInterpolate { .. })
)));
}
/// Three tracks sharing their light colors: two theme colors with
/// other dark ones, and a constant one.
#[component]
fn SharedLight() -> impl IntoElement {
let on = animated_value(0.0);
let green = AdaptiveColor::from(rgb(0x00ff00));
let track = |dark| {
let off = AdaptiveColor {
light: rgb(0x000000).into(),
dark,
};
view()
.size_10()
.bind_background(&on.interpolate_colors(&[0.0, 1.0], &[off, green]))
};
view()
.child(track(rgb(0xffffff).into()))
.child(track(rgb(0x808080).into()))
.child(track(rgb(0x000000).into()))
}
#[test]
fn color_interpolations_sharing_their_light_colors_are_apart() {
let outputs = |batch: &MountBatch| {
let mut outputs: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Animation(
crate::animation::AnimationOp::CreateInterpolate { output, .. }
| crate::animation::AnimationOp::SetOutput { output, .. },
) => Some(output.clone()),
_ => None,
})
.collect();
outputs.sort_by_key(|o| format!("{o:?}"));
outputs
};
let colors = |off: u32| crate::animation::Output::Colors(vec![off, 0x00ff00ff]);
let mut c = core();
c.mount_root(&Root::new::<SharedLight>(|| ()));
assert_eq!(outputs(&c.commit().unwrap()), vec![colors(0x000000ff); 3]);
c.set_environment(crate::element::Environment {
dark: true,
..Default::default()
});
assert_eq!(
outputs(&c.commit().unwrap()),
[colors(0x808080ff), colors(0xffffffff)]
);
}
/// A style bound to a signal.
#[derive(Default)]
struct Lamp;
#[derive(Clone, PartialEq, Props)]
struct LampProps {}
impl Component for Lamp {
type Props = LampProps;
type Event = NoEvent;
fn view(_: LampProps, _: Scope<NoEvent>) -> impl IntoElement {
let on = signal(false);
view()
.on_press(move |_: &()| on.update(|v| *v = !*v))
.w(px(10.0))
.bg(move || {
if on.get() {
rgb(0xff0000)
} else {
rgb(0x0000ff)
}
})
.style_when(on, |s| s.opacity(0.5))
}
}
#[test]
fn bound_styles_change_alone() {
let mut c = core();
c.mount_root(&Root::new::<Lamp>(|| LampProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
let style = view_style_of(&batch, host).unwrap();
assert_eq!(style.background_color, crate::style::Color(0x0000_ffff));
assert_eq!(style.opacity, 1.0);
c.component_event(host, EventKind::Press, &EventPayload::None);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, host).unwrap();
assert_eq!(style.background_color, crate::style::Color(0xff00_00ff));
assert_eq!(style.opacity, 0.5);
let _ = Rc::new(());
}
/// Its own rows in a list, from a signal: a press on a row removes it,
/// one on "add" appends one. A row's text says when it is the last.
#[derive(Default)]
struct Mailbox;
#[derive(Clone, PartialEq, Props)]
struct MailboxProps {
#[prop(default)]
rows: crate::element::Prop<u32>,
}
impl Component for Mailbox {
type Props = MailboxProps;
type Event = NoEvent;
fn view(props: MailboxProps, _: Scope<NoEvent>) -> impl IntoElement {
let rows = signal(
(0..props.rows.get_untracked())
.map(|i| format!("mail {i}"))
.collect::<Vec<_>>(),
);
view()
.flex_1()
.child(view().h(px(20.0)).label("add").on_press(move |_: &()| {
rows.update(|r| {
let n = r.len();
r.push(format!("new {n}"));
});
}))
.child(
virtual_list(
move || rows.with(Vec::len),
move |at| {
view()
.h(px(40.0))
.on_press(move |_: &()| {
rows.update(|r| {
r.remove(at.index());
});
})
// Indexing: a row's bindings never read
// past the rows.
.child(text(move || {
let row = rows.with(|r| r[at.index()].clone());
let last = if at.is_last() { " (last)" } else { "" };
format!("{row}{last}")
}))
},
)
.estimated_item_size(px(40.0))
.keys(move || rows.get())
.flex_1(),
)
}
}
fn mailbox(rows: u32) -> (Core<FakeEngine>, MountBatch) {
let mut c = core();
c.mount_root(&Root::new::<Mailbox>(move || MailboxProps {
rows: rows.into(),
}));
let batch = c.commit().unwrap();
(c, batch)
}
fn pressable(batch: &MountBatch) -> Vec<NodeId> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.collect()
}
fn creates(batch: &MountBatch) -> usize {
batch
.items
.iter()
.filter(|i| matches!(i, MountItem::Create { .. }))
.count()
}
#[test]
fn a_views_list_splices_and_its_cells_keep_their_rows() {
let (mut c, batch) = mailbox(100);
let shown = texts(&batch);
assert!(shown.contains(&"mail 0".to_owned()), "{shown:?}");
assert!(shown.len() < 100, "virtualized: {}", shown.len());
// A press on row 0 removes it: the list splices, the other cells
// keep their content (their rows did not change: nothing to send)
// and the freed cell shows the row coming into view.
let row0 = pressable(&batch)[1];
assert!(c.component_event(row0, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), [format!("mail {}", shown.len())]);
assert_eq!(creates(&batch), 0, "{:?}", batch.items);
}
#[test]
fn a_views_list_grows_in_place() {
let (mut c, batch) = mailbox(3);
let mut shown = texts(&batch);
shown.sort();
assert_eq!(shown, ["mail 0", "mail 1", "mail 2 (last)"]);
let add = pressable(&batch)[0];
assert!(c.component_event(add, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
// The old last row's text changes; a cell comes for the new one.
let mut shown = texts(&batch);
shown.sort();
assert_eq!(shown, ["mail 2", "new 3 (last)"]);
}
#[derive(Clone, PartialEq, Props)]
struct ReplacedListProps {
#[prop(default)]
refresh_replacement: crate::element::Prop<bool>,
}
#[component]
fn ReplacedList(props: ReplacedListProps) -> impl IntoElement {
let refresh_replacement = props.refresh_replacement.get_untracked();
let rows = signal(vec![(0, "old")]);
let replacement = signal(false);
view()
.flex_1()
.child(view().h(px(20.0)).on_press(move || {
// Queue an update from the old binding before replacing its scope.
rows.set(vec![(0, "new")]);
replacement.set(true);
}))
.child(dynamic(move || {
let replaced = replacement.get();
let source = if replaced { "second" } else { "first" };
let list = virtual_list(
move || rows.with(Vec::len),
move |at| {
text(move || rows.with(|r| format!("{source}: {}", r[at.index()].1)))
.h(px(40.0))
},
)
.keys(move || rows.with(|r| r.iter().map(|row| row.0).collect::<Vec<_>>()))
.flex_1();
let refresh = (replaced && refresh_replacement).then(|| {
// Runs after the new list binds, before its reused cells render.
dynamic(move || rows.set(vec![(0, "latest")]))
});
let mut children = vec![list.into_element()];
children.extend(refresh);
children
}))
}
#[test]
fn replacing_a_lists_row_scope_while_its_rows_update_keeps_the_visible_row() {
let mut c = core();
c.mount_root(&Root::of::<ReplacedList>());
let initial = c.commit().unwrap();
assert_eq!(texts(&initial), ["first: old"]);
let replace = pressable(&initial)[0];
assert!(c.component_event(replace, EventKind::Press, &EventPayload::None));
let updated = c.commit().unwrap();
assert_eq!(texts(&updated), ["second: new"]);
}
#[test]
fn a_replacement_lists_own_patch_keeps_the_visible_row() {
let mut c = core();
c.mount_root(&Root::new::<ReplacedList>(|| ReplacedListProps {
refresh_replacement: true.into(),
}));
let initial = c.commit().unwrap();
assert_eq!(texts(&initial), ["first: old"]);
let replace = pressable(&initial)[0];
assert!(c.component_event(replace, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["second: latest"]);
}
#[component]
fn ReplacedListLayout() -> impl IntoElement {
let padding = signal(0.0);
let replacement = signal(false);
view()
.flex_1()
.child(view().on_press(move || {
padding.set(100.0);
replacement.set(true);
}))
.child(view().on_press(move || padding.set(100.0)))
.child(dynamic(move || {
let replaced = replacement.get();
let list = virtual_list(1, move |_| {
text(if replaced { "new" } else { "old" }).h(px(40.0))
})
.flex_1();
if replaced {
list.content_padding_top(px(0.0))
} else {
list.content_padding_top(move || px(padding.get()))
}
}))
}
#[test]
fn a_replacement_list_uses_its_own_layout() {
for commit_old_padding in [false, true] {
let mut c = core();
c.mount_root(&Root::of::<ReplacedListLayout>());
let initial = c.commit().unwrap();
let buttons = pressable(&initial);
if commit_old_padding {
assert!(c.component_event(buttons[1], EventKind::Press, &EventPayload::None));
c.commit().unwrap();
}
assert!(c.component_event(buttons[0], EventKind::Press, &EventPayload::None));
let updated = c.commit().unwrap();
let row = text_node(&updated, "new");
let cell = native_parent(&c, row).unwrap();
let key = c.key(cell).unwrap();
assert_eq!(c.nodes[key as usize].frame.origin.y, px(0.0));
}
}
#[test]
fn a_views_list_cells_show_other_rows_through_their_bindings() {
let (mut c, batch) = mailbox(1000);
let list = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create {
id,
kind: crate::ViewKind::Scroll,
} => Some(*id),
_ => None,
})
.expect("a list");
c.set_scroll_offset(list, point(px(0.0), px(10_000.0)), u32::MAX);
c.commit().unwrap();
// Scrolling on: the cells are reused and their content stays; only
// the texts change.
c.set_scroll_offset(list, point(px(0.0), px(20_000.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(creates(&batch), 0, "{:?}", batch.items);
let shown = texts(&batch);
assert!(shown.contains(&"mail 500".to_owned()), "{shown:?}");
}
#[test]
fn a_views_list_drops_the_rows_that_went_past_its_end() {
let (mut c, batch) = mailbox(3);
// The row of the last text.
let text = text_node(&batch, "mail 2 (last)");
let last = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == text => Some(*parent),
_ => None,
})
.expect("the last row");
assert!(c.component_event(last, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["mail 1 (last)"]);
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { .. })),
"the gone row's nodes: {:?}",
batch.items
);
}
/// A list whose top padding is a signal; a press on it flips it.
#[derive(Default)]
struct Padded;
#[derive(Clone, PartialEq, Props)]
struct PaddedProps {}
impl Component for Padded {
type Props = PaddedProps;
type Event = NoEvent;
fn view(_: PaddedProps, _: Scope<NoEvent>) -> impl IntoElement {
let padded = signal(false);
view()
.flex_1()
.on_press(move |_: &()| padded.update(|p| *p = !*p))
.child(
virtual_list(3, |at| text(format!("row {}", at.index())).h(px(40.0)))
.content_padding_top(move || if padded.get() { 10.0_f32 } else { 0.0 })
.flex_1(),
)
}
}
#[test]
fn a_views_list_layout_is_a_binding() {
let mut c = core();
c.mount_root(&Root::new::<Padded>(|| PaddedProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
// The rows move down; nothing is made again.
assert_eq!(creates(&batch), 0, "{:?}", batch.items);
let moved: Vec<f32> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Frame { frame, .. } => Some(frame.origin.y.0),
_ => None,
})
.collect();
assert!(moved.contains(&10.0), "{:?}", batch.items);
}
thread_local! {
/// How many times `Fresh` was made on this thread.
static FRESH: Cell<u32> = const { Cell::new(0) };
}
/// Content with a state of its own: the how-manieth it was made.
#[derive(Default)]
struct Fresh;
#[derive(Clone, PartialEq, Props)]
struct FreshProps {}
impl Component for Fresh {
type Props = FreshProps;
type Event = NoEvent;
fn view(_: FreshProps, _: Scope<NoEvent>) -> impl IntoElement {
let n = FRESH.with(|f| {
f.set(f.get() + 1);
f.get()
});
view().child(text(format!("fresh {n}")))
}
}
/// Places its (lazy) children while open.
#[derive(Default)]
struct Pocket;
#[derive(Clone, PartialEq, Props)]
struct PocketProps {
#[prop(default)]
open: crate::element::Prop<bool>,
#[prop(lazy)]
children: Children,
}
impl Component for Pocket {
type Props = PocketProps;
type Event = NoEvent;
fn view(props: PocketProps, _: Scope<NoEvent>) -> impl IntoElement {
let children = props.children;
view().child(when(props.open, move || view().p_2().child(children)))
}
}
/// Places its children.
#[derive(Default)]
struct Holder;
#[derive(Clone, PartialEq, Props)]
struct HolderProps {
children: Children,
}
impl Component for Holder {
type Props = HolderProps;
type Event = NoEvent;
fn view(props: HolderProps, _: Scope<NoEvent>) -> impl IntoElement {
view().child(props.children)
}
}
/// A label (a component whose root is a text).
#[component]
fn Label() -> impl IntoElement {
text("label")
}
/// Shows a label (a component), a text and a holder of a text while
/// open, as a holder's content; a press closes.
#[component]
fn Shutter() -> impl IntoElement {
let open = signal(true);
view().on_press(move || open.set(false)).child(
Holder::element(HolderProps {
children: Children::default(),
})
.child(when(open, || {
vec![
label().into_element(),
text("plain").into_element(),
Holder::element(HolderProps {
children: Children::default(),
})
.child(text("inside"))
.into_element(),
]
})),
)
}
#[test]
fn content_leaving_a_nested_component_is_only_deleted() {
let mut c = core();
c.mount_root(&Root::new::<Shutter>(|| ()));
let batch = c.commit().unwrap();
let host = root_host(&batch);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
// Deleting a view detaches it natively: no `Remove` before.
let count = |f: fn(&MountItem) -> bool| batch.items.iter().filter(|i| f(i)).count();
let removes = count(|i| matches!(i, MountItem::Remove { .. }));
let deletes = count(|i| matches!(i, MountItem::Delete { .. }));
assert_eq!((removes, deletes), (0, 4), "{:?}", batch.items);
let holder = c
.components
.instances
.values()
.find(|i| !i.js_children.is_empty());
assert!(holder.is_none(), "no holder keeps what left it");
}
/// Wraps each of its children in a view of its own, placing them from
/// a signal of them.
#[derive(Default)]
struct Wraps;
#[derive(Clone, PartialEq, Props)]
struct WrapsProps {
children: Children,
}
impl Component for Wraps {
type Props = WrapsProps;
type Event = NoEvent;
fn view(props: WrapsProps, _: Scope<NoEvent>) -> impl IntoElement {
view().children_each(props.children, |child, _| view().p_1().child(child))
}
}
/// A list whose rows are wrapping components, each given a text while
/// `shown`; a press hides the texts, then replaces the row.
#[component]
fn WrappedRows() -> impl IntoElement {
let items = signal(vec![1]);
let shown = signal(true);
view()
.on_press(move || {
shown.set(false);
items.set(vec![2]);
})
.child(each(
items,
|n| *n,
move |item, _| {
Wraps::element(WrapsProps {
children: Children::default(),
})
.child(when(shown, move || text(format!("row {}", item.get()))))
},
))
}
#[test]
fn content_leaves_a_nested_component_whose_row_went_in_the_same_commit() {
let mut c = core();
c.mount_root(&Root::new::<WrappedRows>(|| ()));
let batch = c.commit().unwrap();
let host = root_host(&batch);
let row = text_node(&batch, "row 1");
// The text's region queues its patch first; the row then goes, and
// the wrapping component's view with it, before the commit applies
// either.
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(c.key(row).is_err(), "the text went");
assert!(texts(&batch).is_empty(), "{:?}", batch.items);
let wrapping = c
.components
.instances
.values()
.find(|i| !i.js_children.is_empty());
assert!(wrapping.is_none(), "no component keeps what left it");
}
/// JSX text straight in a component's children (`<Button>Open</Button>`):
/// JS sends a raw text run, kept without a node until a use needs one.
/// The component places it, so it gets its node.
#[test]
fn a_raw_text_child_of_a_component_is_placed() {
let mut c = core();
let mut registry = crate::element::Registry::new();
registry.register::<Holder>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Holder>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::CreateText {
id: 4,
text: "Open".into(),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
// Placed where the view places its children (its node made: no
// invalid op), a text outside a `Text` that shows nothing, as in a
// `View`.
let _ = c.commit();
assert_eq!(c.components.instances[&2].js_children, [4]);
let at = native_parent(&c, 4).expect("placed");
assert_eq!(c.nodes[c.key(at).unwrap() as usize].kind, Kind::View);
// It leaves as any child does.
apply(
&mut c,
vec![Op::Remove {
parent: 2,
child: 4,
}],
);
let _ = c.commit();
assert!(c.components.instances[&2].js_children.is_empty());
}
/// Passes its children on to a holder while shown; a press hides and
/// shows the holder.
#[derive(Default)]
struct Forward;
#[derive(Clone, PartialEq, Props)]
struct ForwardProps {
children: Children,
}
impl Component for Forward {
type Props = ForwardProps;
type Event = NoEvent;
fn view(props: ForwardProps, _: Scope<NoEvent>) -> impl IntoElement {
let shown = signal(true);
let children = props.children;
view()
.on_press(move || shown.update(|s| *s = !*s))
.child(when(shown, move || {
Holder::element(HolderProps {
children: Children::default(),
})
.child(text("first"))
.child(children)
}))
}
}
/// Gives a forward three texts, the middle one in a region; a press
/// toggles it.
#[derive(Default)]
struct Relay;
#[derive(Clone, PartialEq, Props)]
struct RelayProps {}
impl Component for Relay {
type Props = RelayProps;
type Event = NoEvent;
fn view(_: RelayProps, _: Scope<NoEvent>) -> impl IntoElement {
let middle = signal(false);
view().on_press(move || middle.update(|m| *m = !*m)).child(
Forward::element(ForwardProps {
children: Children::default(),
})
.child(text("a"))
.child(when(middle, || text("b")))
.child(text("c")),
)
}
}
/// The ids of the native children of `id`.
fn native_children<M: TextEngine>(c: &Core<M>, id: NodeId) -> Vec<NodeId> {
let key = c.key(id).expect("a node");
c.nodes[key as usize]
.children
.iter()
.map(|&k| c.nodes[k as usize].id)
.collect()
}
#[test]
fn children_passed_on_to_a_nested_component_are_placed_by_it() {
let mut c = core();
c.mount_root(&Root::new::<Relay>(|| RelayProps {}));
let batch = c.commit().unwrap();
let relay = root_host(&batch);
let [first, a, cc] = ["first", "a", "c"].map(|t| text_node(&batch, t));
let holder = native_parent(&c, a).expect("placed");
assert_eq!(native_children(&c, holder), [first, a, cc]);
let forward = native_parent(&c, holder).expect("in the forward");
assert_eq!(native_parent(&c, forward), Some(relay));
// Content joining the forward's children goes in its place there.
assert!(c.component_event(relay, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let b = text_node(&batch, "b");
assert_eq!(native_children(&c, holder), [first, a, b, cc]);
// The holder goes: the children it was passed leave it, kept.
assert!(c.component_event(forward, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
for id in [a, b, cc] {
assert_eq!(native_parent(&c, id), None);
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: r } if *r == id)),
"{id} is removed: {:?}",
batch.items
);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id: d } if *d == id)),
"{id} stays"
);
}
// Shown again: a new holder places them.
assert!(c.component_event(forward, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let holder = native_parent(&c, a).expect("placed again");
let first = text_node(&batch, "first");
assert_eq!(native_children(&c, holder), [first, a, b, cc]);
// Leaving the content, a child leaves the holder.
assert!(c.component_event(relay, EventKind::Press, &EventPayload::None));
c.commit();
assert_eq!(native_children(&c, holder), [first, a, cc]);
}
#[test]
fn content_passed_on_two_deep_leaves_every_level() {
let mut c = core();
c.mount_root(&Root::new::<Relay>(|| RelayProps {}));
let batch = c.commit().unwrap();
let relay = root_host(&batch);
assert!(c.component_event(relay, EventKind::Press, &EventPayload::None));
let b = text_node(&c.commit().unwrap(), "b");
let holding = |c: &Core<FakeEngine>| {
c.components
.instances
.iter()
.filter(|(_, i)| i.js_children.contains(&b))
.count()
};
assert_eq!(holding(&c), 2, "the forward's and the holder's");
assert!(c.component_event(relay, EventKind::Press, &EventPayload::None));
c.commit().unwrap();
assert!(c.key(b).is_err(), "released");
assert_eq!(holding(&c), 0, "no component keeps it");
}
#[test]
fn positional_js_children_a_component_places_are_styled_before_the_commit_reads_them() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Forward>();
c.set_components(registry);
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Forward>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for id in [6, 8, 10] {
ops.extend([
Op::Create { id, tag: Tag::View },
class_op(id, "w-10 h-4 last:fixed"),
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
// Placed by the component as it renders, in the commit: the last
// is `position: fixed` in that same commit.
c.commit();
for id in [6, 8, 10] {
assert_eq!(
c.nodes[c.key(id).unwrap() as usize].fixed_view,
id == 10,
"{id}"
);
}
}
#[test]
fn js_children_through_a_forward() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Forward>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Forward>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
],
);
let batch = c.commit().unwrap();
let first = text_node(&batch, "first");
let holder = native_parent(&c, 6).expect("placed");
assert_eq!(native_children(&c, holder), [first, 6]);
// Hide.
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(native_parent(&c, 6), None, "{:?}", batch.items);
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: 6 })),
"{:?}",
batch.items
);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id: 6 }))
);
// While hidden: JS adds 8, removes 6.
apply(
&mut c,
vec![
Op::Create {
id: 8,
tag: Tag::View,
},
Op::Insert {
parent: 2,
child: 8,
before: None,
},
Op::Remove {
parent: 2,
child: 6,
},
],
);
let batch = c.commit();
assert_eq!(
native_parent(&c, 8),
None,
"hidden: {:?}",
batch.map(|b| b.items)
);
assert_eq!(native_parent(&c, 6), None);
// Show.
assert!(c.component_event(2, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let first = text_node(&batch, "first");
let holder = native_parent(&c, 8).expect("placed again");
assert_eq!(native_children(&c, holder), [first, 8], "{:?}", batch.items);
// JS inserts 6 before 8, then moves 8 before 6.
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 6,
before: Some(8),
}],
);
c.commit();
assert_eq!(native_children(&c, holder), [first, 6, 8]);
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 8,
before: Some(6),
}],
);
c.commit();
assert_eq!(native_children(&c, holder), [first, 8, 6]);
// The host goes; JS's children stay.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
let batch = c.commit().unwrap();
for id in [6, 8] {
assert!(c.key(id).is_ok());
assert_eq!(native_parent(&c, id), None, "{id}: {:?}", batch.items);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id: d } if *d == id))
);
}
assert!(c.components.instances.is_empty());
// JS re-inserts 6 into root: fine.
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 6,
before: None,
}],
);
c.commit();
assert_eq!(native_parent(&c, 6), Some(ROOT_ID));
}
/// Shows whether it has children, and places them while shown; a press
/// hides and shows them.
#[derive(Default)]
struct Shy;
#[derive(Clone, PartialEq, Props)]
struct ShyProps {
children: crate::element::Prop<Children>,
}
impl Component for Shy {
type Props = ShyProps;
type Event = NoEvent;
fn view(props: ShyProps, _: Scope<NoEvent>) -> impl IntoElement {
let shown = signal(true);
let children = props.children;
view()
.on_press(move || shown.update(|s| *s = !*s))
.child(text(move || format!("empty {}", children.get().is_empty())))
.child(when(shown, move || view().child(children.get_untracked())))
}
}
/// Passes its children on to a shy one.
#[component]
fn PassOn(props: HolderProps) -> impl IntoElement {
view().child(
Shy::element(ShyProps {
children: Default::default(),
})
.child(props.children),
)
}
/// Gives a pass-on one text while on; a press turns it off.
#[component]
fn Giver() -> impl IntoElement {
let on = signal(true);
view()
.on_press(move || on.update(|o| *o = !*o))
.child(pass_on().child(when(on, || text("given"))))
}
#[test]
fn a_deep_component_knows_when_its_only_child_left() {
let mut c = core();
c.mount_root(&Root::new::<Giver>(|| ()));
let batch = c.commit().unwrap();
let giver = root_host(&batch);
let shy = native_parent(&c, text_node(&batch, "empty false")).unwrap();
assert!(c.component_event(giver, EventKind::Press, &EventPayload::None));
assert!(texts(&c.commit().unwrap()).contains(&"empty true".to_owned()));
// Hidden and shown again, it places nothing.
for _ in 0..2 {
assert!(c.component_event(shy, EventKind::Press, &EventPayload::None));
let _ = c.commit();
}
let dead = c
.components
.instances
.values()
.flat_map(|i| &i.js_children)
.filter(|&&id| c.key(id).is_err())
.count();
assert_eq!(dead, 0, "no released child");
}
thread_local! {
static PLAQUE_TAPS: Cell<u32> = const { Cell::new(0) };
}
/// A counter as its view's root, dimmed, hearing its taps.
#[derive(Default)]
struct Plaque;
#[derive(Clone, PartialEq, Props)]
struct PlaqueProps {}
impl Component for Plaque {
type Props = PlaqueProps;
type Event = NoEvent;
fn view(_: PlaqueProps, _: Scope<NoEvent>) -> impl IntoElement {
Counter::element(CounterProps {
label: "Plaque".into(),
})
.opacity(0.5)
.on_event(|e: &CounterEvent| {
let CounterEvent::Tap(n) = e;
PLAQUE_TAPS.with(|t| t.set(*n));
})
}
}
/// A plaque as its view's root: two components deep.
#[derive(Default)]
struct Shelf;
#[derive(Clone, PartialEq, Props)]
struct ShelfProps {}
impl Component for Shelf {
type Props = ShelfProps;
type Event = NoEvent;
fn view(_: ShelfProps, _: Scope<NoEvent>) -> impl IntoElement {
Plaque::element(PlaqueProps {}).bg(rgb(0xff0000))
}
}
#[test]
fn a_component_rooted_in_another_shares_its_host() {
let mut c = core();
c.mount_root(&Root::new::<Counter>(|| CounterProps {
label: "Plaque".into(),
}));
let alone = creates(&c.commit().unwrap());
for deep in [false, true] {
let mut c = core();
if deep {
c.mount_root(&Root::new::<Shelf>(|| ShelfProps {}));
} else {
c.mount_root(&Root::new::<Plaque>(|| PlaqueProps {}));
}
let batch = c.commit().unwrap();
// The counter's view makes the host: no view of its own.
assert_eq!(creates(&batch), alone, "{:?}", batch.items);
let host = root_host(&batch);
let style = view_style_of(&batch, host).expect("styled");
assert_eq!(style.opacity, 0.5, "the styles the view gives it");
if deep {
assert_ne!(style.background_color, crate::Color::TRANSPARENT);
}
assert_eq!(texts(&batch), ["Plaque 0", "static"]);
let text = text_node(&batch, "Plaque 0");
assert_eq!(native_parent(&c, text), Some(host));
// Its listener runs on the host, its events reach the view.
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["Plaque 1"]);
assert_eq!(PLAQUE_TAPS.with(Cell::get), 1);
PLAQUE_TAPS.with(|t| t.set(0));
assert!(
batch.items.iter().all(|i| match i {
MountItem::Insert { parent, child, .. } =>
c.key(*parent).is_ok() && c.key(*child).is_ok(),
_ => true,
}),
"only nodes' own ids"
);
}
}
/// A press target with no look: presses, its selection for screen
/// readers, and the app's styles.
#[derive(Default)]
struct Key;
#[derive(Clone, PartialEq, Props)]
struct KeyProps {
#[prop(default)]
selected: crate::element::Prop<bool>,
}
impl Component for Key {
type Props = KeyProps;
type Event = NoEvent;
fn view(props: KeyProps, _: Scope<NoEvent>) -> impl IntoElement {
let selected = props.selected;
view()
.size_10()
.accessibility_state(move || crate::AccessibilityState {
selected: selected.get(),
..crate::AccessibilityState::default()
})
.on_press(|| {})
}
}
/// Two keys in a row, styled per state as an app styles a `Button`.
#[derive(Default)]
struct Keys;
#[derive(Clone, PartialEq, Props)]
struct KeysProps {}
impl Component for Keys {
type Props = KeysProps;
type Event = NoEvent;
fn view(_: KeysProps, _: Scope<NoEvent>) -> impl IntoElement {
let key = |selected: bool| {
Key::element(KeyProps {
selected: selected.into(),
})
.bg(rgb(0x0000ff))
.selected(|s| s.bg(rgb(0x00ff00)))
.hover(|s| s.opacity(0.5))
.active(|s| s.bg(rgb(0xff0000)))
};
view().flex_row().child(key(false)).child(key(true))
}
}
#[test]
fn a_nested_components_state_styles_follow_its_roots_states() {
use crate::tailwind::state::{HOVERED, PRESSED};
let mut c = core();
c.mount_root(&Root::new::<Keys>(|| KeysProps {}));
let batch = c.commit().unwrap();
// The keys' roots report presses and hovers to the core.
let tracked = |id: NodeId| {
batch.items.iter().any(|i| {
matches!(i, MountItem::TrackStates { id: v, states }
if *v == id && states & (PRESSED | HOVERED) == PRESSED | HOVERED)
})
};
let roots: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::TrackStates { id, .. } if tracked(*id) => Some(*id),
_ => None,
})
.collect();
assert_eq!(roots.len(), 2, "{:?}", batch.items);
let is_selected = |id: NodeId| {
batch.items.iter().any(|i| {
matches!(i, MountItem::ViewProps { id: v, props }
if *v == id && props.accessibility.state.selected)
})
};
let (selected, plain) = match is_selected(roots[0]) {
true => (roots[0], roots[1]),
false => (roots[1], roots[0]),
};
let background =
|batch: &MountBatch, id| view_style_of(batch, id).map(|s| s.background_color);
assert_eq!(background(&batch, plain), Some(crate::Color(0x0000ffff)));
assert_eq!(
background(&batch, selected),
Some(crate::Color(0x00ff00ff)),
"selected:"
);
c.set_states(plain, PRESSED | HOVERED);
let batch = c.commit().unwrap();
let style = view_style_of(&batch, plain).expect("restyled");
assert_eq!(style.background_color, crate::Color(0xff0000ff), "active:");
assert_eq!(style.opacity, 0.5, "hover:");
c.set_states(plain, 0);
let batch = c.commit().unwrap();
assert_eq!(background(&batch, plain), Some(crate::Color(0x0000ffff)));
}
/// A key a test names: the id goes on the key's root, as TSX's
/// `testID` on a component does.
#[derive(Default)]
struct NamedKey;
#[derive(Clone, PartialEq, Props)]
struct NamedKeyProps {}
impl Component for NamedKey {
type Props = NamedKeyProps;
type Event = NoEvent;
fn view(_: NamedKeyProps, _: Scope<NoEvent>) -> impl IntoElement {
view()
.flex_row()
.child(
Key::element(KeyProps {
selected: false.into(),
})
.test_id("save"),
)
.child(OwnId::element(OwnIdProps {}).test_id("given"))
}
}
/// A component whose root names itself; each press of it changes its
/// own label (an update of the root's own attributes).
#[derive(Default)]
struct OwnId;
#[derive(Clone, PartialEq, Props)]
struct OwnIdProps {}
impl Component for OwnId {
type Props = OwnIdProps;
type Event = NoEvent;
fn view(_: OwnIdProps, _: Scope<NoEvent>) -> impl IntoElement {
let presses = signal(0u32);
view()
.size_10()
.test_id("own")
.label(move || SharedString::from(format!("pressed {}", presses.get())))
.on_press(move || presses.update(|n| *n += 1))
.child(view().label(move || SharedString::from(format!("child {}", presses.get()))))
}
}
#[test]
fn a_nested_components_test_id_is_on_its_root() {
let mut c = core();
c.mount_root(&Root::new::<NamedKey>(|| NamedKeyProps {}));
let batch = c.commit().unwrap();
let named: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some("save") => {
Some(*id)
}
_ => None,
})
.collect();
assert_eq!(named.len(), 1, "{:?}", batch.items);
// The key's root: the view that hears presses.
assert!(c.component_event(named[0], EventKind::Press, &EventPayload::None));
// A test id given to a component is over its root's own.
let ids: Vec<&str> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ViewProps { props, .. } => props.test_id.as_deref(),
_ => None,
})
.collect();
assert!(ids.contains(&"given") && !ids.contains(&"own"), "{ids:?}");
}
/// [`OwnId`] given `"a"`, then `"b"`, then no id: a step per press of
/// `next`.
#[derive(Default)]
struct Renamed;
#[derive(Clone, PartialEq, Props)]
struct RenamedProps {}
impl Component for Renamed {
type Props = RenamedProps;
type Event = NoEvent;
fn view(_: RenamedProps, _: Scope<NoEvent>) -> impl IntoElement {
let step = signal(0u8);
view()
.child(
view()
.size_10()
.test_id("next")
.on_press(move || step.update(|s| *s += 1)),
)
.child(dynamic(move || {
let own = OwnId::element(OwnIdProps {});
match step.get() {
0 => own.test_id("a"),
1 => own.test_id("b"),
_ => own,
}
}))
}
}
#[test]
fn a_given_test_id_stays_over_the_roots_updates_and_the_own_comes_back() {
let ids = |batch: &MountBatch| -> Vec<(NodeId, Option<String>)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ViewProps { id, props } => {
Some((*id, props.test_id.as_deref().map(str::to_owned)))
}
_ => None,
})
.collect()
};
let named = |sent: &[(NodeId, Option<String>)], name: &str| {
sent.iter()
.find(|(_, t)| t.as_deref() == Some(name))
.map(|(id, _)| *id)
};
let mut c = core();
c.mount_root(&Root::new::<Renamed>(|| RenamedProps {}));
let first = ids(&c.commit().unwrap());
let next = named(&first, "next").unwrap();
let root = named(&first, "a").expect("the id given it");
assert!(named(&first, "own").is_none(), "{first:?}");
// The root's own label changes: the label goes, and the id it was
// given neither goes again nor gives way to its own.
assert!(c.component_event(root, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::AccessibilityLabel { id, .. } if *id == root)),
"{:?}",
batch.items
);
assert_eq!(ids(&batch), [], "{:?}", batch.items);
// A second root update must not resend the given id after the child
// changed its own attributes in the previous commit.
assert!(c.component_event(root, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(ids(&batch), [], "{:?}", batch.items);
// Another id given.
assert!(c.component_event(next, EventKind::Press, &EventPayload::None));
let sent = ids(&c.commit().unwrap());
assert!(named(&sent, "b").is_some(), "{sent:?}");
// None given: the root's own.
assert!(c.component_event(next, EventKind::Press, &EventPayload::None));
let sent = ids(&c.commit().unwrap());
assert!(named(&sent, "own").is_some(), "{sent:?}");
}
/// A page whose header's colors are typed styles, theme colors among
/// them.
#[derive(Default)]
struct Page;
#[derive(Clone, PartialEq, Props)]
struct PageProps {}
impl Component for Page {
type Props = PageProps;
type Event = NoEvent;
// The core's own stack and screen: `nsh_base`'s wrap them.
#[allow(deprecated)]
fn view(_: PageProps, _: Scope<NoEvent>) -> impl IntoElement {
stack().flex_1().child(
screen()
.title("Page")
.header_style_with(|s| {
s.bg(AdaptiveColor::rgb(0xffffff, 0x000000))
.text_color(rgb(0x00ff00))
.tint_color(rgb(0x0000ff))
})
.child(view().flex_1()),
)
}
}
#[test]
fn typed_header_styles_reach_the_screens_config() {
let mut c = core();
c.mount_root(&Root::new::<Page>(|| PageProps {}));
let config = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
};
let first = config(&c.commit().unwrap()).expect("a screen");
assert_eq!(first.background_color, Some(crate::Color(0xffffffff)));
assert_eq!(first.title_color, Some(crate::Color(0x00ff00ff)));
assert_eq!(first.tint_color, Some(crate::Color(0x0000ffff)));
// Dark appearance: the theme color switches natively.
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
let dark = config(&c.commit().unwrap()).expect("restyled");
assert_eq!(dark.background_color, Some(crate::Color(0x000000ff)));
}
/// A screen whose header hairline follows `SHADOW`.
#[derive(Default)]
struct ShadowPage;
#[derive(Clone, PartialEq, Props)]
struct ShadowPageProps {}
thread_local! {
static SHADOW: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
impl Component for ShadowPage {
type Props = ShadowPageProps;
type Event = NoEvent;
// The core's own stack and screen: `nsh_base`'s wrap them.
#[allow(deprecated)]
fn view(_: ShadowPageProps, _: Scope<NoEvent>) -> impl IntoElement {
let shadow = signal(true);
SHADOW.with(|s| s.set(Some(shadow)));
stack().flex_1().child(
screen()
.title("Page")
.header_shadow_visible(move || shadow.get())
.child(view().flex_1()),
)
}
}
/// The header hairline is on by default and follows its signal.
#[test]
fn the_header_shadow_reaches_the_screens_config() {
assert!(crate::ScreenConfig::default().header_shadow_visible);
let mut c = core();
c.mount_root(&Root::new::<ShadowPage>(|| ShadowPageProps {}));
let config = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
};
let first = config(&c.commit().unwrap()).expect("a screen");
assert!(first.header_shadow_visible);
let shadow = SHADOW.with(Cell::get).expect("mounted");
{
let _entered = c.components.runtime.enter();
shadow.set(false);
}
let hidden = config(&c.commit().unwrap()).expect("updated");
assert!(!hidden.header_shadow_visible);
}
/// A screen whose title alignment follows `ALIGN`.
#[derive(Default)]
struct AlignPage;
#[derive(Clone, PartialEq, Props)]
struct AlignPageProps {}
thread_local! {
static ALIGN: Cell<Option<Signal<crate::HeaderTitleAlign>>> = const { Cell::new(None) };
}
impl Component for AlignPage {
type Props = AlignPageProps;
type Event = NoEvent;
// The core's own stack and screen: `nsh_base`'s wrap them.
#[allow(deprecated)]
fn view(_: AlignPageProps, _: Scope<NoEvent>) -> impl IntoElement {
let align = signal(crate::HeaderTitleAlign::Left);
ALIGN.with(|s| s.set(Some(align)));
stack().flex_1().child(
screen()
.title("Page")
.header_title_align(move || align.get())
.child(view().flex_1()),
)
}
}
/// The title starts at the left by default and follows its signal.
#[test]
fn the_header_title_align_reaches_the_screens_config() {
assert_eq!(
crate::ScreenConfig::default().title_align,
crate::HeaderTitleAlign::Left
);
let mut c = core();
c.mount_root(&Root::new::<AlignPage>(|| AlignPageProps {}));
let config = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
};
let first = config(&c.commit().unwrap()).expect("a screen");
assert_eq!(first.title_align, crate::HeaderTitleAlign::Left);
let align = ALIGN.with(Cell::get).expect("mounted");
{
let _entered = c.components.runtime.enter();
align.set(crate::HeaderTitleAlign::Center);
}
let centered = config(&c.commit().unwrap()).expect("updated");
assert_eq!(centered.title_align, crate::HeaderTitleAlign::Center);
}
/// A transparent screen whose header background on scroll follows
/// `ON_SCROLL`.
#[derive(Default)]
struct OnScrollPage;
#[derive(Clone, PartialEq, Props)]
struct OnScrollPageProps {}
thread_local! {
static ON_SCROLL: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
impl Component for OnScrollPage {
type Props = OnScrollPageProps;
type Event = NoEvent;
// The core's own stack and screen: `nsh_base`'s wrap them.
#[allow(deprecated)]
fn view(_: OnScrollPageProps, _: Scope<NoEvent>) -> impl IntoElement {
let on = signal(false);
ON_SCROLL.with(|s| s.set(Some(on)));
stack().flex_1().child(
screen()
.title("Page")
.header_transparent(true)
.header_background_on_scroll(move || on.get())
.child(view().flex_1()),
)
}
}
/// The header background on scroll is off by default and follows its
/// signal.
#[test]
fn the_header_background_on_scroll_reaches_the_screens_config() {
assert!(!crate::ScreenConfig::default().header_background_on_scroll);
let mut c = core();
c.mount_root(&Root::new::<OnScrollPage>(|| OnScrollPageProps {}));
let config = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
};
let first = config(&c.commit().unwrap()).expect("a screen");
assert!(first.header_transparent);
assert!(!first.header_background_on_scroll);
let on = ON_SCROLL.with(Cell::get).expect("mounted");
{
let _entered = c.components.runtime.enter();
on.set(true);
}
let updated = config(&c.commit().unwrap()).expect("updated");
assert!(updated.header_background_on_scroll);
}
/// A screen whose trailing header button is UIKit's own.
#[derive(Default)]
struct SystemItemPage;
#[derive(Clone, PartialEq, Props)]
struct SystemItemPageProps {}
impl Component for SystemItemPage {
type Props = SystemItemPageProps;
type Event = NoEvent;
// The core's own stack and screen: `nsh_base`'s wrap them.
#[allow(deprecated)]
fn view(_: SystemItemPageProps, _: Scope<NoEvent>) -> impl IntoElement {
stack().flex_1().child(
screen()
.header_right_system_item(crate::HeaderSystemItem::Add)
.header_right(view().on_press(|_: &()| {}))
.child(view().flex_1()),
)
}
}
/// The platform draws the trailing header button itself, by the name the
/// screen passes (`add` here); the `headerRight` view stays the press
/// target either way.
#[test]
fn a_system_header_button_reaches_the_screens_config() {
let mut c = core();
c.mount_root(&Root::new::<SystemItemPage>(|| SystemItemPageProps {}));
let config = c
.commit()
.unwrap()
.items
.iter()
.find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
.expect("a screen");
assert_eq!(config.right_system_item, Some(crate::HeaderSystemItem::Add));
assert!(config.right.is_some(), "the trailing slot is set");
}
/// A screen whose trailing header item shows a button only while `SHOWN`
/// says so.
#[derive(Default)]
struct OptionalItemPage;
#[derive(Clone, PartialEq, Props)]
struct OptionalItemPageProps {}
thread_local! {
static SHOWN: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
impl Component for OptionalItemPage {
type Props = OptionalItemPageProps;
type Event = NoEvent;
// The core's own stack and screen: `nsh_base`'s wrap them.
#[allow(deprecated)]
fn view(_: OptionalItemPageProps, _: Scope<NoEvent>) -> impl IntoElement {
let shown = signal(false);
SHOWN.with(|s| s.set(Some(shown)));
stack().flex_1().child(
screen()
.header_right(when(shown, || view().w(px(24.0)).h(px(24.0))))
.child(view().flex_1()),
)
}
}
/// The last screen options of `batch`, if it has any.
fn last_screen_config(batch: &MountBatch) -> Option<ScreenConfig> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
}
/// A header item whose content is gone shows nothing: the screen's
/// options leave it out (the iOS bar would wrap it in an empty button),
/// and put it back when its content returns.
#[test]
fn an_empty_header_item_is_left_out_of_the_screens_config() {
let mut c = core();
c.mount_root(&Root::new::<OptionalItemPage>(|| OptionalItemPageProps {}));
let first = last_screen_config(&c.commit().unwrap()).expect("a screen");
assert_eq!(first.right, None, "nothing shows in the trailing slot");
let shown = SHOWN.with(Cell::get).unwrap();
{
let _entered = c.components.runtime.enter();
shown.set(true);
}
let config = last_screen_config(&c.commit().unwrap()).expect("options again");
assert!(config.right.is_some(), "the trailing slot shows its button");
{
let _entered = c.components.runtime.enter();
shown.set(false);
}
let config = last_screen_config(&c.commit().unwrap()).expect("options again");
assert_eq!(config.right, None, "the trailing slot is empty again");
// Nothing changed: no options again.
let batch = c.commit();
assert!(batch.is_none_or(|b| last_screen_config(&b).is_none()));
}
#[derive(Default)]
struct OptionalTitlePage;
#[derive(Clone, PartialEq, Props)]
struct OptionalTitlePageProps {}
thread_local! {
static TITLE_SHOWN: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
impl Component for OptionalTitlePage {
type Props = OptionalTitlePageProps;
type Event = NoEvent;
#[allow(deprecated)]
fn view(_: OptionalTitlePageProps, _: Scope<NoEvent>) -> impl IntoElement {
let shown = signal(false);
TITLE_SHOWN.with(|s| s.set(Some(shown)));
stack().flex_1().child(
screen()
.title("Chat")
.header_title(when(shown, || view().w(px(80.0)).h(px(24.0))))
.child(view().flex_1()),
)
}
}
/// A title view with nothing to show leaves the platform's title text,
/// and comes back when its content does (allsum-nsh#1900).
#[test]
fn an_empty_header_title_falls_back_to_the_system_title() {
let mut c = core();
c.mount_root(&Root::new::<OptionalTitlePage>(
|| OptionalTitlePageProps {},
));
let first = last_screen_config(&c.commit().unwrap()).expect("a screen");
assert_eq!(first.title_view, None, "nothing shows in the title slot");
let shown = TITLE_SHOWN.with(Cell::get).unwrap();
{
let _entered = c.components.runtime.enter();
shown.set(true);
}
let config = last_screen_config(&c.commit().unwrap()).expect("options again");
assert!(config.title_view.is_some(), "the title view shows");
{
let _entered = c.components.runtime.enter();
shown.set(false);
}
let config = last_screen_config(&c.commit().unwrap()).expect("options again");
assert_eq!(config.title_view, None, "back to the system title");
}
/// Without the prop the header is built as before: no system button, so
/// the platform wraps the app's `headerRight` view instead.
#[test]
fn a_screen_without_the_prop_has_no_system_header_button() {
let mut c = core();
c.mount_root(&Root::new::<Page>(|| PageProps {}));
let config = c
.commit()
.unwrap()
.items
.iter()
.find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
.expect("a screen");
assert_eq!(config.right_system_item, None);
}
/// A screen whose header buttons are UIKit's own: a system item on the
/// left, an SF Symbol on the right.
#[derive(Default)]
struct SymbolPage;
#[derive(Clone, PartialEq, Props)]
struct SymbolPageProps {}
impl Component for SymbolPage {
type Props = SymbolPageProps;
type Event = NoEvent;
#[allow(deprecated)]
fn view(_: SymbolPageProps, _: Scope<NoEvent>) -> impl IntoElement {
stack().flex_1().child(
screen()
.header_left_system_item(crate::HeaderSystemItem::Close)
.header_left(view().on_press(|_: &()| {}))
.header_right_symbol("slider.horizontal.3")
.header_right(view().on_press(|_: &()| {}))
.child(view().flex_1()),
)
}
}
/// Both slots take a UIKit button: the leading one by a system item, the
/// trailing one by an SF Symbol's name; the app's views stay the press
/// targets.
#[test]
fn leading_and_symbol_header_buttons_reach_the_screens_config() {
let mut c = core();
c.mount_root(&Root::new::<SymbolPage>(|| SymbolPageProps {}));
let config = c
.commit()
.unwrap()
.items
.iter()
.find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
.expect("a screen");
assert_eq!(
config.left_system_item,
Some(crate::HeaderSystemItem::Close)
);
assert_eq!(config.left_symbol, None);
assert_eq!(config.right_system_item, None);
assert_eq!(config.right_symbol.as_deref(), Some("slider.horizontal.3"));
assert!(
config.left.is_some() && config.right.is_some(),
"both slots are set"
);
}
/// A screen whose trailing bar is several UIKit buttons, one with a menu.
#[derive(Default)]
struct RightItemsPage;
#[derive(Clone, PartialEq, Props)]
struct RightItemsPageProps {}
impl Component for RightItemsPage {
type Props = RightItemsPageProps;
type Event = NoEvent;
#[allow(deprecated)]
fn view(_: RightItemsPageProps, _: Scope<NoEvent>) -> impl IntoElement {
use crate::{
HeaderSystemItem,
element::{desktop::MenuItem, header::HeaderItem},
};
stack().flex_1().child(
screen()
.header_right_items(vec![
HeaderItem::system(HeaderSystemItem::Edit).key("edit"),
HeaderItem::symbol("ellipsis.circle").key("more").menu([
MenuItem::new("Share"),
MenuItem::submenu(
"Danger",
[MenuItem::new("Delete").destructive(true)],
)
.inline(true),
]),
])
.header_right_system_item(HeaderSystemItem::Add)
.header_right(view().on_press(|_: &()| {}))
.child(view().flex_1()),
)
}
}
/// Trailing `header_right_items` reach the screen's config, including a
/// menu; a non-empty list leaves the single system item set too (the
/// platform prefers the list).
#[test]
fn trailing_header_items_reach_the_screens_config() {
let mut c = core();
c.mount_root(&Root::new::<RightItemsPage>(|| RightItemsPageProps {}));
let config = c
.commit()
.unwrap()
.items
.iter()
.find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
.expect("a screen");
assert_eq!(config.right_items.len(), 2);
assert_eq!(config.right_items[0].key.as_deref(), Some("edit"));
assert_eq!(
config.right_items[0].content,
crate::HeaderItemContent::SystemItem(crate::HeaderSystemItem::Edit)
);
assert_eq!(config.right_items[1].key.as_deref(), Some("more"));
let menu = config.right_items[1].menu.as_ref().expect("a menu");
assert_eq!(menu.len(), 2);
assert_eq!(
config.right_system_item,
Some(crate::HeaderSystemItem::Add),
"the single system item stays in the config; the platform prefers the list"
);
}
/// Leading `header_left_items` reach the screen's config next to the
/// trailing ones, each list with its own handlers: a symbol with a
/// title is one button, and pressing either side runs its own handler.
#[test]
fn leading_header_items_reach_the_screens_config() {
use std::cell::Cell;
use crate::{
EventKind, EventPayload, HeaderItemContent, PayloadValue, ROOT_ID,
element::header::HeaderItem,
};
thread_local! {
static LEFT: Cell<u32> = const { Cell::new(0) };
static RIGHT: Cell<u32> = const { Cell::new(0) };
}
LEFT.with(|c| c.set(0));
RIGHT.with(|c| c.set(0));
#[derive(Default)]
struct LeftItemsPage;
#[derive(Clone, PartialEq, Props)]
struct LeftItemsPageProps {}
impl Component for LeftItemsPage {
type Props = LeftItemsPageProps;
type Event = NoEvent;
fn view(_: LeftItemsPageProps, _: Scope<NoEvent>) -> impl IntoElement {
stack().flex_1().child(
screen()
.header_left_items(vec![
HeaderItem::symbol("line.3.horizontal")
.label("Chats")
.key("menu"),
HeaderItem::symbol_title("sparkles", "Upgrade")
.key("upgrade")
.shares_background(false)
.on_press(|| LEFT.with(|c| c.set(c.get() + 1))),
])
.header_right_items(vec![
HeaderItem::symbol("square.and.pencil")
.key("new")
.on_press(|| RIGHT.with(|c| c.set(c.get() + 1))),
])
.header_left_symbol("line.3.horizontal")
.header_left(view().on_press(|_: &()| {}))
.child(view().flex_1()),
)
}
}
let mut c = core();
c.mount_root(&Root::new::<LeftItemsPage>(|| LeftItemsPageProps {}));
let config = c
.commit()
.unwrap()
.items
.iter()
.find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
.expect("a screen");
assert_eq!(config.left_items.len(), 2);
assert_eq!(config.left_items[0].key.as_deref(), Some("menu"));
assert_eq!(config.left_items[0].label.as_deref(), Some("Chats"));
assert_eq!(
config.left_items[1].content,
HeaderItemContent::SymbolTitle {
symbol: "sparkles".into(),
title: "Upgrade".into()
}
);
assert!(config.left_items[0].shares_background);
assert!(!config.left_items[1].shares_background);
assert_eq!(
config.left_symbol.as_deref(),
Some("line.3.horizontal"),
"the single symbol stays in the config; the platform prefers the list"
);
assert_eq!(config.right_items.len(), 1);
let menu = |id| EventPayload::Map(vec![("id", PayloadValue::Number(id as f64))]);
let (left, right) = (
config.left_items[1].press_id,
config.right_items[0].press_id,
);
assert!(left != 0 && right != 0 && left != right);
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(left)));
assert_eq!((LEFT.with(Cell::get), RIGHT.with(Cell::get)), (1, 0));
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(right)));
assert_eq!((LEFT.with(Cell::get), RIGHT.with(Cell::get)), (1, 1));
}
/// A header button's `on_press` and a menu item's `on_select` run when
/// the platform reports their ids as the root's `Menu` event; replacing
/// the items (same keys, so UIKit keeps the buttons) assigns new ids
/// and drops the previous generation's handlers.
#[test]
fn trailing_header_item_handlers_run_on_menu_and_drop_when_replaced() {
use std::cell::Cell;
use crate::{
EventKind, EventPayload, HeaderSystemItem, PayloadValue, ROOT_ID,
element::{desktop::MenuItem, header::HeaderItem, reactive::signal},
};
thread_local! {
static PRESSES: Cell<u32> = const { Cell::new(0) };
static SELECTS: Cell<u32> = const { Cell::new(0) };
}
PRESSES.with(|c| c.set(0));
SELECTS.with(|c| c.set(0));
#[derive(Default)]
struct HandlersPage;
#[derive(Clone, PartialEq, Props)]
struct HandlersPageProps {}
impl Component for HandlersPage {
type Props = HandlersPageProps;
type Event = NoEvent;
fn view(_: HandlersPageProps, _: Scope<NoEvent>) -> impl IntoElement {
// `phase` cannot be named `gen` (edition 2024 keyword).
let phase = signal(0u32);
stack().flex_1().child(
screen()
.header_right_items(move || {
let suspended = phase.get() != 0;
vec![
HeaderItem::system(HeaderSystemItem::Edit)
.key("edit")
.on_press(|| PRESSES.with(|c| c.set(c.get() + 1))),
HeaderItem::symbol("ellipsis.circle").key("more").menu([
MenuItem::new(if suspended { "Reinstate" } else { "Suspend" })
.on_select(|| SELECTS.with(|c| c.set(c.get() + 1))),
]),
]
})
.child(view().flex_1().on_press(move |_: &()| {
phase.set(1);
})),
)
}
}
let mut c = core();
c.mount_root(&Root::new::<HandlersPage>(|| HandlersPageProps {}));
let batch = c.commit().unwrap();
let config = batch
.items
.iter()
.find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
.expect("a screen");
let content_id = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events }
if events.contains(EventKind::Press) && *id != ROOT_ID =>
{
Some(*id)
}
_ => None,
})
.expect("the content view");
let press_id = config.right_items[0].press_id;
let select_id = match &config.right_items[1].menu.as_ref().unwrap()[0] {
crate::desktop::MenuItem::Action(a) => a.id,
_ => panic!("action"),
};
assert!(press_id != 0 && select_id != 0);
let menu = |id| EventPayload::Map(vec![("id", PayloadValue::Number(id as f64))]);
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(press_id)));
assert_eq!(PRESSES.with(|c| c.get()), 1);
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(select_id)));
assert_eq!(SELECTS.with(|c| c.get()), 1);
// Same keys / looks: the platform keeps the buttons. The binding
// still gives each a new id; the previous generation is gone.
assert!(c.component_event(content_id, EventKind::Press, &EventPayload::None));
let updated = c
.commit()
.unwrap()
.items
.iter()
.find_map(|i| match i {
MountItem::ScreenConfig { config, .. } => Some((**config).clone()),
_ => None,
})
.expect("updated screen");
assert!(
crate::element::header::same_buttons(&config.right_items, &updated.right_items),
"identity stays so UIKit keeps the UIBarButtonItems"
);
let new_press_id = updated.right_items[0].press_id;
let new_select_id = match &updated.right_items[1].menu.as_ref().unwrap()[0] {
crate::desktop::MenuItem::Action(a) => {
assert_eq!(a.label, "Reinstate");
a.id
}
_ => panic!("action"),
};
assert_ne!(new_press_id, press_id);
assert_ne!(new_select_id, select_id);
assert!(new_press_id != 0 && new_select_id != 0);
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(press_id)));
assert_eq!(PRESSES.with(|c| c.get()), 1, "stale press id is dropped");
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(select_id)));
assert_eq!(SELECTS.with(|c| c.get()), 1, "stale menu id is dropped");
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(new_press_id)));
assert_eq!(PRESSES.with(|c| c.get()), 2);
assert!(c.component_event(ROOT_ID, EventKind::Menu, &menu(new_select_id)));
assert_eq!(SELECTS.with(|c| c.get()), 2);
}
/// A selectable view's `selection_menu` reaches its view props as plain
/// items and separators (roles, submenus and shortcuts left out), and a
/// chosen item's `on_select` runs when the platform reports its id as
/// the root's `Menu` event.
#[test]
fn selection_menu_items_reach_the_view_and_run_when_chosen() {
use std::cell::Cell;
use crate::{
EventKind, EventPayload, PayloadValue, ROOT_ID,
desktop::{MenuItem as PlatformItem, MenuRole},
element::desktop::MenuItem,
};
thread_local! {
static CHOSEN: Cell<u32> = const { Cell::new(0) };
}
CHOSEN.with(|c| c.set(0));
#[derive(Default)]
struct Area;
#[derive(Clone, PartialEq, Props)]
struct AreaProps {}
impl Component for Area {
type Props = AreaProps;
type Event = NoEvent;
fn view(_: AreaProps, _: Scope<NoEvent>) -> impl IntoElement {
view()
.selectable(true)
.selection_menu(vec![
MenuItem::separator(),
MenuItem::role(MenuRole::Copy),
MenuItem::new("Highlight")
.shortcut("mod+h")
.on_select(|| CHOSEN.with(|c| c.set(c.get() + 1))),
MenuItem::separator(),
MenuItem::separator(),
MenuItem::submenu("More", [MenuItem::new("Nested")]),
MenuItem::new("Define").disabled(true),
MenuItem::separator(),
])
.child(text("Some words"))
}
}
let mut c = core();
c.mount_root(&Root::new::<Area>(|| AreaProps {}));
let batch = c.commit().unwrap();
let menu = batch
.items
.iter()
.find_map(|i| match i {
MountItem::ViewProps { props, .. } if props.selectable_view => {
Some(props.selection_menu.clone())
}
_ => None,
})
.expect("the selectable view's props");
let [
PlatformItem::Action(highlight),
PlatformItem::Separator,
PlatformItem::Action(define),
] = &menu[..]
else {
panic!("plain items and one separator between them: {menu:?}");
};
assert_eq!(highlight.label, "Highlight");
assert_eq!(highlight.shortcut, None);
assert_ne!(highlight.id, 0);
assert_eq!(define.label, "Define");
assert!(!define.enabled);
assert_eq!(define.id, 0, "no handler, no id");
let chosen = EventPayload::Map(vec![("id", PayloadValue::Number(highlight.id as f64))]);
assert!(c.component_event(ROOT_ID, EventKind::Menu, &chosen));
assert_eq!(CHOSEN.with(|c| c.get()), 1);
}
/// A Rust component that renders a native component.
#[derive(Default)]
struct NativeHost;
#[derive(Clone, PartialEq, Props)]
struct NativeHostProps {}
impl Component for NativeHost {
type Props = NativeHostProps;
type Event = NoEvent;
fn view(_: NativeHostProps, _: Scope<NoEvent>) -> impl IntoElement {
crate::element::native("test.native")
.prop("items", serde_json::json!([1]))
.flex_1()
}
}
/// The platform is told which component a Rust `native()` element holds,
/// and gets its props.
#[test]
fn a_native_component_from_rust_is_named() {
let mut c = core();
c.mount_root(&Root::new::<NativeHost>(|| NativeHostProps {}));
let batch = c.commit().unwrap();
let named = batch
.items
.iter()
.any(|i| matches!(i, MountItem::Component { name, .. } if &**name == "test.native"));
assert!(
named,
"the platform is told which component to make: {:#?}",
batch.items
);
let props = batch.items.iter().any(|i| {
matches!(i, MountItem::ComponentProps { props, .. }
if props.iter().any(|(k, _)| &**k == "items"))
});
assert!(props, "its props reach it");
}
/// A Rust component that binds a native component's prop.
#[derive(Default)]
struct AnimatedNativeHost;
#[derive(Clone, PartialEq, Props)]
struct AnimatedNativeHostProps {}
impl Component for AnimatedNativeHost {
type Props = AnimatedNativeHostProps;
type Event = NoEvent;
fn view(_: AnimatedNativeHostProps, _: Scope<NoEvent>) -> impl IntoElement {
let v = animated_value(0.5);
crate::element::native("test.native")
.bind_animated_prop("progress", &v)
.flex_1()
}
}
#[test]
fn native_view_binds_animated_prop() {
let mut c = core();
c.mount_root(&Root::new::<AnimatedNativeHost>(|| {
AnimatedNativeHostProps {}
}));
let batch = c.commit().unwrap();
assert!(
batch.items.iter().any(|i| matches!(
i,
MountItem::ComponentPropSlots { names, .. } if names.len() == 1 && &*names[0] == "progress"
)),
"{:#?}",
batch.items
);
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::AnimationBindings { bindings, .. }
if bindings.iter().any(|(p, _)| *p == crate::animation::AnimationProp::ComponentSlot(0))
)));
// The value lives with the element, though the view let go of it.
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::Animation(crate::animation::AnimationOp::Release { .. })
)));
}
/// A holder of its children as its view's root.
#[derive(Default)]
struct Tray;
#[derive(Clone, PartialEq, Props)]
struct TrayProps {
children: Children,
}
impl Component for Tray {
type Props = TrayProps;
type Event = NoEvent;
fn view(props: TrayProps, _: Scope<NoEvent>) -> impl IntoElement {
Holder::element(HolderProps {
children: Children::default(),
})
.opacity(0.5)
.child(props.children)
}
}
#[test]
fn a_js_host_of_a_rooted_component_takes_the_apps_styles_events_and_children() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Tray>();
registry.register::<Plaque>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Plaque>().into()),
},
Op::SetProp {
id: 2,
prop: Prop::Class("opacity-25".into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
// The app's class goes after what the view gives the counter.
assert_eq!(view_style_of(&batch, 2).map(|s| s.opacity), Some(0.25));
// JS stops listening to presses: the counter's view still does.
apply(
&mut c,
vec![
Op::Listen {
id: 2,
event: EventKind::Press,
enabled: true,
},
Op::Listen {
id: 2,
event: EventKind::Press,
enabled: false,
},
],
);
c.commit();
let key = c.key(2).unwrap();
assert!(c.nodes[key as usize].events.contains(EventKind::Press));
// The app's classes change: the node follows.
c.apply(Op::SetProp {
id: 2,
prop: Prop::Class("opacity-75".into()),
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, 2).map(|s| s.opacity), Some(0.75));
// A tray: JS's children go into the host itself.
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::Component(std::any::type_name::<Tray>().into()),
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(native_parent(&c, 6), Some(4));
assert_eq!(creates(&batch), 2, "{:?}", batch.items);
// Released: its nodes go, JS's child stays.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 4,
},
Op::Release { id: 4 },
Op::Release { id: 2 },
],
);
let batch = c.commit().unwrap();
assert!(c.key(6).is_ok());
assert_eq!(native_parent(&c, 6), None);
assert!(c.components.instances.is_empty());
let deleted: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Delete { id } => Some(*id),
_ => None,
})
.collect();
assert!(deleted.contains(&2) && deleted.contains(&4), "{deleted:?}");
assert_eq!(c.nodes.len(), 2, "the root and JS's child are left");
}
/// Places its corner slot as it is after a title, or padded when
/// `framed`.
#[derive(Default)]
struct Corner;
#[derive(Clone, PartialEq, Props)]
struct CornerProps {
#[prop(default)]
framed: bool,
corner: crate::element::Prop<Option<Slot>>,
}
impl Component for Corner {
type Props = CornerProps;
type Event = NoEvent;
fn view(props: CornerProps, _: Scope<NoEvent>) -> impl IntoElement {
let framed = props.framed;
view().child(text("title")).child(
props
.corner
.place(move |c| if framed { c.p_2() } else { c }),
)
}
}
/// Fills corners: with a counter, with what a press switches (a
/// text, a view of a text), with a text shown while on, and framed.
#[derive(Default)]
struct Corners;
#[derive(Clone, PartialEq, Props)]
struct CornersProps {}
impl Component for Corners {
type Props = CornersProps;
type Event = NoEvent;
fn view(_: CornersProps, _: Scope<NoEvent>) -> impl IntoElement {
let n = signal(0);
view()
.on_press(move || n.update(|n| *n += 1))
.child(Corner::element(CornerProps::default()).fill(
"corner",
Counter::element(CounterProps {
label: "Aside".into(),
}),
))
.child(dynamic(move || {
// A corner each run, filled anew.
let fill = if n.get() % 2 == 0 {
text("even").into_element()
} else {
view().child(text("odd")).into_element()
};
Corner::element(CornerProps::default()).fill("corner", fill)
}))
.child(Corner::element(CornerProps::default()).fill(
"corner",
dynamic(move || (n.get() == 1).then(|| text("one"))),
))
.child(
Corner::element(CornerProps {
framed: true,
..Default::default()
})
.fill("corner", text("framed")),
)
}
}
#[test]
fn a_slot_a_view_fills_is_placed_as_it_is() {
let mut c = core();
c.mount_root(&Root::new::<Corners>(|| CornersProps {}));
let batch = c.commit().unwrap();
let root = root_host(&batch);
let corners = native_children(&c, root);
assert_eq!(corners.len(), 4);
// The third corner's fill shows nothing: its title alone.
assert_eq!(native_children(&c, corners[2]).len(), 1);
// The counter's host is the corner's child: no holder.
let counted = native_parent(&c, text_node(&batch, "Aside 0")).expect("placed");
assert_eq!(native_parent(&c, counted), Some(corners[0]));
assert_eq!(native_children(&c, corners[0]).len(), 2);
assert_eq!(
native_parent(&c, text_node(&batch, "even")),
Some(corners[1])
);
// Styled: in a node of the corner's own.
let framed = native_parent(&c, text_node(&batch, "framed")).expect("placed");
assert_ne!(framed, corners[3]);
assert_eq!(native_parent(&c, framed), Some(corners[3]));
// Its listener and events are its own.
assert!(c.component_event(counted, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["Aside 1"]);
// Filled anew: the new element takes the old one's place.
assert!(c.component_event(root, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let odd = native_parent(&c, text_node(&batch, "odd")).expect("placed");
let corners = native_children(&c, root);
assert_eq!(native_parent(&c, odd), Some(corners[1]));
assert_eq!(native_children(&c, corners[1]).len(), 2);
// A fill that shows something now: placed in its corner.
let one = text_node(&batch, "one");
assert_eq!(native_parent(&c, one), Some(corners[2]));
// And gone again (released with no holder to leave); even again.
assert!(c.component_event(root, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(c.key(one).is_err(), "released");
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { .. })),
"{:?}",
batch.items
);
let corners = native_children(&c, root);
assert_eq!(native_children(&c, corners[2]).len(), 1, "the title alone");
let even = text_node(&batch, "even");
assert_eq!(native_parent(&c, even), Some(corners[1]));
assert_eq!(native_children(&c, corners[1]).len(), 2);
}
/// A row 300 × 40: its label slot made a button (no styles), then a 50 ×
/// 20 box.
#[derive(Default)]
struct LabeledRow;
#[derive(Clone, PartialEq, Props)]
struct LabeledRowProps {
label: crate::element::Prop<Option<Slot>>,
}
impl Component for LabeledRow {
type Props = LabeledRowProps;
type Event = NoEvent;
fn view(props: LabeledRowProps, _: Scope<NoEvent>) -> impl IntoElement {
view()
.flex_row()
.items_center()
.w(px(300.0))
.h(px(40.0))
.child(
props
.label
.place(|c| c.role(crate::AccessibilityRole::Button)),
)
.child(view().w(px(50.0)).h(px(20.0)))
}
}
/// Fills a row's label with a text that grows.
#[derive(Default)]
struct GrowingLabel;
#[derive(Clone, PartialEq, Props)]
struct GrowingLabelProps {}
impl Component for GrowingLabel {
type Props = GrowingLabelProps;
type Event = NoEvent;
fn view(_: GrowingLabelProps, _: Scope<NoEvent>) -> impl IntoElement {
LabeledRow::element(LabeledRowProps::default()).fill("label", text("grow").flex_1())
}
}
/// The node a view wraps its fill of a slot in when the place gives it
/// props but no styles lays the fill out through: the fill grows along
/// the row as the component's own child would, the wrapper takes its
/// box and the fill sits at its origin.
#[test]
fn a_fill_in_a_wrapper_lays_out_in_the_components_layout() {
let mut c = core();
c.mount_root(&Root::new::<GrowingLabel>(|| GrowingLabelProps {}));
let batch = c.commit().unwrap();
let grow = text_node(&batch, "grow");
let wrapper = native_parent(&c, grow).expect("placed");
let row = native_parent(&c, wrapper).expect("placed");
assert_eq!(native_children(&c, row).len(), 2, "the wrapper and the box");
let wrapped = frame_of(&batch, wrapper).expect("a frame");
assert_eq!(
(wrapped.origin.x.0, wrapped.size.width.0),
(0.0, 250.0),
"grows to the box"
);
let grown = frame_of(&batch, grow).expect("a frame");
assert_eq!(
(grown.origin.x.0, grown.origin.y.0, grown.size.width.0),
(0.0, 0.0, 250.0)
);
assert_eq!(grown.size.height, wrapped.size.height);
}
#[derive(Clone, PartialEq, Props)]
struct MidProps {
corner: crate::element::Prop<Option<Slot>>,
}
/// Passes its corner slot on to a corner's.
#[component]
fn Mid(props: MidProps) -> impl IntoElement {
view().child(
Corner::element(CornerProps::default()).fill("corner", props.corner.place(|c| c)),
)
}
/// Fills a mid's corner with a text, and another's with what a press
/// switches (a text, nothing, a view of a text).
#[component]
fn Top() -> impl IntoElement {
let n = signal(0);
view()
.on_press(move || n.update(|n| *n += 1))
.child(mid().corner(text("deep")))
.child(mid().corner(dynamic(move || match n.get() % 3 {
0 => Some(text("switched").into_element()),
1 => None,
_ => Some(view().child(text("boxed")).into_element()),
})))
}
#[test]
fn a_filled_slot_passed_on_to_another_slot_is_placed_there() {
let mut c = core();
c.mount_root(&Root::new::<Top>(|| ()));
let batch = c.commit().unwrap();
let top = root_host(&batch);
// Each mid's view is its corner.
let mids = native_children(&c, top);
let [first, second] = [0, 1].map(|i| native_children(&c, mids[i])[0]);
let deep = text_node(&batch, "deep");
assert_eq!(native_parent(&c, deep), Some(first), "{:?}", batch.items);
let switched = text_node(&batch, "switched");
assert_eq!(native_parent(&c, switched), Some(second));
// Gone, then a view of a text: the deeper corner follows.
assert!(c.component_event(top, EventKind::Press, &EventPayload::None));
c.commit().unwrap();
assert_eq!(native_children(&c, second).len(), 1, "the title alone");
assert!(c.component_event(top, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let boxed = native_parent(&c, text_node(&batch, "boxed")).expect("placed");
assert_eq!(native_parent(&c, boxed), Some(second), "{:?}", batch.items);
}
/// A corner as its view's root, its fill switched by a press on it
/// (a text, a view of a text).
#[component]
fn RootedCorner() -> impl IntoElement {
let on = signal(true);
let flip = move || on.update(|o| *o = !*o);
Corner::element(CornerProps::default()).fill(
"corner",
dynamic(move || {
if on.get() {
text("x").on_press(flip).into_element()
} else {
view().on_press(flip).child(text("y")).into_element()
}
}),
)
}
#[test]
fn a_component_rooted_in_another_fills_its_slot() {
let mut c = core();
c.mount_root(&Root::new::<RootedCorner>(|| ()));
let batch = c.commit().unwrap();
let host = root_host(&batch);
assert_eq!(native_parent(&c, text_node(&batch, "x")), Some(host));
assert_eq!(native_children(&c, host).len(), 2);
for round in 0..4 {
let fill = native_children(&c, host)[1];
assert!(c.component_event(fill, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(
native_children(&c, host).len(),
2,
"{round}: {:?}",
batch.items
);
}
}
#[derive(Clone, PartialEq, Props)]
struct FocusCornerProps {
corner: crate::element::Prop<Option<Slot>>,
}
/// Counts the focus its corner gets and loses: listeners the place
/// gives the slot.
#[component]
fn FocusCorner(props: FocusCornerProps) -> impl IntoElement {
let (focused, blurred) = (signal(0), signal(0));
view()
.child(text(move || {
format!("focus {} blur {}", focused.get(), blurred.get())
}))
.child(props.corner.place(move |c| {
c.on_focus(move || focused.update(|n| *n += 1))
.on_blur(move || blurred.update(|n| *n += 1))
}))
}
/// Fills a focus corner with a focusable view it counts the presses
/// of, then (pressing "switch") with a focusable text in its place.
#[component]
fn FocusTop() -> impl IntoElement {
let (presses, second) = (signal(0), signal(false));
let press = move || presses.update(|n| *n += 1);
view()
.child(text(move || format!("pressed {}", presses.get())))
.child(focus_corner().corner(dynamic(move || {
if second.get() {
text("second").focusable(true).into_element()
} else {
view()
.focusable(true)
.on_press(press)
.child(text("first"))
.into_element()
}
})))
.child(
view()
.on_press(move || second.set(true))
.child(text("switch")),
)
}
/// A slot a Rust view fills with one element, whose place gives it
/// listeners: they go to that element as to a TSX app's in its holder
/// (the node around the fill keeps none), so the focus, which only the
/// focused element hears, reaches the component; the element's own
/// listeners run too, and an element made in its place takes them.
#[test]
fn a_fills_one_element_hears_the_listeners_its_place_gives() {
let events = |c: &Core<FakeEngine>, id: NodeId| c.nodes[c.key(id).unwrap() as usize].events;
let mut c = core();
c.mount_root(&Root::new::<FocusTop>(|| ()));
let batch = c.commit().unwrap();
let switch = native_parent(&c, text_node(&batch, "switch")).expect("placed");
let first = native_parent(&c, text_node(&batch, "first")).expect("placed");
let holder = native_parent(&c, first).expect("in the node around the fill");
assert!(events(&c, first).contains(EventKind::Focus));
assert!(events(&c, first).contains(EventKind::Blur));
assert!(events(&c, first).contains(EventKind::Press), "its own");
assert!(!events(&c, holder).contains(EventKind::Focus));
assert!(c.component_event(first, EventKind::Focus, &EventPayload::None));
assert!(c.component_event(first, EventKind::Blur, &EventPayload::None));
assert!(c.component_event(first, EventKind::Press, &EventPayload::None));
let shown = texts(&c.commit().unwrap());
assert!(shown.contains(&"focus 1 blur 1".into()), "{shown:?}");
assert!(shown.contains(&"pressed 1".into()), "{shown:?}");
// Another element in its place: the listeners follow it.
assert!(c.component_event(switch, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let second = text_node(&batch, "second");
assert!(c.key(first).is_err(), "released");
assert_eq!(native_parent(&c, second), Some(holder));
assert!(events(&c, second).contains(EventKind::Focus));
assert!(!events(&c, holder).contains(EventKind::Focus));
assert!(c.component_event(second, EventKind::Focus, &EventPayload::None));
let shown = texts(&c.commit().unwrap());
assert!(shown.contains(&"focus 2 blur 1".into()), "{shown:?}");
}
/// A focusable pad counting its presses.
#[component]
fn Pad() -> impl IntoElement {
let presses = signal(0);
view()
.focusable(true)
.on_press(move || presses.update(|n| *n += 1))
.child(text(move || format!("pad {}", presses.get())))
}
/// A pad as its view's root: its node is made under the pad's id.
#[component]
fn RootedPad() -> impl IntoElement {
pad()
}
/// Fills a focus corner with a rooted pad: a component whose view,
/// made once the slot places it, has another component as its root.
#[component]
fn RootedPadTop() -> impl IntoElement {
view().child(focus_corner().corner(rooted_pad()))
}
/// A Rust fill that is a component whose view's root is another
/// component (a library button made of a base one) hears the
/// listeners its place gives, as a plain element does: its view is
/// made after the slot is placed, under the inner component's id, and
/// the slot's listeners follow it there. Its own listeners run too.
#[test]
fn a_fill_rooted_in_another_component_hears_the_listeners_its_place_gives() {
let mut c = core();
c.mount_root(&Root::new::<RootedPadTop>(|| ()));
let batch = c.commit().unwrap();
let pad = native_parent(&c, text_node(&batch, "pad 0")).expect("placed");
let events = c.nodes[c.key(pad).unwrap() as usize].events;
assert!(events.contains(EventKind::Focus));
assert!(events.contains(EventKind::Blur));
// The host's own handling is what the dispatch reports.
c.component_event(pad, EventKind::Focus, &EventPayload::None);
c.component_event(pad, EventKind::Blur, &EventPayload::None);
assert!(c.component_event(pad, EventKind::Press, &EventPayload::None));
let shown = texts(&c.commit().unwrap());
assert!(shown.contains(&"focus 1 blur 1".into()), "{shown:?}");
assert!(shown.contains(&"pad 1".into()), "{shown:?}");
}
/// Logs the focus coming into its area and leaving it, and dims the
/// area while the focus is in it: two focusable views and a popup
/// inside, one outside.
#[component]
fn FocusArea() -> impl IntoElement {
let log = signal(Vec::<&'static str>::new());
let area = element_ref();
area.on_focus_in(move || log.update(|l| l.push("in")));
area.on_focus_out(move || log.update(|l| l.push("out")));
view()
.child(text(move || format!("log {}", log.get().join(" "))))
.child(
view()
.element_ref(&area)
.focus_within(|s| s.opacity(0.5))
.child(view().focusable(true).child(text("first")))
.child(view().focusable(true).child(text("second")))
.child(overlay().child(view().focusable(true).child(text("popup")))),
)
.child(view().focusable(true).child(text("away")))
}
/// GPUI's `on_focus_in` / `on_focus_out` of an element: the focus
/// coming in from outside and leaving to outside, not moving inside it
/// (into its popup too); `.focus_within(..)` styles it meanwhile.
#[test]
fn an_element_hears_the_focus_come_in_and_leave() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
c.mount_root(&Root::new::<FocusArea>(|| ()));
let batch = c.commit().unwrap();
let first = native_parent(&c, text_node(&batch, "first")).unwrap();
let second = native_parent(&c, text_node(&batch, "second")).unwrap();
let popup = native_parent(&c, text_node(&batch, "popup")).unwrap();
let away = native_parent(&c, text_node(&batch, "away")).unwrap();
let area = native_parent(&c, first).unwrap();
c.set_states(first, FOCUSED);
let batch = c.commit().unwrap();
assert!(
texts(&batch).contains(&"log in".into()),
"{:?}",
texts(&batch)
);
assert_eq!(view_style_of(&batch, area).unwrap().opacity, 0.5);
c.set_states(second, FOCUSED);
c.set_states(first, 0);
c.set_states(popup, FOCUSED);
c.set_states(second, 0);
let batch = c.commit();
assert!(batch.is_none_or(|b| texts(&b).is_empty()), "no news inside");
c.set_states(away, FOCUSED);
c.set_states(popup, 0);
let batch = c.commit().unwrap();
assert!(
texts(&batch).contains(&"log in out".into()),
"{:?}",
texts(&batch)
);
assert_eq!(view_style_of(&batch, area).unwrap().opacity, 1.0);
// Back in: the area's own state again.
c.set_states(popup, FOCUSED);
c.set_states(away, 0);
let batch = c.commit().unwrap();
assert!(
texts(&batch).contains(&"log in out in".into()),
"{:?}",
texts(&batch)
);
}
/// Logs the focus coming into and leaving one ref's element, which
/// shows (with a focusable view inside) while `shown`: a press on
/// "toggle" removes it, and the next brings a new one with the ref.
#[component]
fn FocusRemount() -> impl IntoElement {
let log = signal(Vec::<&'static str>::new());
let shown = signal(true);
let area = element_ref();
area.on_focus_in(move || log.update(|l| l.push("in")));
area.on_focus_out(move || log.update(|l| l.push("out")));
view()
.child(text(move || format!("log {}", log.get().join(" "))))
.child(when(shown, move || {
view()
.element_ref(&area)
.child(view().focusable(true).child(text("field")))
}))
.child(
view()
.on_press(move || shown.update(|s| *s = !*s))
.child(text("toggle")),
)
}
/// An element removed with the focus inside it is left (the focus goes
/// to none), and the ref's next element hears the focus come in again.
#[test]
fn an_element_removed_with_the_focus_in_it_is_left() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
c.mount_root(&Root::new::<FocusRemount>(|| ()));
let batch = c.commit().unwrap();
let field = native_parent(&c, text_node(&batch, "field")).unwrap();
let toggle = native_parent(&c, text_node(&batch, "toggle")).unwrap();
c.set_states(field, FOCUSED);
let shown = texts(&c.commit().unwrap());
assert!(shown.contains(&"log in".into()), "{shown:?}");
// Removed while the focus is in it.
assert!(c.component_event(toggle, EventKind::Press, &EventPayload::None));
let shown = texts(&c.commit().unwrap());
assert!(c.key(field).is_err(), "released");
assert!(shown.contains(&"log in out".into()), "{shown:?}");
// A new element with the same ref; the focus comes into it.
assert!(c.component_event(toggle, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let field = native_parent(&c, text_node(&batch, "field")).unwrap();
c.set_states(field, FOCUSED);
let shown = texts(&c.commit().unwrap());
assert!(shown.contains(&"log in out in".into()), "{shown:?}");
// And out to none (a blur lets go at the frame).
c.set_states(field, 0);
assert!(c.commit().is_none());
c.run_frame(crate::time::now());
let shown = texts(&c.commit().unwrap());
assert!(shown.contains(&"log in out in out".into()), "{shown:?}");
}
#[derive(Clone, PartialEq, Props)]
struct AnchoredCornerProps {
corner: crate::element::Prop<Option<Slot>>,
#[prop(default)]
open: crate::element::Prop<bool>,
}
/// Gives its corner a ref and, while `open`, shows a 40 × 20 overlay
/// 4 points below what the corner draws, from its start (a popover's).
#[component]
fn AnchoredCorner(props: AnchoredCornerProps) -> impl IntoElement {
let anchor = element_ref();
view()
.child(props.corner.place(move |c| c.element_ref(&anchor)))
.child(when(
move || props.open.get(),
move || {
overlay()
.anchor_content(&anchor)
.placement(Placement::Bottom)
.align(Align::Start)
.offset(px(4.0))
.w(px(40.0))
.h(px(20.0))
.child(text("pop"))
},
))
}
/// Fills an anchored corner, 100 points down, with an 80 × 30 view
/// around a 50 × 10 box; a press on the root opens its overlay.
#[component]
fn AnchoredTop() -> impl IntoElement {
let open = signal(false);
view().pt(px(100.0)).on_press(move || open.set(true)).child(
anchored_corner().open(open).corner(
view()
.w(px(80.0))
.h(px(30.0))
.child(view().w(px(50.0)).h(px(10.0)).child(text("box"))),
),
)
}
/// The ref a component gives a slot a Rust view fills is the filled
/// element's, not its child's, and an overlay placed against what the
/// slot draws goes by the element's own box (its size, not its
/// content's), as it did while the ref was on the node around it.
#[test]
fn a_fills_element_takes_the_slots_ref_with_its_own_box() {
let mut c = core();
c.mount_root(&Root::new::<AnchoredTop>(|| ()));
let batch = c.commit().unwrap();
let top = root_host(&batch);
let inner = native_parent(&c, text_node(&batch, "box")).expect("placed");
let element = native_parent(&c, inner).expect("placed");
let holder = native_parent(&c, element).expect("in the node around the fill");
assert_eq!(
c.components.adopted.get(&element),
Some(&holder),
"the element takes the slot's props"
);
assert!(c.component_event(top, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let pop = native_parent(&c, text_node(&batch, "pop")).expect("shown");
// Below the element (0, 100, 80 × 30), not its 10-point box; 8
// points off the window's edge (the snap margin).
assert_eq!(frame_of(&batch, pop), Some(rect(8.0, 134.0, 40.0, 20.0)));
}
/// Rows of a list, each with a filled corner, a holder of a text and a
/// plaque.
#[component]
fn FilledRows() -> impl IntoElement {
view().flex_1().child(
virtual_list(200, move |at| {
let i = at.index();
view()
.h(px(40.0))
.child(
Corner::element(CornerProps::default())
.fill("corner", text(format!("r{i}"))),
)
.child(
Holder::element(HolderProps {
children: Children::default(),
})
.child(text(format!("h{i}"))),
)
.child(Plaque::element(PlaqueProps {}))
})
.estimated_item_size(px(40.0))
.flex_1(),
)
}
#[test]
fn list_rows_with_filled_slots_follow_their_rows() {
let mut c = core();
c.mount_root(&Root::new::<FilledRows>(|| ()));
let batch = c.commit().unwrap();
let list = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create {
id,
kind: ViewKind::Scroll,
} => Some(*id),
_ => None,
})
.expect("a list");
let mut shown: std::collections::HashMap<String, NodeId> = Default::default();
let record = |b: &MountBatch, shown: &mut std::collections::HashMap<String, NodeId>| {
for i in &b.items {
if let MountItem::Text { id, text, .. } = i {
shown.retain(|_, v| v != id);
shown.insert(text.text.clone(), *id);
}
}
};
record(&batch, &mut shown);
let mut sizes = Vec::new();
for step in 1..=12u32 {
let y = (step as f32 * 900.0) % 7000.0;
c.set_scroll_offset(list, point(px(0.0), px(y)), u32::MAX);
for _ in 0..3 {
if let Some(b) = c.commit() {
record(&b, &mut shown);
}
}
sizes.push((c.nodes.len(), c.components.instances.len()));
// Every r<i> shown is in the corner of the row showing h<i>.
for (t, &id) in &shown {
let Some(n) = t.strip_prefix('r') else {
continue;
};
if c.key(id).is_err() {
continue;
}
let Some(corner) = native_parent(&c, id) else {
continue;
};
let row = native_parent(&c, corner).expect("a corner in a row");
if let Some(&h) = shown.get(&format!("h{n}"))
&& c.key(h).is_ok()
{
let holder = native_parent(&c, h).unwrap();
assert_eq!(native_parent(&c, holder), Some(row), "{step}: {t} and h{n}");
}
}
}
assert!(
sizes
.windows(2)
.skip(2)
.all(|w| w[0].0.abs_diff(w[1].0) < 40),
"{sizes:?}"
);
assert_eq!(sizes[3].1, sizes[sizes.len() - 1].1, "{sizes:?}");
}
/// A chat of 50 messages of 60 pt, estimated at 170 pt.
#[component]
fn Chat() -> impl IntoElement {
messages(60.0)
}
/// The same chat, its newest message longer than the screen.
#[component]
fn LongChat() -> impl IntoElement {
messages(900.0)
}
fn messages(newest: f32) -> impl IntoElement {
view().flex_1().child(
virtual_list(50, move |at| {
let i = at.index();
text(format!("m{i}")).h(px(if i == 49 { newest } else { 60.0 }))
})
.estimated_item_size(px(170.0))
.initial_scroll_at_end()
.flex_1(),
)
}
/// Mounts `root`'s chat and follows its list as a platform would, the
/// offset clamped to the content: the texts of the first batch, and
/// where the list ends against where its content ends.
fn open_chat(root: &Root) -> (Vec<String>, f32, f32) {
let mut c = core();
c.mount_root(root);
let first = c.commit().unwrap();
let list = first
.items
.iter()
.find_map(|i| match i {
MountItem::Create {
id,
kind: ViewKind::Scroll,
} => Some(*id),
_ => None,
})
.expect("a list");
let texts = first
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.clone()),
_ => None,
})
.collect();
let (mut at, mut content) = (0.0_f32, 0.0_f32);
let mut apply = |b: &MountBatch| {
for item in &b.items {
let max = (content - 480.0).max(0.0);
match item {
MountItem::ScrollContent { id, size } if *id == list => {
content = size.height.0;
at = at.min((content - 480.0).max(0.0));
}
MountItem::Command {
id,
command: Command::ScrollTo { y, .. },
} if *id == list => at = y.0.clamp(0.0, max),
MountItem::ScrollBy { id, dy, .. } if *id == list => {
at = (at + dy.0).clamp(0.0, max);
}
_ => {}
}
}
};
apply(&first);
while let Some(batch) = c.commit() {
apply(&batch);
}
(texts, at, content - 480.0)
}
#[test]
fn a_list_opens_at_its_end_and_stays_there_as_rows_measure() {
// Rows shorter than estimated shrink the content under the jump;
// a newest row longer than the screen opens at its end, not its top.
for root in [Root::new::<Chat>(|| ()), Root::new::<LongChat>(|| ())] {
let (texts, at, end) = open_chat(&root);
// The first frame shows the newest message, not the first ones.
assert!(texts.contains(&"m49".to_string()), "{texts:?}");
assert!(!texts.contains(&"m0".to_string()), "{texts:?}");
assert_eq!(at, end);
assert_ne!(end, 50.0 * 170.0 - 480.0, "rows were measured");
}
}
/// A text as its root.
#[derive(Default)]
struct Lit;
#[derive(Clone, PartialEq, Props)]
struct LitProps {}
impl Component for Lit {
type Props = LitProps;
type Event = NoEvent;
fn view(_: LitProps, _: Scope<NoEvent>) -> impl IntoElement {
text("lit").p_1()
}
}
/// Gives a lit text an animated opacity, an inline style and insets a
/// press changes; and a plaque (rooted in a counter) an inline style.
#[derive(Default)]
struct Lighting;
#[derive(Clone, PartialEq, Props)]
struct LightingProps {}
impl Component for Lighting {
type Props = LightingProps;
type Event = NoEvent;
fn view(_: LightingProps, _: Scope<NoEvent>) -> impl IntoElement {
let v = animated_value(0.5);
let wide = signal(false);
let red = crate::element::Style::default().with(
crate::StyleKey::BackgroundColor,
crate::PropertyValue::Color(Some(crate::Color::rgba(255, 0, 0, 255))),
);
view()
.on_press(move || wide.update(|w| *w = !*w))
.child(
Lit::element(LitProps {})
.bind_opacity(&v)
.inline_style(red.clone())
.inset_padding(move || {
EdgeInsets::all(px(if wide.get() { 8.0 } else { 4.0 }))
}),
)
.child(Plaque::element(PlaqueProps {}).inline_style(red))
}
}
#[test]
fn what_a_view_gives_a_component_element_goes_on_its_root() {
let mut c = core();
c.mount_root(&Root::new::<Lighting>(|| LightingProps {}));
let batch = c.commit().unwrap();
let root = root_host(&batch);
let lit = text_node(&batch, "lit");
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::AnimationBindings { id, .. } if *id == lit)),
"the opacity is bound on the text: {:?}",
batch.items
);
let red = crate::Color::rgba(0xff, 0, 0, 0xff);
assert_eq!(
view_style_of(&batch, lit).map(|s| s.background_color),
Some(red)
);
let insets = |c: &Core<FakeEngine>, id| {
let key = c.key(id).unwrap();
c.nodes[key as usize]
.insets
.as_deref()
.copied()
.unwrap_or_default()[0]
};
assert_eq!(insets(&c, lit), EdgeInsets::all(px(4.0)));
// On a rooted component's host too, over the counter's own style.
let plaque = native_children(&c, root)[1];
assert_eq!(
view_style_of(&batch, plaque).map(|s| s.background_color),
Some(red)
);
// A bound inset follows.
assert!(c.component_event(root, EventKind::Press, &EventPayload::None));
c.commit();
assert_eq!(insets(&c, lit), EdgeInsets::all(px(8.0)));
}
/// A count its API reads.
#[derive(Default)]
struct Dial;
#[derive(Clone, Copy)]
struct DialApi {
at: crate::element::Signal<i32>,
}
#[crate::element::methods]
impl DialApi {
/// Where it is.
pub(crate) fn at(&self) -> i32 {
self.at.get_untracked()
}
}
impl Component for Dial {
type Props = ();
type Event = NoEvent;
const METHODS: crate::element::Methods = crate::element::Methods::of::<DialApi>();
fn view(_: (), cx: Scope<NoEvent>) -> impl IntoElement {
let at = signal(7);
cx.methods(DialApi { at });
text(move || format!("at {}", at.get()))
}
}
thread_local! {
static DIAL: Cell<Option<crate::element::ComponentRef<Dial>>> = const { Cell::new(None) };
}
#[derive(Clone, PartialEq, Props)]
struct DialPanelProps {
rooted: bool,
}
/// A dial with a ref, as its view's root or inside a view.
#[component]
fn DialPanel(props: DialPanelProps) -> impl IntoElement {
let handle = component_ref::<Dial>();
DIAL.with(|d| d.set(Some(handle)));
let el = Dial::element(()).component_ref(&handle);
if props.rooted {
el.into_element()
} else {
view().child(el).into_element()
}
}
#[test]
fn the_api_of_a_component_rooted_in_another_is_its_refs() {
for rooted in [false, true] {
let mut c = core();
c.mount_root(&Root::new::<DialPanel>(move || DialPanelProps { rooted }));
let _ = c.commit().unwrap();
let dial = DIAL.with(Cell::get).unwrap();
let _entered = c.components.runtime.enter();
let at = dial.api::<DialApi>().map(|api| api.at());
assert_eq!(at, Some(7), "rooted: {rooted}");
}
}
/// A view passing content to nested components: a pocket's lazy
/// children and a region in a holder's; a press opens and closes.
#[derive(Default)]
struct Wardrobe;
#[derive(Clone, PartialEq, Props)]
struct WardrobeProps {}
impl Component for Wardrobe {
type Props = WardrobeProps;
type Event = NoEvent;
fn view(_: WardrobeProps, _: Scope<NoEvent>) -> impl IntoElement {
let open = signal(false);
view()
.on_press(move |_: &()| open.update(|o| *o = !*o))
.child(
Pocket::element(PocketProps {
open: open.into(),
children: Children::default(),
})
.child(Fresh::element(FreshProps {})),
)
.child(
Holder::element(HolderProps {
children: Children::default(),
})
.child(text("before"))
.child(when(open, || text("open")))
.child(text("after")),
)
}
}
#[test]
fn a_view_passes_lazy_children_and_regions_to_nested_components() {
let mut c = core();
c.mount_root(&Root::new::<Wardrobe>(|| WardrobeProps {}));
let batch = c.commit().unwrap();
let mut shown = texts(&batch);
shown.sort();
assert_eq!(shown, ["after", "before"]);
assert_eq!(FRESH.with(Cell::get), 0, "closed: not made");
let host = root_host(&batch);
// Opened: the content is made, the region's text placed between.
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let mut shown = texts(&batch);
shown.sort();
assert_eq!(shown, ["fresh 1", "open"]);
// The region's text is the holder's middle child.
let holder = c
.components
.instances
.values()
.find(|i| i.js_children.len() == 3)
.expect("the holder has three children");
assert_eq!(holder.js_children[1], text_node(&batch, "open"));
// Closed, then opened again: made afresh.
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
c.commit();
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let mut shown = texts(&c.commit().unwrap());
shown.sort();
assert_eq!(shown, ["fresh 2", "open"]);
let events = js_events(&mut c);
assert!(events.is_empty(), "nothing for JS: {events:?}");
}
/// A text as its root: a count, bumped by a press.
#[derive(Default)]
struct Tally;
#[derive(Clone, PartialEq, Props)]
struct TallyProps {}
impl Component for Tally {
type Props = TallyProps;
type Event = NoEvent;
fn view(_: TallyProps, _: Scope<NoEvent>) -> impl IntoElement {
let n = signal(0);
text(move || format!("tally {}", n.get())).on_press(move |_: &()| n.update(|n| *n += 1))
}
}
/// A scroll view as its root.
#[derive(Default)]
struct Scroller;
#[derive(Clone, PartialEq, Props)]
struct ScrollerProps {}
impl Component for Scroller {
type Props = ScrollerProps;
type Event = NoEvent;
fn view(_: ScrollerProps, _: Scope<NoEvent>) -> impl IntoElement {
scroll().child(text("inside"))
}
}
#[test]
fn a_views_root_can_be_any_element() {
let mut c = core();
c.mount_root(&Root::new::<Tally>(|| TallyProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
assert!(
batch.items.iter().any(|i| matches!(
i,
MountItem::Create { id, kind: crate::ViewKind::Text } if *id == host
)),
"the host is the text: {:?}",
batch.items
);
assert_eq!(
batch
.items
.iter()
.filter(|i| matches!(i, MountItem::Create { id, .. } if *id == host))
.count(),
1,
"made once"
);
assert_eq!(texts(&batch), ["tally 0"]);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["tally 1"]);
let mut c = core();
c.mount_root(&Root::new::<Scroller>(|| ScrollerProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
assert!(
batch.items.iter().any(|i| matches!(
i,
MountItem::Create { id, kind: crate::ViewKind::Scroll } if *id == host
)),
"the host is the scroll view: {:?}",
batch.items
);
assert_eq!(texts(&batch), ["inside"]);
}
/// Dims a nested component (its host) with a bound style; a press
/// flips it.
#[derive(Default)]
struct Dimmer;
#[derive(Clone, PartialEq, Props)]
struct DimmerProps {}
impl Component for Dimmer {
type Props = DimmerProps;
type Event = NoEvent;
fn view(_: DimmerProps, _: Scope<NoEvent>) -> impl IntoElement {
let dim = signal(false);
view()
.on_press(move |_: &()| dim.update(|d| *d = !*d))
.child(
Holder::element(HolderProps {
children: Children::default(),
})
.w(px(10.0))
.opacity(move || if dim.get() { 0.5_f32 } else { 1.0 }),
)
}
}
#[test]
fn a_views_bound_styles_on_a_nested_component_are_a_binding() {
let mut c = core();
c.mount_root(&Root::new::<Dimmer>(|| DimmerProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let dimmed = batch.items.iter().find_map(|i| match i {
MountItem::ViewStyle { id, style } if style.opacity == 0.5 => Some(*id),
_ => None,
});
let nested = dimmed.expect("the nested host is dimmed");
assert_ne!(nested, host);
assert_eq!(creates(&batch), 0);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(view_style_of(&batch, nested).map(|s| s.opacity), Some(1.0));
}
/// Fades its edges with a bound mask; presses turn, remove and restore it.
#[derive(Default)]
struct Faded;
#[derive(Clone, PartialEq, Props)]
struct FadedProps {}
impl Component for Faded {
type Props = FadedProps;
type Event = NoEvent;
fn view(_: FadedProps, _: Scope<NoEvent>) -> impl IntoElement {
let phase = signal(0);
let angle = signal(deg(90.0));
view()
.on_press(move |_: &()| {
phase.update(|n| *n = (*n + 1) % 3);
angle.set(if phase.get() == 0 {
deg(90.0)
} else {
deg(180.0)
});
})
.w(px(10.0))
.bg_linear(deg(180.0))
.gradient_from(white())
.gradient_to(black())
.mask_linear(angle, move || {
if phase.get() == 2 {
Vec::new()
} else {
vec![
transparent_black().into(),
black().into(),
transparent_black().into(),
]
}
})
.style_when(move || phase.get() == 2, |s| s.mask_none())
}
}
#[test]
fn a_bound_mask_is_mounted_removed_and_restored() {
let mut c = core();
c.mount_root(&Root::new::<Faded>(|| FadedProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
let masks = |batch: &MountBatch| {
view_style_of(batch, host)
.and_then(|s| s.effects)
.map(|e| e.mask_images.clone())
};
let mounted = masks(&batch).expect("the mask is mounted");
assert_eq!(mounted.len(), 1);
assert_eq!(
mounted[0].kind,
crate::effects::GradientKind::Linear { angle: deg(90.0) }
);
assert_eq!(
mounted[0].stops.iter().map(|s| s.color).collect::<Vec<_>>(),
[Color::TRANSPARENT, Color::from(black()), Color::TRANSPARENT]
);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let turned = masks(&batch).unwrap();
assert_eq!(
turned[0].kind,
crate::effects::GradientKind::Linear { angle: deg(180.0) }
);
assert_eq!(turned[0].stops, mounted[0].stops);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(masks(&batch).is_none_or(|m| m.is_empty()));
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(masks(&batch), Some(mounted));
let effects = view_style_of(&batch, host).unwrap().effects.unwrap();
assert_eq!(effects.background_images.len(), 1);
}
/// Counts back presses while its view lives.
#[derive(Default)]
struct Catcher;
#[derive(Clone, PartialEq, Props)]
struct CatcherProps {}
impl Component for Catcher {
type Props = CatcherProps;
type Event = NoEvent;
fn view(_: CatcherProps, _: Scope<NoEvent>) -> impl IntoElement {
let caught = signal(0);
on_back_press(move || {
caught.update(|n| *n += 1);
true
});
view().child(text(move || format!("caught {}", caught.get())))
}
}
#[test]
fn a_views_back_press_listener_hears_the_back_button() {
let mut c = core();
c.mount_root(&Root::new::<Catcher>(|| CatcherProps {}));
assert_eq!(texts(&c.commit().unwrap()), ["caught 0"]);
assert!(c.component_event(ROOT_ID, EventKind::BackPress, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["caught 1"]);
}
/// Shows the back gesture's last step while its view lives.
#[derive(Default)]
struct Follower;
#[derive(Clone, PartialEq, Props)]
struct FollowerProps {}
impl Component for Follower {
type Props = FollowerProps;
type Event = NoEvent;
fn view(_: FollowerProps, _: Scope<NoEvent>) -> impl IntoElement {
let step = signal(String::from("none"));
on_back_progress(move |e: &BackProgressEvent| {
let edge = match e.edge {
Some(PanEdge::Left) => "left",
Some(PanEdge::Right) => "right",
_ => "-",
};
step.set(format!("{} {} {edge}", e.phase.name(), e.progress.0));
});
view().child(text(move || step.get()))
}
}
fn back_step(phase: BackPhase, progress: f32, edge: Option<PanEdge>) -> EventPayload {
BackProgressEvent::new(phase, Percentage(progress), edge).payload()
}
#[test]
fn a_views_back_progress_listener_follows_the_back_gesture() {
let mut c = core();
c.mount_root(&Root::new::<Follower>(|| FollowerProps {}));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["none"]);
// The root listens, so the platform hands the gesture to the app.
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Events { id: ROOT_ID, events } if events.contains(EventKind::BackProgress)
)));
for (phase, progress, shown) in [
(BackPhase::Start, 0.0, "start 0 left"),
(BackPhase::Move, 0.25, "move 0.25 left"),
(BackPhase::Move, 0.5, "move 0.5 left"),
(BackPhase::End, 0.5, "end 0.5 left"),
] {
let step = back_step(phase, progress, Some(PanEdge::Left));
// Without JS listening, the views took it.
assert!(c.component_event(ROOT_ID, EventKind::BackProgress, &step));
assert_eq!(texts(&c.commit().unwrap()), [shown]);
}
// A step outside a gesture (a move after its end) is dropped.
let late = back_step(BackPhase::Move, 0.75, Some(PanEdge::Left));
assert!(c.component_event(ROOT_ID, EventKind::BackProgress, &late));
assert!(c.commit().is_none_or(|b| texts(&b).is_empty()));
// A cancelled gesture from the right edge.
for (phase, progress, shown) in [
(BackPhase::Start, 0.0, "start 0 right"),
(BackPhase::Cancel, 0.0, "cancel 0 right"),
] {
let step = back_step(phase, progress, Some(PanEdge::Right));
assert!(c.component_event(ROOT_ID, EventKind::BackProgress, &step));
assert_eq!(texts(&c.commit().unwrap()), [shown]);
}
}
#[test]
fn js_back_progress_listeners_hear_the_gesture_after_the_views() {
let mut c = core();
c.mount_root(&Root::new::<Follower>(|| FollowerProps {}));
c.commit();
c.apply(Op::Listen {
id: ROOT_ID,
event: EventKind::BackProgress,
enabled: true,
})
.unwrap();
let start = back_step(BackPhase::Start, 0.0, None);
// The views heard it, then JS's listeners do.
assert!(!c.component_event(ROOT_ID, EventKind::BackProgress, &start));
assert_eq!(texts(&c.commit().unwrap()), ["start 0 -"]);
}
thread_local! {
/// What the quitter's listener did.
static QUIT_LOG: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Ready on its second poll: work that waits for something.
#[derive(Default)]
struct YieldOnce(bool);
impl std::future::Future for YieldOnce {
type Output = ();
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<()> {
if std::mem::replace(&mut self.0, true) {
std::task::Poll::Ready(())
} else {
cx.waker().wake_by_ref();
std::task::Poll::Pending
}
}
}
/// Saves as the app quits.
#[derive(Default)]
struct Quitter;
#[derive(Clone, PartialEq, Props)]
struct QuitterProps {}
impl Component for Quitter {
type Props = QuitterProps;
type Event = NoEvent;
fn view(_: QuitterProps, _: Scope<NoEvent>) -> impl IntoElement {
crate::element::desktop::on_app_quit(|| {
QUIT_LOG.with(|log| log.borrow_mut().push("started"));
async {
YieldOnce::default().await;
QUIT_LOG.with(|log| log.borrow_mut().push("saved"));
}
});
view()
}
}
#[test]
fn quit_listeners_run_their_work_as_the_app_quits() {
let mut c = core();
assert!(!c.has_quit_listeners());
c.mount_root(&Root::new::<Quitter>(|| QuitterProps {}));
c.commit();
assert!(c.has_quit_listeners());
assert!(QUIT_LOG.with(|log| log.borrow().is_empty()));
assert!(c.start_quit());
assert_eq!(QUIT_LOG.with(|log| log.borrow().clone()), ["started"]);
c.run_component_tasks();
assert_eq!(
QUIT_LOG.with(|log| log.borrow().clone()),
["started", "saved"]
);
assert!(!c.quit_pending());
}
/// Its view panics as it is made.
#[derive(Default)]
struct Broken;
#[derive(Clone, PartialEq, Props)]
struct BrokenProps {}
impl Component for Broken {
type Props = BrokenProps;
type Event = NoEvent;
fn view(_: BrokenProps, _: Scope<NoEvent>) -> impl IntoElement {
panic!("no view");
#[allow(unreachable_code)]
view()
}
}
/// A counter whose text panics past 1, and a broken component, each
/// under an error boundary.
#[derive(Default)]
struct Guarded;
#[derive(Clone, PartialEq, Props)]
struct GuardedProps {}
impl Component for Guarded {
type Props = GuardedProps;
type Event = NoEvent;
fn view(_: GuardedProps, _: Scope<NoEvent>) -> impl IntoElement {
let n = signal(0);
view()
.on_press(move |_: &()| n.update(|n| *n += 1))
.child(catch_error(
move || {
text(move || {
assert!(n.get() < 2, "too many");
format!("n {}", n.get())
})
},
|e, _| text(format!("failed: {}", e.message)),
))
.child(catch_error(
|| Broken::element(BrokenProps {}),
|e, _| text(format!("{} failed", e.component)),
))
}
}
#[test]
fn error_boundaries_show_their_fallback() {
let mut c = core();
c.mount_root(&Root::new::<Guarded>(|| GuardedProps {}));
let batch = c.commit().unwrap();
let shown = texts(&batch);
assert!(shown.contains(&"n 0".to_owned()), "{shown:?}");
assert!(
shown.iter().any(|t| t.ends_with("Broken failed")),
"{shown:?}"
);
let host = root_host(&batch);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["n 1"]);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(texts(&c.commit().unwrap()), ["failed: too many"]);
}
/// A large component with one value changing often: 300 rows of
/// static content and a counter.
#[component]
fn Ticker() -> impl IntoElement {
let tick = signal(0_u32);
view()
.on_press(move |_: &()| tick.update(|t| *t += 1))
.child(text(move || format!("tick {}", tick.get())))
.children((0..300).map(|i| {
view()
.flex_row()
.p_2()
.gap_2()
.child(view().size(px(20.0)).bg(rgb(0x3366ff)))
.child(text(format!("row {i}")).text_sm())
}))
}
/// `cargo test --release -p nsh-core bench_view_tick -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_view_tick() {
let mut c = core();
c.mount_root(&Root::new::<Ticker>(|| ()));
let host = root_host(&c.commit().unwrap());
let n = 2000;
let (mut event, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
let mut items = 0;
for _ in 0..n {
let start = std::time::Instant::now();
c.component_event(host, EventKind::Press, &EventPayload::None);
let mid = std::time::Instant::now();
items += c.commit().map_or(0, |b| b.items.len());
event += mid - start;
commit += mid.elapsed();
}
eprintln!(
"view tick: {:?} per event, {:?} per commit, {} mount items",
event / n,
commit / n,
items / n as usize
);
}
/// How many rows [`Board`] shows, and how many of its values change
/// on each tick (the first cell of as many rows).
const BOARD_ROWS: usize = 80;
const BOARD_TICKING: usize = 40;
#[derive(Clone, Copy, PartialEq, Props)]
struct BoardProps {
/// Its cells have a size of their own: what their text says moves
/// nothing around them.
fixed: bool,
/// Each tick changes how wide the changing values are (a sign comes
/// and goes); otherwise they keep their width, but for the rare
/// digit a price gains (the tests' text engine gives every
/// character one width, as tabular figures have).
widening: bool,
}
/// A page of high-frequency updates, a quote board: 80 rows of a
/// mark and five cells (about a thousand nodes), the first cells of 40
/// rows changing together on each press.
#[component]
fn Board(props: BoardProps) -> impl IntoElement {
let (fixed, widening) = (props.fixed, props.widening);
let ticks: Vec<Signal<u32>> = (0..BOARD_TICKING).map(|_| signal(0)).collect();
let pressed = ticks.clone();
let cell = move |content: Text| {
let cell = view().p_1().child(content);
if fixed {
cell.w(px(56.0)).h(px(24.0))
} else {
cell
}
};
view()
.on_press(move |_: &()| {
batch(|| {
for tick in &pressed {
tick.update(|t| *t += 7);
}
})
})
.children((0..BOARD_ROWS).map(|row| {
let first = match ticks.get(row) {
Some(&tick) => text(move || {
let t = tick.get();
let sign = if widening && t % 2 == 1 { "+" } else { "" };
format!("{sign}{}.{:02}", 9 + t / 3, t % 100)
}),
None => text(format!("{row}.00")),
};
view()
.flex_row()
.items_center()
.p_1()
.gap_2()
.child(view().size(px(12.0)).bg(rgb(0x22aa66)))
.child(cell(first))
.children((1..5).map(move |col| cell(text(format!("r{row} c{col}")))))
}))
}
/// `cargo test --release -p nsh-core bench_high_frequency -- --ignored --nocapture`
///
/// The cost of a commit when many values of a large page change at
/// once and often: [`Board`] with fixed cells, and with cells that
/// take their text's size, the values keeping their widths or not.
#[test]
#[ignore]
fn bench_high_frequency() {
for (fixed, widening, label) in [
(true, false, "fixed cells"),
(false, false, "content-sized cells, same widths"),
(false, true, "content-sized cells, new widths"),
] {
let mut c = core();
c.mount_root(&Root::new::<Board>(move || BoardProps { fixed, widening }));
let first = c.commit().unwrap();
let nodes = first
.items
.iter()
.filter(|i| matches!(i, MountItem::Create { .. }))
.count();
let host = root_host(&first);
let n = 2000;
let (mut event, mut commit) = (std::time::Duration::ZERO, std::time::Duration::ZERO);
let mut items = 0;
for _ in 0..n {
let start = std::time::Instant::now();
c.component_event(host, EventKind::Press, &EventPayload::None);
let mid = std::time::Instant::now();
items += c.commit().map_or(0, |b| b.items.len());
event += mid - start;
commit += mid.elapsed();
}
eprintln!(
"high frequency ({label}, {nodes} views, {BOARD_TICKING} values a tick): \
{:?} per event, {:?} per commit, {} mount items",
event / n,
commit / n,
items / n as usize
);
}
}
#[derive(Clone, Copy, PartialEq, Props)]
struct ShownProps {
value: crate::element::Prop<SharedString>,
}
/// Shows its prop.
#[component]
fn Shown(props: ShownProps) -> impl IntoElement {
text(props.value)
}
/// Passes `Shown` a binding, then, from the second press, a value: its
/// region makes the element again, a new `Shown`.
#[component]
fn Passer() -> impl IntoElement {
let n = signal(0);
let fixed = signal(false);
view()
.on_press(move |_: &()| {
if n.get_untracked() == 1 {
fixed.set(true);
}
n.update(|n| *n += 1);
})
.child(dynamic(move || {
let value: crate::element::Prop<SharedString> = if fixed.get() {
"fixed".into()
} else {
crate::element::Prop::bind(move || format!("n {}", n.get()).into())
};
shown().value(value)
}))
}
#[test]
fn a_prop_follows_a_binding_and_a_region_made_again_makes_a_new_component() {
let mut c = core();
c.mount_root(&Root::new::<Passer>(|| ()));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["n 0"]);
let host = root_host(&batch);
let press = |c: &mut Core<FakeEngine>| {
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
c.commit().map(|b| texts(&b)).unwrap_or_default()
};
assert_eq!(press(&mut c), ["n 1"]);
assert_eq!(press(&mut c), ["fixed"]);
// The old `Shown` went with its binding.
assert!(press(&mut c).is_empty());
}
thread_local! {
static REBUILT_PROP_OWNER: Cell<Option<Owner>> = const { Cell::new(None) };
}
#[component]
fn RebuiltLabel(props: ShownProps) -> impl IntoElement {
REBUILT_PROP_OWNER.with(|owner| owner.set(Some(Owner::current())));
text(props.value)
}
#[component]
fn RebuiltProp() -> impl IntoElement {
let n = signal(0);
view()
.on_press(move |_: &()| n.update(|n| *n += 1))
.child(dynamic(move || {
let value = n.get();
rebuilt_label().value(move || format!("{value}: {}", n.get()))
}))
}
#[test]
fn rebuilding_a_region_retires_its_components_property_bindings() {
let mut c = core();
c.mount_root(&Root::new::<RebuiltProp>(|| ()));
let batch = c.commit().unwrap();
assert_eq!(texts(&batch), ["0: 0"]);
let host = root_host(&batch);
for n in 1..=3 {
let previous = REBUILT_PROP_OWNER.with(Cell::get).unwrap();
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
{
let _entered = c.components.runtime.enter();
assert!(
!previous.is_live(),
"the old component must retire before the core commits its replacement"
);
}
assert!(c.components.runtime.take_failures().is_empty());
let batch = c.commit().expect("the rebuilt component renders");
assert_eq!(texts(&batch), [format!("{n}: {n}")]);
}
}
/// Counts Mod+K while a branch is shown; a press hides the branch.
#[component]
fn Shortcuts() -> impl IntoElement {
let count = signal(0);
let shown = signal(true);
view()
.on_press(move |_: &()| shown.set(false))
.child(text(move || format!("k {}", count.get())))
.child(when(shown, move || {
on_key("mod+k", move |_| count.update(|c| *c += 1));
view()
}))
}
#[test]
fn a_views_shortcuts_join_jss_and_run_in_the_core() {
use crate::keymap::{KeyBinding, Keymap, Keystroke, When};
let tables = |batch: &MountBatch| -> Vec<Vec<u32>> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Keymap(k) => Some(k.bindings().iter().map(|b| b.id).collect()),
_ => None,
})
.collect()
};
let mut c = core();
c.mount_root(&Root::new::<Shortcuts>(|| ()));
let batch = c.commit().unwrap();
let host = root_host(&batch);
let table = tables(&batch);
let [ours] = table.last().expect("a table").as_slice() else {
panic!("{table:?}");
};
let ours = *ours;
assert!(ours >= crate::element::keys::FIRST_ID);
// JS's table joins it: JS's first, then the views'.
let js = KeyBinding::new(
1,
Keystroke::parse_with("mod+j", true).unwrap(),
When::Auto,
false,
);
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::Keymap(std::sync::Arc::new(Keymap::new(vec![js]))),
}],
);
assert_eq!(tables(&c.commit().unwrap()), [vec![1, ours]]);
// The view's runs here; JS's goes to JS.
let key = |id: u32| EventPayload::Value(crate::PayloadValue::Number(id as f64));
assert!(c.component_event(ROOT_ID, EventKind::KeyCommand, &key(ours)));
assert_eq!(texts(&c.commit().unwrap()), ["k 1"]);
assert!(!c.component_event(ROOT_ID, EventKind::KeyCommand, &key(1)));
// The binding goes with its owner.
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(tables(&c.commit().unwrap()), [vec![1]]);
}
#[test]
fn jss_shortcuts_over_focused_come_after_the_views() {
use crate::keymap::{KeyBinding, KeyMatch, Keymap, Keystroke, When};
let mod_k = Keystroke::parse_with("mod+k", true).unwrap();
let tables = |batch: &MountBatch| -> Vec<std::sync::Arc<Keymap>> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Keymap(k) => Some(k.clone()),
_ => None,
})
.collect()
};
let mut c = core();
c.mount_root(&Root::new::<Shortcuts>(|| ()));
let batch = c.commit().unwrap();
let ours = tables(&batch).last().expect("a table").bindings()[0].id;
// JS binds the view's mod+k twice: plainly (1) and over the views (2).
let plain = KeyBinding::new(1, mod_k, When::Auto, false);
let over = KeyBinding::new(2, mod_k, When::Auto, false).over_focused(true);
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::Keymap(std::sync::Arc::new(Keymap::new(vec![over, plain]))),
}],
);
let batch = c.commit().unwrap();
let table = tables(&batch).pop().expect("a table");
let ids: Vec<u32> = table.bindings().iter().map(|b| b.id).collect();
// The plain one before the view's, the one over them after.
assert_eq!(ids, [1, ours, 2]);
assert_eq!(table.find(mod_k, false, false), KeyMatch::Fire(2));
// Without it, the view's wins as before.
apply(
&mut c,
vec![Op::SetProp {
id: ROOT_ID,
prop: Prop::Keymap(std::sync::Arc::new(Keymap::new(vec![plain]))),
}],
);
let table = tables(&c.commit().unwrap()).pop().expect("a table");
assert_eq!(table.find(mod_k, false, false), KeyMatch::Fire(ours));
}
#[test]
fn jss_shortcuts_bound_before_any_view_stay_beside_the_views() {
use crate::keymap::{KeyBinding, Keymap, Keystroke, When};
let tables = |batch: &MountBatch| -> Vec<Vec<u32>> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Keymap(k) => Some(k.bindings().iter().map(|b| b.id).collect()),
_ => None,
})
.collect()
};
let listening = |c: &Core<FakeEngine>| {
c.nodes[c.root as usize]
.events
.contains(EventKind::KeyCommand)
};
let mut c = core();
let js = KeyBinding::new(
1,
Keystroke::parse_with("escape", true).unwrap(),
When::Always,
false,
);
apply(
&mut c,
vec![
Op::SetProp {
id: ROOT_ID,
prop: Prop::Keymap(std::sync::Arc::new(Keymap::new(vec![js]))),
},
Op::Listen {
id: ROOT_ID,
event: EventKind::KeyCommand,
enabled: true,
},
],
);
assert_eq!(tables(&c.commit().unwrap()), [vec![1]]);
c.mount_root(&Root::new::<Shortcuts>(|| ()));
let batch = c.commit().unwrap();
let host = root_host(&batch);
let table = tables(&batch);
let [js, ours] = table.last().expect("a table").as_slice() else {
panic!("{table:?}");
};
assert_eq!(*js, 1);
assert!(*ours >= crate::element::keys::FIRST_ID);
assert!(listening(&c));
// The view's binding goes; JS's stays, still listened to.
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
assert_eq!(tables(&c.commit().unwrap()), [vec![1]]);
assert!(listening(&c));
}
/// A pressable box with the pointing hand.
#[component]
fn Pointing() -> impl IntoElement {
view().size_10().cursor_pointer()
}
#[test]
fn a_typed_cursor_reaches_the_view() {
let mut c = core();
c.mount_root(&Root::new::<Pointing>(|| ()));
let batch = c.commit().unwrap();
assert!(
batch.items.iter().any(|i| matches!(
i,
MountItem::ViewStyle { style, .. } if style.cursor == crate::Cursor::Pointer
)),
"{:#?}",
batch.items
);
}
/// A leaf in a region of its own.
#[component]
fn Leafy() -> impl IntoElement {
view().child(dynamic(|| text("leaf")))
}
/// Shows a `Leafy` until pressed.
#[component]
fn Branch() -> impl IntoElement {
let shown = signal(true);
view()
.on_press(move |_: &()| shown.set(false))
.child(when(shown, leafy))
}
#[test]
fn a_released_view_releases_what_its_regions_made() {
let mut c = core();
c.mount_root(&Root::new::<Branch>(|| ()));
let batch = c.commit().unwrap();
let leaf = text_node(&batch, "leaf");
let host = root_host(&batch);
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == leaf)),
"{:?}",
batch.items
);
}
/// A download's progress: a range for screen readers that follows the
/// app's value, and none while it is indeterminate.
#[derive(Default)]
struct Download;
#[derive(Clone, PartialEq, Props)]
struct DownloadProps {}
impl Component for Download {
type Props = DownloadProps;
type Event = NoEvent;
fn view(_: DownloadProps, _: Scope<NoEvent>) -> impl IntoElement {
let now = signal(Some(40.0_f32));
view()
.size_10()
.accessible(true)
.role(crate::AccessibilityRole::Progressbar)
.accessibility_value(move || {
Some(crate::AccessibilityValue {
min: Some(0.0),
max: Some(100.0),
now: now.get(),
text: None,
})
})
.on_press(move || now.set(now.get().map_or(Some(0.0), |_| None)))
}
}
/// Cells that show a code a text field tells screen readers already:
/// hidden from them until pressed.
#[derive(Default)]
struct Cells;
#[derive(Clone, PartialEq, Props)]
struct CellsProps {}
impl Component for Cells {
type Props = CellsProps;
type Event = NoEvent;
fn view(_: CellsProps, _: Scope<NoEvent>) -> impl IntoElement {
let hidden = signal(true);
view()
.size_10()
.test_id("cells")
.accessibility_elements_hidden(hidden)
.on_press(move || hidden.set(false))
.child(text("4"))
}
}
/// A row whose custom action is named in the interface's language,
/// which a press switches.
#[derive(Default)]
struct Row;
#[derive(Clone, PartialEq, Props)]
struct RowProps {}
impl Component for Row {
type Props = RowProps;
type Event = NoEvent;
fn view(_: RowProps, _: Scope<NoEvent>) -> impl IntoElement {
let chinese = signal(false);
view()
.size_10()
.test_id("row")
.accessibility_actions(move || {
vec![crate::AccessibilityActionDef {
name: "delete".into(),
label: Some(if chinese.get() { "删除" } else { "Delete" }.into()),
}]
})
.on_press(move || chinese.set(!chinese.get()))
}
}
#[test]
fn an_elements_accessibility_actions_follow_their_signals_in_place() {
let mut c = core();
c.mount_root(&Root::new::<Row>(|| RowProps {}));
let batch = c.commit().unwrap();
let actions = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some("row") => {
Some((*id, props.accessibility.actions.clone()))
}
_ => None,
})
};
let action = |label: &str| crate::AccessibilityActionDef {
name: "delete".into(),
label: Some(label.into()),
};
let (id, first) = actions(&batch).expect("the row's props");
assert_eq!(first, vec![action("Delete")]);
assert!(c.component_event(id, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
// The same view, renamed: nothing is created or removed, so the
// screen reader's focus stays on it.
assert_eq!(actions(&batch), Some((id, vec![action("删除")])));
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Create { .. } | MountItem::Remove { .. })),
"{:?}",
batch.items
);
}
#[test]
fn an_element_hides_from_screen_readers_while_its_signal_holds() {
let mut c = core();
c.mount_root(&Root::new::<Cells>(|| CellsProps {}));
let batch = c.commit().unwrap();
let hidden = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some("cells") => {
Some((*id, props.accessibility.hidden))
}
_ => None,
})
};
let (id, first) = hidden(&batch).expect("the cells' props");
assert!(first);
assert!(c.component_event(id, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(hidden(&batch), Some((id, false)));
}
#[test]
fn an_elements_accessibility_value_follows_its_signals() {
let mut c = core();
c.mount_root(&Root::new::<Download>(|| DownloadProps {}));
let batch = c.commit().unwrap();
let value = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::ViewProps { id, props }
if props.accessibility.role == crate::AccessibilityRole::Progressbar =>
{
Some((*id, props.accessibility.value.clone()))
}
_ => None,
})
};
let (id, first) = value(&batch).expect("the progress bar's props");
let range = |now| crate::AccessibilityValue {
min: Some(0.0),
max: Some(100.0),
now,
text: None,
};
assert_eq!(first, Some(range(Some(40.0))));
assert!(c.component_event(id, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(value(&batch).map(|(_, v)| v), Some(Some(range(None))));
assert!(c.component_event(id, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert_eq!(value(&batch).map(|(_, v)| v), Some(Some(range(Some(0.0)))));
}
}
mod rust_desktop {
use std::cell::Cell;
use super::*;
use crate::{
desktop::{DesktopCommand, TitleBarOptions, TitleBarStyle, WindowAttributes, WindowEvent},
element::{
Root,
desktop::{current_window, quit, restart, title_bar, window},
},
geometry::{Edges, Points},
prelude::*,
};
thread_local! {
static DRAG: Cell<Option<Signal<bool>>> = const {Cell::new(None)};
static READS: Cell<u32> = const {Cell::new(0)};
}
#[component]
fn Chrome() -> impl IntoElement {
window().id("main").title("Chrome").content(chrome_body)
}
#[component]
fn ChromeBody() -> impl IntoElement {
let window = current_window();
window.set(WindowAttributes {
title_bar: Some(TitleBarOptions {
style: TitleBarStyle::Hidden,
height: Some(px(42.0)),
..Default::default()
}),
..Default::default()
});
let drag = signal(true);
DRAG.set(Some(drag));
view()
.window_drag(move || drag.get())
.child(text(move || {
READS.set(READS.get() + 1);
let area = title_bar();
format!("{} {} {}", area.top.0, area.left.0, area.right.0)
}))
.child(
text("Close window")
.window_drag(false)
.on_press(move |_: &()| window.close()),
)
.child(text("Quit").on_press(|_: &()| quit()))
.child(text("Restart").on_press(|_: &()| restart()))
}
/// Commits until a text shows `wanted`: an update may land in a later
/// commit than the event that caused it.
fn commit_showing(c: &mut Core<FakeEngine>, wanted: &str) -> bool {
for _ in 0..3 {
let Some(batch) = c.commit() else { continue };
if batch
.items
.iter()
.any(|item| matches!(item, MountItem::Text { text, .. } if text.text == wanted))
{
return true;
}
}
false
}
#[test]
fn rust_title_bar_commands_and_reactive_drag_props_reach_the_platform() {
let mut c = core();
READS.set(0);
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<Chrome>());
let batch = c.commit().unwrap();
// The window opens with the attributes its content set while it
// first rendered (the effect may land in the next commit).
let mut commands: Vec<(crate::NodeId, DesktopCommand)> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
id,
command: Command::Desktop(command),
} => Some((*id, (**command).clone())),
_ => None,
})
.collect();
if let Some(next) = c.commit() {
commands.extend(next.items.iter().filter_map(|item| match item {
MountItem::Command {
id,
command: Command::Desktop(command),
} => Some((*id, (**command).clone())),
_ => None,
}));
}
let mut window = None;
let mut merged = WindowAttributes::default();
for (at, command) in &commands {
match command {
DesktopCommand::OpenWindow(open) => {
window = Some(*at);
merged.merge(&open.options.attributes);
}
DesktopCommand::SetAttributes(a) if Some(*at) == window => merged.merge(a),
_ => {}
}
}
let window = window.expect("the window opens");
assert!(
merged
.title_bar
.is_some_and(|t| t.style == TitleBarStyle::Hidden && t.height == Some(px(42.0)))
);
let header = batch
.items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props } if props.window_drag == Some(true) => Some(*id),
_ => None,
})
.unwrap();
let close = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Text { id, text, .. } if text.text == "Close window" => Some(*id),
_ => None,
})
.unwrap();
assert!(batch.items.iter().any(|item| matches!(item, MountItem::ViewProps {id, props} if *id == close && props.window_drag == Some(false))));
let quit_button = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Text { id, text, .. } if text.text == "Quit" => Some(*id),
_ => None,
})
.unwrap();
let restart_button = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Text { id, text, .. } if text.text == "Restart" => Some(*id),
_ => None,
})
.unwrap();
// Its title bar area starts empty: the platform reports it.
assert!(
batch
.items
.iter()
.any(|item| matches!(item, MountItem::Text {text, .. } if text.text == "0 0 0"))
);
let area = |top: f32, left: f32, right: f32| Edges {
top: Points(top),
left: Points(left),
right: Points(right),
bottom: Points(0.0),
};
c.component_event(
window,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::TitleBar(area(42.0, 78.0, 0.0)))),
);
assert!(commit_showing(&mut c, "42 78 0"));
{
let _entered = c.components.runtime.enter();
DRAG.get().unwrap().set(false);
}
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|item| matches!(item, MountItem::ViewProps {id, props} if *id == header && props.window_drag == Some(false))));
assert!(
!batch
.items
.iter()
.any(|item| matches!(item, MountItem::Create { .. }))
);
let reads = READS.get();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
dark: true,
..Default::default()
});
assert!(c.commit().is_none());
assert_eq!(
READS.get(),
reads,
"other environment changes do not rerun title_bar readers"
);
c.component_event(
window,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::TitleBar(area(42.0, 0.0, 138.0)))),
);
assert!(commit_showing(&mut c, "42 0 138"));
c.component_event(
window,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::TitleBar(Edges::default()))),
);
assert!(commit_showing(&mut c, "0 0 0"));
// Quitting is a command of its own: the platform ends the app's run,
// not only its window.
assert!(c.component_event(quit_button, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let sent: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
id: crate::ROOT_ID,
command: Command::Desktop(command),
} => Some(&**command),
_ => None,
})
.collect();
assert_eq!(sent, [&DesktopCommand::Quit]);
// Restarting too: the platform quits, then starts the app again.
assert!(c.component_event(restart_button, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|item| matches!(item, MountItem::Command {id: crate::ROOT_ID, command: Command::Desktop(command)} if **command == DesktopCommand::Restart)));
// Closing a window of the app's own removes its root: the platform
// closes the native window when it goes.
assert!(c.component_event(close, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|item| matches!(
item,
MountItem::Remove { id } | MountItem::Delete { id } if *id == window
)));
}
}
mod rust_windows {
use std::cell::RefCell;
use super::*;
use crate::{
desktop::{
DesktopCommand, OpenWindow, SizeToContent, WindowAttributes, WindowCloseCause,
WindowEvent, WindowKind, WindowLevel, WindowRequest,
},
element::{
Root,
desktop::{OpenChange, current_window, window},
},
geometry::Edges,
prelude::*,
};
thread_local! {
static TITLE: RefCell<Option<Signal<String>>> = const { RefCell::new(None) };
static CHANGES: RefCell<Vec<OpenChange>> = const { RefCell::new(Vec::new()) };
static INSIDE: RefCell<Option<String>> = const { RefCell::new(None) };
}
#[component]
fn Windows() -> impl IntoElement {
let title = signal(String::from("Inspector"));
TITLE.with(|t| *t.borrow_mut() = Some(title));
let open = signal(true);
view().child(
window()
.id("inspector")
.kind(WindowKind::Panel)
.title(move || title.get())
.open(move || open.get())
.on_open_change(move |e| {
CHANGES.with(|c| c.borrow_mut().push(*e));
open.set(e.open);
})
.content(|| {
INSIDE.with(|i| *i.borrow_mut() = Some(current_window().id().to_owned()));
text("Inspector")
}),
)
}
#[test]
fn a_window_shown_in_a_commit_gets_its_attributes_first() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
let desktop = |command| Op::Command {
id: crate::ROOT_ID,
command: Command::Desktop(Box::new(command)),
};
c.apply(desktop(DesktopCommand::Request(WindowRequest::Show)))
.unwrap();
c.apply(desktop(DesktopCommand::SetAttributes(Box::new(
WindowAttributes {
activate: Some(false),
..Default::default()
},
))))
.unwrap();
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
assert!(
matches!(
&commands[..],
[
(_, DesktopCommand::SetAttributes(a)),
(_, DesktopCommand::Request(WindowRequest::Show)),
] if a.activate == Some(false)
),
"{commands:?}"
);
}
fn window_commands(batch: &MountBatch) -> Vec<(NodeId, DesktopCommand)> {
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
id,
command: Command::Desktop(command),
} if command.is_window_command() => Some((*id, (**command).clone())),
_ => None,
})
.collect()
}
#[test]
fn rust_windows_open_with_their_kinds_defaults_and_send_what_changes() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<Windows>());
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
let [(id, DesktopCommand::OpenWindow(open))] = &commands[..] else {
panic!("one window opens: {commands:?}");
};
let OpenWindow { options, .. } = &**open;
assert_eq!(options.id, "inspector");
assert_eq!(options.kind, WindowKind::Panel);
// The kind's defaults arrive resolved, the app's own over them.
let a = &options.attributes;
assert_eq!(a.title.as_deref(), Some("Inspector"));
assert_eq!(a.level, Some(WindowLevel::Floating));
assert_eq!(a.taskbar, Some(false));
assert_eq!(a.close_on_press, Some(true));
// `current_window()` in its content is the window.
assert_eq!(
INSIDE.with(|i| i.borrow().clone()).as_deref(),
Some("inspector")
);
// A changed title: one diff with only the title.
{
let _entered = c.components.runtime.enter();
TITLE.with(|t| t.borrow().unwrap().set("Layers".into()));
}
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
assert_eq!(
commands,
[(
*id,
DesktopCommand::SetAttributes(Box::new(WindowAttributes {
title: Some("Layers".into()),
..Default::default()
}))
)]
);
// Escape closed it (its policy): the app hears why and the window's
// root goes.
c.component_event(
*id,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::Closed {
cause: WindowCloseCause::Escape,
})),
);
let batch = c.commit().unwrap();
assert_eq!(
CHANGES.with(|c| c.borrow().clone()),
[OpenChange {
open: false,
reason: WindowCloseCause::Escape
}]
);
assert!(
batch
.items
.iter()
.any(|item| matches!(item, MountItem::Remove { id: removed } | MountItem::Delete { id: removed } if removed == id)),
"{:?}",
batch.items
);
}
#[component]
fn Empty() -> impl IntoElement {
view()
}
#[test]
fn rust_open_window_opens_one_window_per_id_until_it_closes() {
use crate::element::desktop::open_window;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
let closed = Rc::new(RefCell::new(Vec::new()));
let doc = {
let _entered = c.components.runtime.enter();
let closed = closed.clone();
open_window(
window()
.id("doc:1")
.title("Doc 1")
.on_open_change(move |e| closed.borrow_mut().push(e.reason))
.content(|| {
INSIDE.with(|i| *i.borrow_mut() = Some(current_window().id().to_owned()));
text("Doc 1")
}),
)
.expect("opens on a desktop")
};
assert_eq!(doc.id(), "doc:1");
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
let [(id, DesktopCommand::OpenWindow(open))] = &commands[..] else {
panic!("one window opens: {commands:?}");
};
assert_eq!(open.options.id, "doc:1");
assert_eq!(
INSIDE.with(|i| i.borrow().clone()).as_deref(),
Some("doc:1")
);
// The same id again: the open window, focused, not a second one.
let again = {
let _entered = c.components.runtime.enter();
open_window(window().id("doc:1").content(|| text("Other")))
};
assert!(again.as_ref() == Some(&doc));
let batch = c.commit().unwrap();
assert_eq!(
window_commands(&batch),
[(*id, DesktopCommand::Request(WindowRequest::Focus))]
);
// Its ref closes it: the app hears it and the window's root goes.
{
let _entered = c.components.runtime.enter();
doc.close();
}
let batch = c.commit().unwrap();
assert_eq!(*closed.borrow(), [WindowCloseCause::Close]);
assert!(
batch
.items
.iter()
.any(|item| matches!(item, MountItem::Remove { id: removed } | MountItem::Delete { id: removed } if removed == id)),
"{:?}",
batch.items
);
// A closed ref's signals are gone; reading it is safe.
{
let _entered = c.components.runtime.enter();
assert_eq!(doc.state(), None);
assert_eq!(doc.title_bar(), Edges::default());
}
// Closed, the id opens a new window.
{
let _entered = c.components.runtime.enter();
assert!(open_window(window().id("doc:1").content(|| text("Doc 1"))).is_some());
}
let batch = c.commit().unwrap();
assert!(matches!(
&window_commands(&batch)[..],
[(_, DesktopCommand::OpenWindow(_))]
));
}
#[component]
fn SetsOwnTitle() -> impl IntoElement {
view().child(window().id("settings").title("Static title").content(|| {
let me = current_window();
effect(move || {
me.set(WindowAttributes {
title: Some("Set in content".into()),
..Default::default()
});
me.set(WindowAttributes {
resizable: Some(false),
..Default::default()
});
});
text("settings")
}))
}
// #1344: attributes a window's own content sets while it first opens
// reach the window, after the open and over its options.
#[test]
fn attributes_set_while_a_window_opens_are_kept() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<SetsOwnTitle>());
let mut commands = window_commands(&c.commit().unwrap());
// An effect may run in the next commit: collect both.
if let Some(batch) = c.commit() {
commands.extend(window_commands(&batch));
}
// It opens with them (or gets them right after): what it ends up with.
let mut id = None;
let mut merged = WindowAttributes::default();
for (at, command) in &commands {
match command {
DesktopCommand::OpenWindow(open) => {
id = Some(*at);
merged.merge(&open.options.attributes);
}
DesktopCommand::SetAttributes(a) if Some(*at) == id => merged.merge(a),
_ => {}
}
}
assert!(id.is_some(), "the window opens: {commands:?}");
assert_eq!(
merged.title.as_deref(),
Some("Set in content"),
"{commands:?}"
);
assert_eq!(merged.resizable, Some(false), "{commands:?}");
// Sent once: nothing more on the next commit.
assert!(c.commit().is_none_or(|b| window_commands(&b).is_empty()));
}
fn opened_title(c: &mut Core<FakeEngine>) -> Option<String> {
let mut title = None;
while let Some(batch) = c.commit() {
for (_, command) in window_commands(&batch) {
match command {
DesktopCommand::OpenWindow(open) => title = open.options.attributes.title,
DesktopCommand::SetAttributes(a) if a.title.is_some() => title = a.title,
_ => {}
}
}
}
title
}
// #2759: what the ref `open_window` returns is asked for in the same
// turn follows the opening, in order; attributes join its options.
#[test]
fn requests_made_right_after_open_window_follow_its_opening() {
use crate::{desktop::WindowMode, element::desktop::open_window};
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
let doc = {
let _entered = c.components.runtime.enter();
let doc = open_window(window().id("doc").title("Static").content(|| text("doc")))
.expect("opens on a desktop");
doc.focus();
doc.set(WindowAttributes {
title: Some("Set".into()),
..Default::default()
});
doc.set_mode(WindowMode::Maximized);
doc.focus();
doc
};
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
let [
(id, DesktopCommand::OpenWindow(open)),
(focus, DesktopCommand::Request(WindowRequest::Focus)),
(mode, DesktopCommand::Request(WindowRequest::SetMode(WindowMode::Maximized))),
(again, DesktopCommand::Request(WindowRequest::Focus)),
] = &commands[..]
else {
panic!("opens, then its requests in order: {commands:?}");
};
assert_eq!([focus, mode, again], [id; 3]);
assert_eq!(open.options.attributes.title.as_deref(), Some("Set"));
// Sent once: a later commit does not repeat them.
{
let _entered = c.components.runtime.enter();
doc.set(WindowAttributes {
title: Some("Later".into()),
..Default::default()
});
}
let commands = window_commands(&c.commit().unwrap());
assert!(
matches!(&commands[..], [(_, DesktopCommand::SetAttributes(_))]),
"{commands:?}"
);
// Closed: its requests reach nothing, and the next opening of the
// id does not inherit them.
{
let _entered = c.components.runtime.enter();
doc.close();
}
let _ = c.commit().unwrap();
{
let _entered = c.components.runtime.enter();
doc.set_mode(WindowMode::FullScreen);
doc.focus();
}
assert!(c.commit().is_none_or(|b| window_commands(&b).is_empty()));
{
let _entered = c.components.runtime.enter();
open_window(window().id("doc").content(|| text("doc"))).expect("opens again");
}
let commands = window_commands(&c.commit().unwrap());
assert!(
matches!(&commands[..], [(_, DesktopCommand::OpenWindow(_))]),
"{commands:?}"
);
}
// #1344, `open_window` and a window opened again: each opening keeps
// what its content set then, not what an earlier one did.
#[test]
fn attributes_set_while_an_opened_window_opens_are_kept_each_time() {
use crate::element::desktop::open_window;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
let _ = c.commit();
let open = |title: &'static str| {
open_window(window().id("doc").title("Static").content(move || {
let me = current_window();
effect(move || {
me.set(WindowAttributes {
title: Some(title.into()),
..Default::default()
});
});
text("doc")
}))
.expect("opens on a desktop")
};
let doc = {
let _entered = c.components.runtime.enter();
open("First")
};
assert_eq!(opened_title(&mut c).as_deref(), Some("First"));
{
let _entered = c.components.runtime.enter();
doc.close();
}
let _ = opened_title(&mut c);
{
let _entered = c.components.runtime.enter();
open("Second");
}
assert_eq!(opened_title(&mut c).as_deref(), Some("Second"));
}
#[component]
fn WithNotes() -> impl IntoElement {
view().child(window().id("notes").content(|| text("Notes")))
}
#[test]
fn rust_open_window_finds_declared_windows_and_follows_capabilities() {
use crate::element::desktop::open_window;
// Off the desktops: nothing opens.
let mut c = core();
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
{
let _entered = c.components.runtime.enter();
assert!(open_window(window().id("doc")).is_none());
}
// A `window()` in the tree with the id: focused, not a second one.
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<WithNotes>());
let batch = c.commit().unwrap();
let [(notes, DesktopCommand::OpenWindow(_))] = &window_commands(&batch)[..] else {
panic!("the declared window opens");
};
let notes = *notes;
{
let _entered = c.components.runtime.enter();
let found = open_window(window().id("notes").content(|| text("Other")));
assert_eq!(found.as_ref().map(|w| w.id()), Some("notes"));
}
let batch = c.commit().unwrap();
assert_eq!(
window_commands(&batch),
[(notes, DesktopCommand::Request(WindowRequest::Focus))]
);
// Not granted by the capabilities: nothing opens, as `Window.open`
// throws.
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
let mut access = crate::access::Access::all();
access.declared.windows = None;
c.set_access(std::sync::Arc::new(access));
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
{
let _entered = c.components.runtime.enter();
assert!(open_window(window().id("doc")).is_none());
}
assert!(c.commit().is_none_or(|b| window_commands(&b).is_empty()));
}
thread_local! {
static PRESSES: RefCell<Vec<(String, crate::desktop::CloseReason)>> =
const { RefCell::new(Vec::new()) };
}
#[component]
fn ClosePresses() -> impl IntoElement {
crate::element::desktop::main_window().on_close_press(|reason| {
PRESSES.with(|p| p.borrow_mut().push(("main".into(), reason)))
});
view().child(window().id("notes").content(|| {
let this = current_window();
let id = this.id().to_owned();
this.on_close_press(move |reason| {
PRESSES.with(|p| p.borrow_mut().push((id.clone(), reason)))
});
text("Notes")
}))
}
#[test]
fn rust_listeners_hear_close_presses_of_the_main_window_and_their_own() {
use crate::desktop::CloseReason;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.mount_root(&Root::of::<ClosePresses>());
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
let [(notes, DesktopCommand::OpenWindow(_))] = &commands[..] else {
panic!("one window opens: {commands:?}");
};
for (id, reason) in [
(crate::ROOT_ID, CloseReason::CloseButton),
(*notes, CloseReason::Shortcut),
(crate::ROOT_ID, CloseReason::Shortcut),
] {
c.component_event(
id,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::ClosePress { reason })),
);
let _ = c.commit();
}
assert_eq!(
PRESSES.with(|p| p.borrow().clone()),
[
("main".to_owned(), CloseReason::CloseButton),
("notes".to_owned(), CloseReason::Shortcut),
("main".to_owned(), CloseReason::Shortcut),
]
);
}
/// The root's desktop commands that are not about a window.
fn app_commands(batch: &MountBatch) -> Vec<DesktopCommand> {
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
id: crate::ROOT_ID,
command: Command::Desktop(command),
} if !command.is_window_command() => Some((**command).clone()),
_ => None,
})
.collect()
}
#[test]
fn quit_requests_go_to_the_app_while_it_listens() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
let first = c.commit().unwrap();
assert_eq!(
app_commands(&first),
[],
"nothing listens: quitting as before"
);
let heard = Rc::new(std::cell::Cell::new(0));
let (owner, ()) = {
let _entered = c.components.runtime.enter();
let heard = heard.clone();
crate::element::create_root(move || {
crate::element::desktop::on_quit_request(move || heard.set(heard.get() + 1));
})
};
let batch = c.commit().unwrap();
assert_eq!(
app_commands(&batch),
[DesktopCommand::SetQuitOnRequest(false)],
"the platform leaves quitting to the app"
);
// The platform reports the user's request instead of quitting.
c.component_event(
crate::ROOT_ID,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::QuitRequest)),
);
let after = c.commit();
assert_eq!(heard.get(), 1);
assert!(
after.is_none_or(|b| app_commands(&b).is_empty()),
"the app decides when to quit"
);
{
let _entered = c.components.runtime.enter();
owner.dispose();
}
let batch = c.commit().unwrap();
assert_eq!(
app_commands(&batch),
[DesktopCommand::SetQuitOnRequest(true)],
"without a listener quit requests quit again"
);
}
/// A listener that quits at once answers within the request's delivery:
/// the quit is in the commit that follows it, so a platform that must
/// decide on the spot (a web page leaving) knows the answer before it
/// returns.
#[test]
fn a_quit_request_answered_at_once_quits_in_the_same_commit() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
c.commit();
let dirty = Rc::new(std::cell::Cell::new(true));
let _root = {
let _entered = c.components.runtime.enter();
let dirty = dirty.clone();
crate::element::create_root(move || {
crate::element::desktop::on_quit_request(move || {
if !dirty.get() {
crate::element::desktop::quit();
}
});
})
};
c.commit();
let request = |c: &mut Core<FakeEngine>| {
c.component_event(
crate::ROOT_ID,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::QuitRequest)),
);
c.commit().map(|b| app_commands(&b)).unwrap_or_default()
};
assert_eq!(
request(&mut c),
[],
"something to lose: the app keeps running"
);
dirty.set(false);
assert_eq!(request(&mut c), [DesktopCommand::Quit]);
}
#[test]
fn the_app_hears_reopens_and_its_last_window_closing() {
use crate::element::desktop::open_window;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
let reopens = Rc::new(Cell::new(0));
let closes = Rc::new(Cell::new(0));
let (owner, subscriptions) = {
let _entered = c.components.runtime.enter();
let reopens = reopens.clone();
let closes = closes.clone();
crate::element::create_root(move || {
let reopen = crate::element::desktop::add_reopen_listener(Rc::new(move || {
reopens.set(reopens.get() + 1);
}));
let closed =
crate::element::desktop::add_last_window_closed_listener(Rc::new(move || {
closes.set(closes.get() + 1);
}));
(reopen, closed)
})
};
let _ = c.commit();
c.reopened();
assert_eq!(reopens.get(), 1, "the app heard the reopen");
assert_eq!(closes.get(), 0);
// A window of the app's own goes: the app hears the last one only.
let first = {
let _entered = c.components.runtime.enter();
open_window(window().id("one").content(view))
};
let second = {
let _entered = c.components.runtime.enter();
open_window(window().id("two").content(view))
};
assert!(first.is_some() && second.is_some(), "two windows open");
let _ = c.commit();
{
let _entered = c.components.runtime.enter();
first.as_ref().unwrap().close();
}
let batch = c.commit().unwrap();
assert_eq!(closes.get(), 0, "a window is still open");
assert!(
app_commands(&batch).is_empty(),
"the core's default policy leaves quitting to the engine"
);
{
let _entered = c.components.runtime.enter();
second.as_ref().unwrap().close();
}
let _ = c.commit();
assert_eq!(closes.get(), 1, "the app heard its last window close");
// The listeners that went stop hearing: the app's owner is gone.
drop(subscriptions);
let _ = owner;
c.reopened();
let _ = c.commit();
assert_eq!(reopens.get(), 1);
assert_eq!(closes.get(), 1);
}
#[test]
fn closing_the_last_window_quits_under_the_quit_mode() {
use crate::element::desktop::open_window;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
..Default::default()
});
c.apply(Op::Command {
id: crate::ROOT_ID,
command: Command::Desktop(Box::new(DesktopCommand::SetQuitMode(
crate::desktop::QuitMode::LastWindowClosed,
))),
})
.unwrap();
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
let open = |c: &mut Core<FakeEngine>, id: &'static str| {
let _entered = c.components.runtime.enter();
open_window(window().id(id).content(view)).unwrap()
};
let first = open(&mut c, "one");
let second = open(&mut c, "two");
let _ = c.commit().unwrap();
{
let _entered = c.components.runtime.enter();
first.close();
}
let batch = c.commit().unwrap();
assert!(
app_commands(&batch).is_empty(),
"one window still open: no quit"
);
{
let _entered = c.components.runtime.enter();
second.close();
}
let batch = c.commit().unwrap();
assert!(
app_commands(&batch).contains(&DesktopCommand::Quit),
"the last window went under the mode: the app quits"
);
}
#[test]
fn closing_the_implicit_main_window_quits_unless_a_quit_mode_is_set() {
let open_and_close = |implicit: bool, explicit_mode: Option<crate::desktop::QuitMode>| {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.__set_default_quit_mode(crate::desktop::QuitMode::Platform);
if let Some(mode) = explicit_mode {
c.set_quit_mode(mode);
}
let mut open = OpenWindow {
implicit,
..OpenWindow::default()
};
open.options.id = "main".into();
c.apply(Op::Create {
id: 2,
tag: Tag::Modal,
})
.unwrap();
c.apply(Op::Insert {
parent: crate::ROOT_ID,
child: 2,
before: None,
})
.unwrap();
c.apply(Op::Command {
id: 2,
command: Command::Desktop(Box::new(DesktopCommand::OpenWindow(Box::new(open)))),
})
.unwrap();
let _ = c.commit().unwrap();
c.apply(Op::Remove {
parent: crate::ROOT_ID,
child: 2,
})
.unwrap();
let batch = c.commit().unwrap();
app_commands(&batch).contains(&DesktopCommand::Quit)
};
assert!(
open_and_close(true, None),
"implicit main window quits on macOS when no quit mode was set"
);
assert!(
!open_and_close(true, Some(crate::desktop::QuitMode::Platform)),
"explicitly setting platform keeps macOS running even for an implicit window"
);
assert!(
!open_and_close(true, Some(crate::desktop::QuitMode::Explicit)),
"explicit quit mode keeps macOS running for an implicit window"
);
assert!(
!open_and_close(false, None),
"explicit windows keep the platform default on macOS"
);
}
/// Rust sets the mode as TSX does (`set_quit_mode`), and the last
/// window's close follows it.
#[test]
fn a_rust_app_sets_the_quit_mode_of_its_last_window() {
use crate::element::desktop::open_window;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
let _root = {
let _entered = c.components.runtime.enter();
crate::element::create_root(move || {
crate::element::desktop::set_quit_mode(crate::desktop::QuitMode::Explicit);
})
};
// The command reaches the core with this commit, which sends nothing.
let _ = c.commit();
let only = {
let _entered = c.components.runtime.enter();
open_window(window().id("only").content(view)).unwrap()
};
let _ = c.commit().unwrap();
{
let _entered = c.components.runtime.enter();
only.close();
}
let batch = c.commit().unwrap();
assert!(
!app_commands(&batch).contains(&DesktopCommand::Quit),
"explicit: the app keeps running with no windows"
);
}
#[test]
fn a_last_window_listener_opens_the_next_window() {
use crate::element::desktop::open_window;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<Empty>());
let _ = c.commit().unwrap();
let reopened: Rc<RefCell<Option<crate::element::desktop::WindowRef>>> =
Rc::new(RefCell::new(None));
let _subscription = {
let _entered = c.components.runtime.enter();
let reopened = reopened.clone();
crate::element::desktop::add_last_window_closed_listener(Rc::new(move || {
let next = open_window(window().id("next").content(view));
*reopened.borrow_mut() = next;
}))
};
let only = {
let _entered = c.components.runtime.enter();
open_window(window().id("only").content(view)).unwrap()
};
let _ = c.commit().unwrap();
{
let _entered = c.components.runtime.enter();
only.close();
}
// The mode is explicit (the core's default): the app stays and the
// listener's window opens in the commit after it.
let batch = c.commit();
assert!(
batch
.as_ref()
.is_none_or(|b| !app_commands(b).contains(&DesktopCommand::Quit)),
"the app decides: no quit"
);
let batch = c.commit().unwrap();
assert!(
window_commands(&batch).iter().any(
|(_, c)| matches!(c, DesktopCommand::OpenWindow(open) if open.options.id == "next")
),
"{:?}",
batch.items
);
assert!(reopened.borrow().is_some(), "the next window is open");
}
/// Two windows the app declares, the first with nothing of its own.
#[component]
fn TwoWindows() -> impl IntoElement {
view().child(window().id("main").content(view)).child(
window()
.id("aside")
.title("Aside")
.default_size(size(px(300.0), px(200.0)))
.content(view),
)
}
#[test]
fn the_first_app_window_inherits_the_launch_defaults() {
use crate::desktop::{MainWindowOptions, WindowAttributes};
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_main_window(&MainWindowOptions {
default_size: Some(size(px(900.0), px(600.0))),
attributes: WindowAttributes {
title: Some("Mail".into()),
..Default::default()
},
..Default::default()
});
c.mount_root(&Root::of::<TwoWindows>());
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
let open = |wanted: &str| {
commands
.iter()
.find_map(|(_, c)| match c {
DesktopCommand::OpenWindow(open) if open.options.id == wanted => {
Some(&open.options)
}
_ => None,
})
.unwrap_or_else(|| panic!("{wanted} opens: {commands:?}"))
};
let main = open("main");
assert_eq!(main.default_size, Some(size(px(900.0), px(600.0))));
assert_eq!(main.attributes.title.as_deref(), Some("Mail"));
// The next window is the app's own: the launch defaults are for the
// first one only.
let aside = open("aside");
assert_eq!(aside.default_size, Some(size(px(300.0), px(200.0))));
assert_eq!(aside.attributes.title.as_deref(), Some("Aside"));
}
thread_local! {
static FITTED: RefCell<Option<crate::element::desktop::WindowRef>> =
const { RefCell::new(None) };
}
/// A first window as tall as its content, and a panel as large as its
/// content.
#[component]
fn Fitted() -> impl IntoElement {
window().id("main").content(|| {
current_window().set(WindowAttributes {
size_to_content: Some(SizeToContent::Height),
..Default::default()
});
view().child(view().h(px(120.0))).child(
window()
.id("fitted")
.attributes(WindowAttributes {
size_to_content: Some(SizeToContent::Both),
..Default::default()
})
.content(|| {
FITTED.with(|f| *f.borrow_mut() = Some(current_window()));
view().w(px(300.0)).h(px(200.0))
}),
)
})
}
#[test]
fn rust_windows_fit_their_content_and_report_their_title_bars() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_viewport(size(px(800.0), px(600.0)));
c.mount_root(&Root::of::<Fitted>());
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
let fit = |w: Option<f32>, h: Option<f32>| {
DesktopCommand::Request(WindowRequest::SetContentSize {
width: w.map(Points),
height: h.map(Points),
})
};
// The first window: only its height, its content's.
let open_id = |wanted: &str| {
commands
.iter()
.find_map(|(id, c)| match c {
DesktopCommand::OpenWindow(open) if open.options.id == wanted => Some(*id),
_ => None,
})
.unwrap_or_else(|| panic!("{wanted} opens: {commands:?}"))
};
let main = open_id("main");
let id = open_id("fitted");
assert!(
commands.contains(&(main, fit(None, Some(120.0)))),
"{commands:?}"
);
assert!(
commands.contains(&(id, fit(Some(300.0), Some(200.0)))),
"{commands:?}"
);
// The platform sized them: nothing more to ask.
// (A commit with nothing to mount gives no batch.)
c.set_viewport(size(px(800.0), px(120.0)));
if let Some(batch) = c.commit() {
assert!(
!window_commands(&batch)
.iter()
.any(|(_, c)| matches!(c, DesktopCommand::Request(_))),
"{:?}",
batch.items
);
}
// Its title bar's area, as the platform reports it.
let handle = FITTED
.with(|f| f.borrow().clone())
.expect("the panel's handle");
{
let _entered = c.components.runtime.enter();
assert_eq!(handle.title_bar(), Edges::default());
}
let area = Edges {
top: px(28.0),
left: px(72.0),
..Default::default()
};
c.component_event(
id,
EventKind::Window,
&EventPayload::Window(Box::new(WindowEvent::TitleBar(area))),
);
let _entered = c.components.runtime.enter();
assert_eq!(handle.title_bar(), area);
}
/// Escape bound in the app root and in two windows of the app's own
/// (#1343), Mod+K app-wide from the app root; a press closes "about".
#[component]
fn WindowKeys() -> impl IntoElement {
let main = signal(0);
let settings = signal(0);
let about = signal(0);
let about_open = signal(true);
on_key("escape", move |_| main.update(|n| *n += 1));
on_key("mod+k", move |_| main.update(|n| *n += 10));
view()
.on_press(move |_: &()| about_open.set(false))
.child(text(move || {
format!("{} {} {}", main.get(), settings.get(), about.get())
}))
.child(
window()
.id("settings")
.default_size(size(px(300.0), px(100.0)))
.content(move || {
on_key("escape", move |_| settings.update(|n| *n += 1));
on_key("mod+l", move |_| settings.update(|n| *n += 100));
on_key_with(
"mod+j",
KeyOptions {
scope: KeyScope::App,
..Default::default()
},
|_| {},
);
view()
}),
)
.child(
window()
.id("about")
.open(about_open)
.default_size(size(px(300.0), px(100.0)))
.content(move || {
on_key("escape", move |_| about.update(|n| *n += 1));
view()
}),
)
}
#[test]
fn a_shortcut_fires_only_in_the_window_that_bound_it() {
use super::views::{root_host, texts};
use crate::keymap::{KeyMatch, Keymap, Keystroke};
let last_table = |batch: &MountBatch| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Keymap(k) => Some(k.clone()),
_ => None,
})
};
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_viewport(size(px(800.0), px(600.0)));
c.mount_root(&Root::of::<WindowKeys>());
let batch = c.commit().unwrap();
let host = root_host(&batch);
let windows: Vec<NodeId> = window_commands(&batch)
.iter()
.filter(|(_, c)| matches!(c, DesktopCommand::OpenWindow(_)))
.map(|(id, _)| *id)
.collect();
let [settings, about] = windows[..] else {
panic!("two windows open: {windows:?}");
};
// The table may come in a later commit, once the windows' roots
// are mounted.
let mut table: Option<std::sync::Arc<Keymap>> = last_table(&batch);
for _ in 0..3 {
if let Some(b) = c.commit() {
table = last_table(&b).or(table);
}
}
let table = table.expect("a table");
let escape = Keystroke::parse_with("escape", true).unwrap();
let mod_k = Keystroke::parse_with("mod+k", true).unwrap();
let tab = Keystroke::parse_with("tab", true).unwrap();
let fired = |window: NodeId, key: Keystroke| match table.find_in(window, key, false, false)
{
KeyMatch::Fire(id) => Some(id),
KeyMatch::None => None,
other => panic!("{other:?}"),
};
let in_main = fired(ROOT_ID, escape).expect("the main window's Escape");
let in_settings = fired(settings, escape).expect("Settings' Escape");
let in_about = fired(about, escape).expect("About's Escape");
assert_ne!(in_main, in_settings);
assert_ne!(in_settings, in_about);
assert_eq!(table.find(escape, false, false), KeyMatch::Fire(in_main));
// Mod+K, bound in the app root, is every window's; keys no binding
// takes go on in every window.
let app_mod_k = fired(settings, mod_k).expect("the app's Mod+K");
assert_eq!(fired(ROOT_ID, mod_k), Some(app_mod_k));
assert_eq!(fired(about, mod_k), Some(app_mod_k));
// A window's own binding stays there; an explicit app scope from
// inside a window is every window's.
let mod_l = Keystroke::parse_with("mod+l", true).unwrap();
assert!(fired(settings, mod_l).is_some());
assert_eq!(fired(ROOT_ID, mod_l), None);
assert_eq!(fired(about, mod_l), None);
let mod_j = Keystroke::parse_with("mod+j", true).unwrap();
let app_mod_j = fired(ROOT_ID, mod_j).expect("the app's Mod+J");
assert_eq!(fired(settings, mod_j), Some(app_mod_j));
assert_eq!(fired(about, mod_j), Some(app_mod_j));
assert_eq!(fired(about, tab), None);
assert_eq!(fired(ROOT_ID, tab), None);
// Each runs its own window's handler.
let key = |id: u32| EventPayload::Value(crate::PayloadValue::Number(id as f64));
for (id, shown) in [
(in_settings, "0 1 0"),
(in_main, "1 1 0"),
(in_about, "1 1 1"),
] {
assert!(c.component_event(ROOT_ID, EventKind::KeyCommand, &key(id)));
assert_eq!(texts(&c.commit().unwrap()), [shown]);
}
// A closed window's binding goes with it; the app's stays.
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let mut table = None;
for _ in 0..3 {
if let Some(b) = c.commit() {
table = last_table(&b).or(table);
}
}
let table = table.expect("a new table");
assert_eq!(
table.find_in(about, escape, false, false),
KeyMatch::Fire(in_main)
);
assert_eq!(
table.find_in(settings, escape, false, false),
KeyMatch::Fire(in_settings)
);
assert_eq!(table.bindings().len(), 5);
}
/// Counts the Escapes it is bound to.
#[component]
fn EscapeCount() -> impl IntoElement {
let count = signal(0);
on_key("escape", move |_| count.update(|n| *n += 1));
text(move || format!("escape {}", count.get()))
}
/// A component JS places in a window of the app's own (TS `<Window>`)
/// has no `WindowRef` around it in Rust, yet its shortcuts are that
/// window's, as an `Editor`'s arrows in a `Window` are; the same
/// component in the main window keeps the main window's.
#[test]
fn a_component_js_places_in_a_window_binds_its_keys_there() {
use super::views::texts;
use crate::{
element::Registry,
keymap::{KeyMatch, Keystroke},
};
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_viewport(size(px(800.0), px(600.0)));
let mut registry = Registry::new();
registry.register::<EscapeCount>();
c.set_components(registry);
let mut open = OpenWindow::default();
open.options.id = "panel".into();
open.options.default_size = Some(size(px(300.0), px(100.0)));
let component = || crate::Prop::Component(std::any::type_name::<EscapeCount>().into());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Modal,
},
Op::Command {
id: 2,
command: Command::Desktop(Box::new(DesktopCommand::OpenWindow(Box::new(open)))),
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: component(),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
Op::SetProp {
id: 6,
prop: component(),
},
Op::Insert {
parent: ROOT_ID,
child: 6,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let mut table = None;
for _ in 0..3 {
if let Some(b) = c.commit() {
table = b
.items
.iter()
.rev()
.find_map(|i| match i {
MountItem::Keymap(k) => Some(k.clone()),
_ => None,
})
.or(table);
}
}
let table = table.expect("a table");
let escape = Keystroke::parse_with("escape", true).unwrap();
let fired = |window: NodeId| match table.find_in(window, escape, false, false) {
KeyMatch::Fire(id) => id,
other => panic!("Escape in window {window}: {other:?}"),
};
let (in_panel, in_main) = (fired(2), fired(ROOT_ID));
assert_ne!(in_panel, in_main, "each window has its own");
let key = |id: u32| EventPayload::Value(crate::PayloadValue::Number(id as f64));
assert!(c.component_event(ROOT_ID, EventKind::KeyCommand, &key(in_panel)));
assert_eq!(texts(&c.commit().unwrap()), ["escape 1"]);
}
/// A popover anchored to a button and a dialog, both in a window's
/// content, below a tall view of the main window.
#[component]
fn Popups() -> impl IntoElement {
let button = element_ref();
view().child(view().h(px(500.0))).child(
window()
.id("tools")
.default_size(size(px(300.0), px(100.0)))
.content(move || {
view()
.pl(px(20.0))
.pt(px(50.0))
.child(view().element_ref(&button).w(px(60.0)).h(px(30.0)))
.child(
overlay()
.anchor(&button)
.placement(crate::overlay::Placement::Bottom)
.align(crate::overlay::Align::Start)
.w(px(80.0))
.h(px(40.0))
.child(text("pop")),
)
.child(modal().child(text("dialog")))
}),
)
}
#[test]
fn rust_windows_show_their_popups_and_dialogs_in_themselves() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_viewport(size(px(800.0), px(600.0)));
c.mount_root(&Root::of::<Popups>());
let batch = c.commit().unwrap();
let commands = window_commands(&batch);
let Some((window, _)) = commands
.iter()
.find(|(_, c)| matches!(c, DesktopCommand::OpenWindow(_)))
else {
panic!("the window opens: {commands:?}");
};
let window = *window;
// The popover's view goes into the window's root view, placed in
// its coordinates, whatever is above the window's node in the main
// window: above the button, as the window (100 points tall, not the
// main window's 600) has no room below it.
let text_parent = |batch: &MountBatch, label: &str| {
let id = batch.items.iter().find_map(|i| match i {
MountItem::Text { id, text, .. } if &*text.text == label => Some(*id),
_ => None,
})?;
batch.items.iter().find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == id => Some(*parent),
_ => None,
})
};
let popover = text_parent(&batch, "pop").expect("the popover's view");
assert!(
batch.items.iter().any(|i| matches!(
i,
MountItem::Insert { parent, child, .. } if *parent == window && *child == popover
)),
"{:?}",
batch.items
);
assert_eq!(
frame_of(&batch, popover).map(|f| f.origin),
Some(point(px(20.0), px(10.0)))
);
// The dialog shows over the window, not the main one.
let dialog = text_parent(&batch, "dialog").expect("the dialog's root");
let config = batch.items.iter().find_map(|i| match i {
MountItem::ModalConfig { id, config } if *id == dialog => Some(config.clone()),
_ => None,
});
assert_eq!(config.map(|c| c.window), Some(window));
// The window's own root: in the main window.
let config = batch.items.iter().find_map(|i| match i {
MountItem::ModalConfig { id, config } if *id == window => Some(config.clone()),
_ => None,
});
assert_eq!(config.map(|c| c.window), Some(ROOT_ID));
}
/// A dialog with a disabled button, an enabled one and a field.
#[derive(Clone, PartialEq, Props)]
struct FocusDialogProps {
#[prop(default)]
auto: bool,
}
#[component]
fn FocusDialog(props: FocusDialogProps) -> impl IntoElement {
let auto = props.auto;
view().child(view().on_press(|| {})).child(
modal()
.child(text("title"))
.child(view().disabled(true).on_press(|| {}).child(text("off")))
.child(view().on_press(|| {}).child(text("ok")))
.child(input().auto_focus(auto)),
)
}
fn open_focus_dialog(os: crate::platform::Os, auto: bool) -> (MountBatch, Option<NodeId>) {
let mut c = core();
c.set_environment(crate::element::Environment {
os,
..Default::default()
});
c.set_viewport(size(px(800.0), px(600.0)));
c.mount_root(&crate::element::Root::new::<FocusDialog>(move || {
FocusDialogProps { auto }
}));
let batch = c.commit().unwrap();
let ok = batch.items.iter().find_map(|i| match i {
MountItem::Text { id, text, .. } if &*text.text == "ok" => Some(*id),
_ => None,
});
let button = ok.and_then(|ok| {
batch.items.iter().find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == ok => Some(*parent),
_ => None,
})
});
(batch, button)
}
fn focus_commands(batch: &MountBatch) -> Vec<NodeId> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Command {
id,
command: Command::Focus,
} => Some(*id),
_ => None,
})
.collect()
}
#[test]
fn a_dialog_opening_focuses_its_first_enabled_control() {
for os in [
crate::platform::Os::MacOs,
crate::platform::Os::Windows,
crate::platform::Os::Linux,
crate::platform::Os::Web,
] {
let (batch, button) = open_focus_dialog(os, false);
let button = button.expect("the ok button");
assert_eq!(focus_commands(&batch), [button], "{os:?}");
}
}
#[test]
fn a_dialog_with_an_auto_focus_field_leaves_the_focus_to_it() {
let (batch, _) = open_focus_dialog(crate::platform::Os::MacOs, true);
assert!(
focus_commands(&batch).is_empty(),
"{:?}",
focus_commands(&batch)
);
}
#[test]
fn a_dialog_on_a_phone_moves_no_focus() {
for os in [crate::platform::Os::Ios, crate::platform::Os::Android] {
let (batch, _) = open_focus_dialog(os, false);
assert!(focus_commands(&batch).is_empty(), "{os:?}");
}
}
#[test]
fn main_windows_that_restore_their_bounds_keep_their_placement() {
use crate::desktop::{MainWindowOptions, WindowMode, WindowPlacement, WindowState};
let mut c = core();
c.set_main_window(&MainWindowOptions {
restore_bounds: true,
..Default::default()
});
let bounds =
crate::geometry::Bounds::new(point(px(40.0), px(60.0)), size(px(640.0), px(480.0)));
let placement = WindowPlacement::new(WindowMode::Maximized, bounds);
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
window_state: Some(WindowState::new(bounds, placement)),
..Default::default()
});
let kept = {
let _entered = c.components.runtime.enter();
crate::storage::Storage::get_item("nsh.window:main")
};
let kept: WindowPlacement = serde_json::from_str(&kept.expect("kept")).unwrap();
assert_eq!(kept, placement);
}
#[test]
fn hidden_main_windows_keep_the_placement_the_user_left() {
use crate::desktop::{MainWindowOptions, WindowMode, WindowPlacement, WindowState};
let mut c = core();
let kept = |c: &Core<FakeEngine>| {
let _entered = c.components.runtime.enter();
crate::storage::Storage::get_item("nsh.window:main")
.map(|json| serde_json::from_str::<WindowPlacement>(&json).unwrap())
};
let state = |x: f32, mode: WindowMode, visible: bool| {
let bounds =
crate::geometry::Bounds::new(point(px(x), px(60.0)), size(px(640.0), px(480.0)));
let mut state = WindowState::new(bounds, WindowPlacement::new(mode, bounds));
state.visible = visible;
state
};
let report = |c: &mut Core<FakeEngine>, state: WindowState| {
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
window_state: Some(state),
..Default::default()
});
};
// Hidden since launch (`defaultVisible: false`), in Normal mode
// until it shows in the mode it opens in: nothing kept yet, so the
// placement of the last run stays.
report(&mut c, state(0.0, WindowMode::Normal, false));
c.set_main_window(&MainWindowOptions {
restore_bounds: true,
default_visible: Some(false),
..Default::default()
});
report(&mut c, state(10.0, WindowMode::Normal, false));
assert_eq!(kept(&c), None);
let maximized = state(40.0, WindowMode::Maximized, true);
report(&mut c, maximized);
assert_eq!(kept(&c), Some(maximized.placement));
// Shown, it is where the user left it, hidden too: a window hidden
// right after a resize reports its new size only then (a tray
// app's close).
let resized = state(40.0, WindowMode::Normal, false);
report(&mut c, resized);
assert_eq!(kept(&c), Some(resized.placement));
// The app host never shows, `defaultVisible` or not: it keeps no
// placement of its own. The first app window's placement is kept
// under its own id.
let mut c = core();
c.set_main_window(&MainWindowOptions {
restore_bounds: true,
..Default::default()
});
let hidden = state(80.0, WindowMode::Normal, false);
report(&mut c, hidden);
assert_eq!(kept(&c), None);
}
/// `nsh.json`'s `"window"` and the app's own `set` reach the main
/// window where the surface has one: the desktops', and a browser's
/// page (its title). A phone's surface is a view in its app's screen:
/// nothing is sent there for its platform to refuse.
#[test]
fn main_window_attributes_go_where_the_surface_has_a_window() {
use crate::{
desktop::{MainWindowOptions, TitleBarStyle},
platform::Os,
};
let options = MainWindowOptions::from_json(
&serde_json::from_str::<crate::JsonValue>(
r#"{"title":"Notes","titleBar":{"style":"hidden","height":40},"minSize":{"width":360,"height":480},"restoreBounds":true}"#,
)
.unwrap(),
)
.unwrap();
let sent = |c: &mut Core<FakeEngine>| -> Vec<WindowAttributes> {
c.commit()
.map(|batch| batch.items)
.unwrap_or_default()
.into_iter()
.filter_map(|item| match item {
MountItem::Command {
id: ROOT_ID,
command: Command::Desktop(command),
} => match *command {
DesktopCommand::SetAttributes(attributes) => Some(*attributes),
_ => None,
},
_ => None,
})
.collect()
};
for os in [
Os::MacOs,
Os::Windows,
Os::Linux,
Os::Web,
Os::Ios,
Os::Android,
] {
let mut c = core();
c.set_environment(crate::element::Environment {
os,
..Default::default()
});
c.set_main_window(&options);
let launch = sent(&mut c);
let title = WindowAttributes {
title: Some("Inbox".to_owned()),
..Default::default()
};
let _ = c.apply_op(Op::Command {
id: ROOT_ID,
command: Command::Desktop(Box::new(DesktopCommand::SetAttributes(Box::new(title)))),
});
let set = sent(&mut c);
if os.is_desktop() || os == Os::Web {
assert_eq!(launch.len(), 1, "{os:?}");
assert_eq!(launch[0].title.as_deref(), Some("Notes"), "{os:?}");
assert!(
launch[0]
.title_bar
.is_some_and(|t| t.style == TitleBarStyle::Hidden),
"{os:?}"
);
assert_eq!(set.len(), 1, "{os:?}");
assert_eq!(set[0].title.as_deref(), Some("Inbox"), "{os:?}");
} else {
assert!(launch.is_empty(), "{os:?}: {launch:?}");
assert!(set.is_empty(), "{os:?}: {set:?}");
}
}
}
/// nsh.json's `"window"` belongs to the host that reads it, not to the
/// app's capabilities: an app that declares capabilities without
/// `application` still gets its launch window attributes. Its own sets
/// of the main window still need `application`.
#[test]
fn launch_window_defaults_apply_without_the_application_capability() {
use crate::desktop::{MainWindowOptions, WindowAttributes};
let mut c = core();
let access = |application: bool| {
std::sync::Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({
"application": application,
}))
.unwrap(),
granted: None,
})
};
c.set_access(access(false));
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_main_window(&MainWindowOptions {
attributes: WindowAttributes {
title: Some("Notes".into()),
..Default::default()
},
..Default::default()
});
let sent = |c: &mut Core<FakeEngine>| -> Vec<WindowAttributes> {
c.commit()
.map(|batch| batch.items)
.unwrap_or_default()
.into_iter()
.filter_map(|item| match item {
MountItem::Command {
id: ROOT_ID,
command: Command::Desktop(command),
} => match *command {
DesktopCommand::SetAttributes(attributes) => Some(*attributes),
_ => None,
},
_ => None,
})
.collect()
};
let launch = sent(&mut c);
assert_eq!(launch.len(), 1, "{launch:?}");
assert_eq!(launch[0].title.as_deref(), Some("Notes"));
// The app's own set of the main window is what `application` grants.
let set = |c: &mut Core<FakeEngine>| {
let _ = c.apply_op(Op::Command {
id: ROOT_ID,
command: Command::Desktop(Box::new(DesktopCommand::SetAttributes(Box::new(
WindowAttributes {
title: Some("Inbox".into()),
..Default::default()
},
)))),
});
};
set(&mut c);
assert!(sent(&mut c).is_empty(), "without `application`");
c.set_access(access(true));
set(&mut c);
let granted = sent(&mut c);
assert_eq!(granted.len(), 1, "{granted:?}");
assert_eq!(granted[0].title.as_deref(), Some("Inbox"));
}
/// Every window request the app root's ref takes, and an attribute it
/// sets and an attention request it asks for.
#[component]
fn AppRootRef() -> impl IntoElement {
use crate::{
desktop::{WindowAttributes, WindowMode},
element::desktop::main_window,
};
let main = main_window();
main.show();
main.hide();
main.focus();
main.minimize();
main.restore();
main.set_mode(WindowMode::Maximized);
main.close();
main.request_attention(false);
main.set(WindowAttributes {
title: Some("App".into()),
..Default::default()
});
view()
}
/// The app root's ref is not a user window: its window requests reach no
/// platform command, so they cannot present or close the hidden host.
/// Its attributes and its attention request are the app's and still
/// reach the platform.
#[test]
fn app_root_window_requests_do_nothing() {
use crate::{
desktop::{DesktopCommand, WindowRequest},
platform::Os,
};
let mut c = core();
c.set_environment(crate::element::Environment {
os: Os::Windows,
..Default::default()
});
c.mount_root(&Root::of::<AppRootRef>());
let sent: Vec<DesktopCommand> =
c.commit()
.map(|batch| batch.items)
.unwrap_or_default()
.into_iter()
.filter_map(|item| match item {
MountItem::Command {
id: ROOT_ID,
command: Command::Desktop(command),
} => match *command {
command @ (DesktopCommand::Request(_)
| DesktopCommand::SetAttributes(_)) => Some(command),
_ => None,
},
_ => None,
})
.collect();
let allowed = |command: &DesktopCommand| {
matches!(
command,
DesktopCommand::SetAttributes(_)
| DesktopCommand::Request(WindowRequest::RequestAttention { .. })
)
};
assert!(sent.iter().all(allowed), "{sent:?}");
assert!(
sent.iter().any(|command| matches!(
command,
DesktopCommand::Request(WindowRequest::RequestAttention { .. })
)),
"{sent:?}"
);
assert!(
sent.iter().any(|command| matches!(
command,
DesktopCommand::SetAttributes(attributes) if attributes.title.as_deref() == Some("App")
)),
"{sent:?}"
);
}
/// A window with no size of the app's, and one with a `defaultSize`,
/// each filled by a view.
#[component]
fn Sized() -> impl IntoElement {
view()
.child(window().id("unsized").content(|| {
view()
.flex_grow(1.0)
.child(view().w(px(200.0)).h(px(100.0)))
}))
.child(
window()
.id("document")
.default_size(size(px(640.0), px(560.0)))
.content(|| view().flex_grow(1.0)),
)
}
#[test]
fn window_roots_are_laid_out_at_their_own_size() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_viewport(size(px(1100.0), px(820.0)));
c.mount_root(&Root::of::<Sized>());
let batch = c.commit().unwrap();
let opened: Vec<(NodeId, String)> = window_commands(&batch)
.into_iter()
.filter_map(|(id, c)| match c {
DesktopCommand::OpenWindow(open) => Some((id, open.options.id.clone())),
_ => None,
})
.collect();
let id_of = |name: &str| {
opened
.iter()
.find(|(_, n)| n == name)
.map(|(id, _)| *id)
.unwrap_or_else(|| panic!("{name} opens: {opened:?}"))
};
let (free_size, document) = (id_of("unsized"), id_of("document"));
let main = rect(0.0, 0.0, 1100.0, 820.0);
// Never the main window's size: the size it opens at, or its
// content's until the platform tells.
assert_eq!(
frame_of(&batch, document),
Some(rect(0.0, 0.0, 640.0, 560.0))
);
let first = frame_of(&batch, free_size).expect("the window root's frame");
assert_ne!(first, main);
assert_eq!(first.size, size(px(200.0), px(100.0)));
// The platform reports their sizes: laid out at them, and again
// at each new one.
c.set_root_size(free_size, size(px(500.0), px(400.0)), EdgeInsets::default());
c.set_root_size(document, size(px(700.0), px(600.0)), EdgeInsets::default());
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, free_size),
Some(rect(0.0, 0.0, 500.0, 400.0))
);
assert_eq!(
frame_of(&batch, document),
Some(rect(0.0, 0.0, 700.0, 600.0))
);
c.set_root_size(free_size, size(px(520.0), px(300.0)), EdgeInsets::default());
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, free_size),
Some(rect(0.0, 0.0, 520.0, 300.0))
);
}
/// A plain dialog next to a window of the app's own.
#[component]
fn DialogBesideWindow() -> impl IntoElement {
view()
.child(
view()
.p(px(30.0))
.child(modal().child(text("plain dialog"))),
)
.child(window().id("side").content(|| text("side")))
}
#[test]
fn plain_dialog_roots_fill_the_main_window() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
c.set_viewport(size(px(1100.0), px(820.0)));
c.mount_root(&Root::of::<DialogBesideWindow>());
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id, text, .. } if &*text.text == "plain dialog" => Some(*id),
_ => None,
})
.expect("the dialog's text");
let dialog = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Insert { parent, child, .. } if *child == text => Some(*parent),
_ => None,
})
.expect("the dialog's root");
// The main window's size, wherever its node is, a window of the
// app's own open or not; its window is the main one.
assert_eq!(
frame_of(&batch, dialog),
Some(rect(0.0, 0.0, 1100.0, 820.0))
);
let config = batch.items.iter().find_map(|i| match i {
MountItem::ModalConfig { id, config } if *id == dialog => Some(config.clone()),
_ => None,
});
assert_eq!(config.map(|c| c.window), Some(ROOT_ID));
// The main window resized: so is it.
c.set_viewport(size(px(900.0), px(700.0)));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, dialog), Some(rect(0.0, 0.0, 900.0, 700.0)));
}
#[test]
fn rust_windows_render_nothing_off_desktops() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Ios,
..Default::default()
});
c.mount_root(&Root::of::<Windows>());
let batch = c.commit().unwrap();
assert!(window_commands(&batch).is_empty());
}
}
mod rust_menus {
use super::*;
use crate::{
PayloadValue, PressEvent,
desktop::{DesktopCommand, MenuItem as Item, MenuRole},
element::{
Root,
desktop::{MenuItem, popup_menu_at, set_application_menu, window},
},
keymap::Modifiers,
platform::Os,
prelude::*,
};
/// An application menu following a signal, and a context menu shown by
/// a press, which says whether Shift was held.
#[component]
fn Menus() -> impl IntoElement {
window().id("main").title("Notes").content(menus_body)
}
#[component]
fn MenusBody() -> impl IntoElement {
let wrap = signal(false);
let log = signal(String::from("ready"));
effect(move || {
set_application_menu(vec![MenuItem::submenu(
"View",
[
MenuItem::new("Word Wrap")
.shortcut("mod+shift+w")
.checked(wrap.get())
.on_select(move || wrap.update(|w| *w = !*w)),
MenuItem::separator(),
MenuItem::role(MenuRole::ToggleFullScreen),
],
)]);
});
view()
.child(text(move || format!("wrap {}", wrap.get())))
.child(text(move || log.get()))
.child(text("More").on_press(move |e: &PressEvent| {
let shift = e.modifiers.shift;
let closed = popup_menu_at(
vec![
MenuItem::new("Rename")
.on_select(move || log.set(format!("rename {shift}"))),
],
e.page_position,
);
spawn(async move {
closed.await;
log.update(|l| l.push_str(" closed"));
});
}))
}
fn desktop(command: &MountItem) -> Option<&DesktopCommand> {
match command {
MountItem::Command {
id: ROOT_ID,
command: Command::Desktop(command),
} => Some(command),
_ => None,
}
}
/// The id and checked state of the application menu's first item.
fn first_action(batch: &MountBatch) -> (u32, Option<bool>) {
let menu = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::SetMenu(Some(items)) => Some(items.clone()),
_ => None,
})
.expect("the application menu");
let Item::Submenu { label, items, .. } = &menu[0] else {
panic!("a submenu: {menu:?}");
};
assert_eq!(label, "View");
let Item::Action(wrap) = &items[0] else {
panic!("an action: {items:?}");
};
assert_eq!(wrap.label, "Word Wrap");
// `mod` is Control off macOS.
assert_eq!(
wrap.shortcut,
Some(crate::desktop::Shortcut::parse("ctrl+shift+w", false).unwrap())
);
let Item::Action(full) = &items[2] else {
panic!("an action: {items:?}");
};
// A role's item: the platform's shortcut, nothing for the app.
assert_eq!(
(full.id, full.shortcut),
(0, MenuRole::ToggleFullScreen.shortcut(false))
);
(wrap.id, wrap.checked)
}
/// A menu with an icon of each source Rust gives.
#[component]
fn IconMenus() -> impl IntoElement {
const LOGO: ImageAsset = ImageAsset {
url: "asset:/@app/logo.png",
size: crate::geometry::Size {
width: Points(16.0),
height: Points(16.0),
},
scales: &[1.0, 2.0],
};
set_application_menu(vec![
MenuItem::submenu(
"File",
[
MenuItem::new("New").icon("data:image/svg+xml,%3Csvg/%3E"),
MenuItem::new("Logo").icon(LOGO),
MenuItem::new("Empty").icon(""),
MenuItem::new("None"),
MenuItem::role(MenuRole::Quit).icon("asset:/quit.svg"),
],
)
.icon("asset:/file.svg"),
]);
view()
}
#[test]
fn menu_labels_follow_the_language_the_app_shows() {
use crate::platform::{Languages, Locale};
let labels_in = |batch: &MountBatch| {
batch.items.iter().filter_map(desktop).find_map(|command| {
if let DesktopCommand::SetMenuLabels(labels) = command {
Some((**labels).clone())
} else {
None
}
})
};
let mut first = core();
let mut env = crate::element::Environment {
os: Os::MacOs,
locale: Locale::parse("en").unwrap(),
..Default::default()
};
env.locale_settings.languages = Languages::one(env.locale);
first.set_environment(env);
let labels = labels_in(&first.commit().unwrap()).unwrap();
assert_eq!(labels.label(MenuRole::Copy), "Copy");
env.locale = Locale::parse("ja-JP").unwrap();
env.locale_settings.languages = Languages::one(env.locale);
first.set_environment(env);
let labels = labels_in(&first.commit().unwrap()).unwrap();
assert_eq!(labels.label(MenuRole::Copy), "コピー");
assert_eq!(labels.label(MenuRole::Paste), "ペースト");
assert_eq!(labels.edit_menu.as_deref(), Some("編集"));
// With an English-only app dictionary, text falls back to English
// even when all of the user's preferred languages are Japanese.
first.set_translations(
crate::i18n::Translations::from_json(r#"{"en":{"hello":"Hello"}}"#).unwrap(),
);
let labels = labels_in(&first.commit().unwrap()).unwrap();
assert_eq!(labels.label(MenuRole::Copy), "Copy");
assert_eq!(labels.edit_menu.as_deref(), Some("Edit"));
// Adding Japanese translations at run time switches the menu labels
// back to Japanese without resetting the surface.
first.add_translations(std::collections::HashMap::from([(
"ja".to_owned(),
std::collections::HashMap::from([("hello".to_owned(), "こんにちは".to_owned())]),
)]));
let labels = labels_in(&first.commit().unwrap()).unwrap();
assert_eq!(labels.label(MenuRole::Copy), "コピー");
assert_eq!(labels.edit_menu.as_deref(), Some("編集"));
// Mobile platforms use the system's own menus.
env.os = Os::Ios;
first.set_environment(env);
assert!(first.commit().as_ref().and_then(labels_in).is_none());
env.os = Os::MacOs;
env.idiom = crate::platform::Idiom::Terminal;
first.set_environment(env);
assert!(first.commit().as_ref().and_then(labels_in).is_none());
}
#[test]
fn mobile_platforms_hear_the_language_the_app_shows() {
use crate::platform::{Languages, Locale};
let sent = |batch: Option<MountBatch>| -> Vec<String> {
batch
.map(|batch| {
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
id: ROOT_ID,
command: Command::TextLocale(locale),
} => Some(locale.to_string()),
_ => None,
})
.collect()
})
.unwrap_or_default()
};
let mut c = core();
let mut env = crate::element::Environment {
os: Os::Android,
locale: Locale::parse("ja-JP").unwrap(),
..Default::default()
};
env.locale_settings.languages = Languages::one(env.locale);
c.set_environment(env);
assert_eq!(sent(c.commit()), ["ja-JP"]);
// Another region of the same language is told; the same one is not.
env.locale = Locale::parse("ja").unwrap();
env.locale_settings.languages = Languages::one(env.locale);
c.set_environment(env);
assert_eq!(sent(c.commit()), ["ja"]);
env.dark = true;
c.set_environment(env);
assert_eq!(sent(c.commit()), Vec::<String>::new());
// An English-only app shows its text in English.
c.set_translations(
crate::i18n::Translations::from_json(r#"{"en":{"hello":"Hello"}}"#).unwrap(),
);
assert_eq!(sent(c.commit()), ["en-US"]);
// Translations added at run time bring the user's language back.
c.add_translations(std::collections::HashMap::from([(
"ja".to_owned(),
std::collections::HashMap::from([("hello".to_owned(), "こんにちは".to_owned())]),
)]));
assert_eq!(sent(c.commit()), ["ja"]);
// Desktops and browsers speak states in the screen reader's words.
for os in [Os::MacOs, Os::Linux, Os::Web] {
let mut c = core();
c.set_environment(crate::element::Environment {
os,
locale: Locale::parse("ko").unwrap(),
..Default::default()
});
assert_eq!(sent(c.commit()), Vec::<String>::new(), "{os:?}");
}
}
fn menu_event(c: &mut Core<FakeEngine>, fields: Vec<(&'static str, PayloadValue)>) -> bool {
c.component_event(ROOT_ID, EventKind::Menu, &EventPayload::Map(fields))
}
#[test]
fn rust_menus_run_their_items_and_presses_report_modifiers() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<Menus>());
let batch = c.commit().unwrap();
let open = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Command {
command: Command::Desktop(command),
..
} => match &**command {
DesktopCommand::OpenWindow(open) => Some(open.clone()),
_ => None,
},
_ => None,
})
.expect("the window opens");
assert_eq!(open.options.attributes.title.as_deref(), Some("Notes"));
let (id, checked) = first_action(&batch);
assert!(id >= 1 << 31, "views' ids are above JS's: {id}");
assert_eq!(checked, Some(false));
let more = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Text { id, text, .. } if text.text == "More" => Some(*id),
_ => None,
})
.unwrap();
// JS's ids are JS's.
assert!(!menu_event(&mut c, vec![("id", PayloadValue::Number(1.0))]));
// The chosen item runs; the effect sets the menu again, checked.
assert!(menu_event(
&mut c,
vec![("id", PayloadValue::Number(f64::from(id)))]
));
let batch = c.commit().unwrap();
assert!(texts_of(&batch).contains(&"wrap true".to_owned()));
let (again, checked) = first_action(&batch);
assert_eq!(checked, Some(true));
// The replaced menu's item no longer runs.
assert!(menu_event(
&mut c,
vec![("id", PayloadValue::Number(f64::from(id)))]
));
assert!(c.commit().is_none());
assert_ne!(again, id);
// A Shift-click shows a context menu where it was pressed.
let press = PressEvent {
page_position: point(px(30.0), px(40.0)),
modifiers: Modifiers {
shift: true,
..Default::default()
},
clicks: 1,
..Default::default()
};
assert!(c.component_event(more, EventKind::Press, &EventPayload::Press(press)));
let batch = c.commit().unwrap();
let (rename, at) = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::PopupMenu { items, at } => match &items[0] {
Item::Action(a) if a.label == "Rename" => Some((a.id, *at)),
_ => None,
},
_ => None,
})
.expect("the context menu");
assert_eq!(at, Some(point(px(30.0), px(40.0))));
assert!(menu_event(
&mut c,
vec![("id", PayloadValue::Number(f64::from(rename)))]
));
// Its closing is JS's to hear too (it settles a menu JS showed).
assert!(!menu_event(
&mut c,
vec![
("id", PayloadValue::Number(0.0)),
("closed", PayloadValue::Bool(true)),
],
));
let end = std::time::Instant::now() + std::time::Duration::from_secs(5);
let mut shown = Vec::new();
while !shown.contains(&"rename true closed".to_owned()) {
assert!(std::time::Instant::now() < end, "not closed: {shown:?}");
c.run_component_tasks();
if let Some(batch) = c.commit() {
shown.extend(texts_of(&batch));
}
}
// A press without Shift (or from the keyboard: no position).
assert!(c.component_event(more, EventKind::Press, &EventPayload::None));
let batch = c.commit().unwrap();
let rename = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::PopupMenu { items, at } => {
assert_eq!(*at, Some(point(px(0.0), px(0.0))));
match &items[0] {
Item::Action(a) => Some(a.id),
_ => None,
}
}
_ => None,
})
.unwrap();
assert!(menu_event(
&mut c,
vec![("id", PayloadValue::Number(f64::from(rename)))]
));
assert!(texts_of(&c.commit().unwrap()).contains(&"rename false".to_owned()));
}
#[test]
fn rust_menu_items_carry_their_icons() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: Os::Windows,
..Default::default()
});
c.mount_root(&Root::of::<IconMenus>());
let batch = c.commit().unwrap();
let menu = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::SetMenu(Some(items)) => Some(items.clone()),
_ => None,
})
.expect("the application menu");
let Item::Submenu { icon, items, .. } = &menu[0] else {
panic!("a submenu: {menu:?}");
};
assert_eq!(icon.as_ref().map(|i| &*i.uri), Some("asset:/file.svg"));
let icons: Vec<_> = items
.iter()
.map(|item| match item {
Item::Action(action) => action.icon.clone(),
other => panic!("an action: {other:?}"),
})
.collect();
// A `data:` URI has its bytes in hand, as an `<Image>`'s has.
let inline = icons[0].as_ref().expect("the data URI");
assert_eq!(inline.data.as_deref(), Some(&b"<svg/>"[..]));
// An asset has its size and scales.
let logo = icons[1].as_ref().expect("the asset");
assert_eq!(&*logo.uri, "asset:/@app/logo.png");
assert_eq!(logo.size, Some(crate::geometry::size_pt(16.0, 16.0)));
assert_eq!(logo.uri_for(2.0).as_ref(), "asset:/@app/logo@2x.png");
assert_eq!(
logo.at_pixel_ratio(2.0).uri.as_ref(),
"asset:/@app/logo@2x.png"
);
assert_eq!(icons[2], None, "an empty URL is no image");
assert_eq!(icons[3], None);
assert_eq!(icons[4].as_ref().map(|i| &*i.uri), Some("asset:/quit.svg"));
}
/// Inline sections leave the element API expanded: items between
/// separators, their labels not shown.
#[test]
fn rust_menus_expand_inline_sections_before_the_platform() {
#[component]
fn InlineMenus() -> impl IntoElement {
set_application_menu(vec![MenuItem::submenu(
"File",
[
MenuItem::new("New"),
MenuItem::submenu("Danger", [MenuItem::new("Delete"), MenuItem::new("Wipe")])
.inline(true),
MenuItem::new("Quit"),
],
)]);
view().child(text("ready").on_press(move |e: &PressEvent| {
drop(popup_menu_at(
vec![
MenuItem::new("Rename"),
MenuItem::submenu("More", [MenuItem::new("Duplicate")]).inline(true),
MenuItem::new("Delete"),
],
e.page_position,
));
}))
}
let mut c = core();
c.set_environment(crate::element::Environment {
os: Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<InlineMenus>());
let batch = c.commit().unwrap();
let menu = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::SetMenu(Some(items)) => Some(items.clone()),
_ => None,
})
.expect("the application menu");
let Item::Submenu { items, .. } = &menu[0] else {
panic!("a submenu: {menu:?}");
};
let labels: Vec<_> = items
.iter()
.map(|i| match i {
Item::Separator => "—",
Item::Action(a) => a.label.as_str(),
Item::Submenu { label, inline, .. } => {
assert!(!inline, "inline already expanded");
label.as_str()
}
})
.collect();
assert_eq!(labels, ["New", "—", "Delete", "Wipe", "—", "Quit"]);
let ready = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Text { id, text, .. } if text.text == "ready" => Some(*id),
_ => None,
})
.unwrap();
let press = PressEvent {
page_position: point(px(10.0), px(20.0)),
..Default::default()
};
assert!(c.component_event(ready, EventKind::Press, &EventPayload::Press(press)));
let batch = c.commit().unwrap();
let popup = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::PopupMenu { items, .. } => Some(items.clone()),
_ => None,
})
.expect("the context menu");
let popup_labels: Vec<_> = popup
.iter()
.map(|i| match i {
Item::Separator => "—",
Item::Action(a) => a.label.as_str(),
Item::Submenu { .. } => "sub",
})
.collect();
assert_eq!(popup_labels, ["Rename", "—", "Duplicate", "—", "Delete"]);
}
#[test]
fn rust_menus_do_nothing_off_desktops() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: Os::Ios,
..Default::default()
});
c.mount_root(&Root::of::<Menus>());
let batch = c.commit().unwrap();
assert!(!batch.items.iter().filter_map(desktop).any(|c| matches!(
c,
DesktopCommand::SetMenu(_) | DesktopCommand::PopupMenu { .. }
)));
}
/// A tray with a menu and a click, and a global shortcut, from Rust.
#[component]
fn TrayAndShortcut() -> impl IntoElement {
let log = signal(String::from("ready"));
crate::element::desktop::set_tray(
crate::element::desktop::tray()
.tooltip("Player")
.title([
crate::desktop::TrayTitleRun::new("Now "),
crate::desktop::TrayTitleRun::new("playing").color(crate::color::rgb(0xd92d20)),
])
.title_placement(crate::desktop::TrayTitlePlacement::Left)
.menu([MenuItem::new("Pause").on_select(move || log.set("pause".into()))])
.on_click(move |e| log.set(format!("click {}", e.bounds.is_some()))),
);
let taken = crate::element::desktop::register_global_shortcut("ctrl+alt+p", move || {
log.update(|l| l.push_str(" pressed"))
});
spawn(async move {
let taken = taken.await;
log.update(|l| l.push_str(&format!(" taken {taken}")));
});
view().child(text(move || log.get()))
}
#[test]
fn rust_tray_and_global_shortcuts_run_their_handlers() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: Os::Linux,
..Default::default()
});
c.mount_root(&Root::of::<TrayAndShortcut>());
let batch = c.commit().unwrap();
let tray = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::SetTray(Some(tray)) => Some(tray.clone()),
_ => None,
})
.expect("the tray");
assert_eq!(tray.tooltip, "Player");
assert_eq!(
tray.title,
[
crate::desktop::TrayTitleRun::new("Now "),
crate::desktop::TrayTitleRun::new("playing").color(crate::color::rgb(0xd92d20)),
]
);
assert_eq!(
tray.title_placement,
crate::desktop::TrayTitlePlacement::Left
);
assert!(tray.click >= 1 << 31);
let Item::Action(pause) = &tray.menu[0] else {
panic!("an action: {:?}", tray.menu);
};
let global = batch
.items
.iter()
.filter_map(desktop)
.find_map(|c| match c {
DesktopCommand::RegisterGlobalShortcut { id, shortcut } => Some((*id, *shortcut)),
_ => None,
})
.expect("the global shortcut");
assert_eq!(
global.1,
crate::desktop::Shortcut::parse("ctrl+alt+p", false).unwrap()
);
let n = |id: u32| PayloadValue::Number(f64::from(id));
assert!(menu_event(
&mut c,
vec![
("id", n(global.0)),
("registered", PayloadValue::Bool(true))
]
));
assert!(menu_event(&mut c, vec![("id", n(global.0))]));
let mut shown = texts_of(&c.commit().unwrap());
let end = std::time::Instant::now() + std::time::Duration::from_secs(5);
while !shown.contains(&"ready pressed taken true".to_owned()) {
assert!(std::time::Instant::now() < end, "not answered: {shown:?}");
c.run_component_tasks();
if let Some(batch) = c.commit() {
shown.extend(texts_of(&batch));
}
}
assert!(menu_event(&mut c, vec![("id", n(pause.id))]));
let batch = c.commit().unwrap();
assert!(texts_of(&batch).contains(&"pause".to_owned()));
let bounds = crate::geometry::Bounds::new(
crate::geometry::point(Points(10.0), Points(0.0)),
crate::geometry::Size {
width: Points(24.0),
height: Points(24.0),
},
);
assert!(menu_event(
&mut c,
vec![
("id", n(tray.click)),
("bounds", PayloadValue::Bounds(bounds))
]
));
let batch = c.commit().unwrap();
assert!(texts_of(&batch).contains(&"click true".to_owned()));
}
}
#[test]
fn file_drop_callbacks_keep_urls_and_disabled_targets_unmount_their_events() {
use crate::prelude::*;
#[component]
fn DropView() -> impl IntoElement {
let received = signal(String::new());
let disabled = signal(false);
view()
.disabled(move || disabled.get())
.on_press(move |_: &()| disabled.set(true))
.on_file_drag_enter(move |event: &crate::element::FileDragEvent| {
received.set(format!("enter {}", event.uris.join("\n")))
})
.on_file_drag_leave(|_: &()| {})
.on_file_drop(move |event: &crate::element::FileDropEvent| {
received.set(event.uris.join("\n"))
})
.child(text(move || received.get()))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<DropView>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if events.contains(EventKind::FileDrop) => Some(*id),
_ => None,
})
.unwrap();
let uris = vec![
"file:///tmp/a%20b.txt".into(),
"file:///tmp/%E4%B8%AD%E6%96%87/".into(),
];
assert!(c.component_event(
host,
EventKind::FileDragEnter,
&EventPayload::FileDrop(uris.clone())
));
let entered = c.commit().unwrap();
assert!(entered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == format!("enter {}", uris.join("\n")))));
assert!(c.component_event(
host,
EventKind::FileDrop,
&EventPayload::FileDrop(uris.clone())
));
let delivered = c.commit().unwrap();
assert!(delivered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == uris.join("\n"))));
assert!(c.component_event(host, EventKind::Press, &EventPayload::None));
let disabled = c.commit().unwrap();
let events = disabled
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if *id == host => Some(*events),
_ => None,
})
.unwrap();
for event in [
EventKind::FileDragEnter,
EventKind::FileDragLeave,
EventKind::FileDrop,
] {
assert!(!events.contains(event));
}
}
#[test]
fn mouse_moves_reach_rust_listeners_with_their_positions_modifiers_and_buttons() {
use crate::prelude::*;
#[component]
fn Crosshair() -> impl IntoElement {
let at = signal(String::new());
view()
.on_mouse_move(move |e: &MouseEvent| {
at.set(format!(
"{} {} {} {} {} {:?}",
e.position.x.0,
e.position.y.0,
e.page_position.x.0,
e.page_position.y.0,
e.modifiers.shift,
e.pressed_button
))
})
.child(text(move || at.get()))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Crosshair>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if events.contains(EventKind::MouseMove) => Some(*id),
_ => None,
})
.expect("the listening view mounts MouseMove in its event mask");
let event = crate::MouseEvent::new(
point(px(4.0), px(5.0)),
point(px(14.0), px(25.0)),
crate::keymap::Modifiers {
shift: true,
..Default::default()
},
Some(crate::MouseButton::Left),
);
assert!(c.component_event(host, EventKind::MouseMove, &EventPayload::Mouse(event)));
let delivered = c.commit().unwrap();
assert!(delivered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == "4 5 14 25 true Some(Left)")));
// One sent without a payload (an embedder's, a script's) still reaches
// the listener, at no known position.
assert!(c.component_event(host, EventKind::MouseMove, &EventPayload::None));
let delivered = c.commit().unwrap();
assert!(delivered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == "0 0 0 0 false None")));
}
#[test]
fn mouse_ups_reach_rust_listeners_with_their_positions_and_button() {
use crate::prelude::*;
#[component]
fn Release() -> impl IntoElement {
let at = signal(String::new());
view()
.on_mouse_up(move |e: &MouseEvent| {
at.set(format!(
"{} {} {} {} {:?}",
e.position.x.0,
e.position.y.0,
e.page_position.x.0,
e.page_position.y.0,
e.button.unwrap()
))
})
.child(text(move || at.get()))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Release>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if events.contains(EventKind::MouseUp) => Some(*id),
_ => None,
})
.expect("the listening view mounts MouseUp in its event mask");
let event = crate::MouseEvent::released(
point(px(6.0), px(7.0)),
point(px(16.0), px(27.0)),
crate::keymap::Modifiers::default(),
crate::MouseButton::Right,
);
assert!(c.component_event(host, EventKind::MouseUp, &EventPayload::Mouse(event)));
let delivered = c.commit().unwrap();
assert!(delivered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == "6 7 16 27 Right")));
}
#[test]
fn retained_views_clear_omitted_capture_rules() {
use crate::prelude::*;
#[component]
fn Configured() -> impl IntoElement {
let configured = signal(true);
view()
.on_press(move || configured.set(false))
.child(dynamic(move || {
view()
.key("pad")
.when(configured.get(), |view| view.capture_keys(KeyCapture::All))
}))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Configured>());
let initial = c.commit().unwrap();
let trigger = initial
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap();
let pad = initial
.items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props } if props.key_capture == KeyCapture::All => Some(*id),
_ => None,
})
.unwrap();
c.component_event(trigger, EventKind::Press, &EventPayload::None);
let changed = c.commit().unwrap();
assert!(!changed.items.iter().any(|item| matches!(item,
MountItem::Delete { id } if *id == pad
)));
let cleared = changed
.items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props } if *id == pad => Some(props),
_ => None,
})
.expect("omitted props must clear the retained native view");
assert_eq!(cleared.key_capture, KeyCapture::None);
}
#[test]
fn key_capture_reads_mounted_rules_with_canonical_strokes() {
use crate::{keymap::Keystroke, prelude::*};
let stroke = Keystroke::parse_with("mod+k", true).unwrap();
#[component]
fn Captured() -> impl IntoElement {
view()
.capture_keys(KeyCapture::keys([
Keystroke::parse_with("mod+k", true).unwrap()
]))
.child(view())
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Captured>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props }
if props.key_capture == KeyCapture::keys([stroke]) =>
{
Some(*id)
}
_ => None,
})
.expect("the capture rule mounts");
// Command+K on Apple conventions; the same stroke's key with no
// modifier is not it.
assert!(c.key_captured(host, Some(&stroke)));
let plain_k = Keystroke::parse_with("k", true).unwrap();
assert!(!c.key_captured(host, Some(&plain_k)));
// The path reaches the focused view and its ancestors, ending at the
// window's root.
let mut path = Vec::new();
c.key_path(host, &mut path);
assert_eq!(path.first(), Some(&host));
assert_eq!(path.last(), Some(&crate::ROOT_ID));
}
/// Capture matches the stroke the adapter's own shortcut vocabulary names,
/// never a stroke derived from the event's `code`: a browser whose
/// `KeyboardEvent.code` differs from the logical key (NumLock-off Numpad1
/// for End, AZERTY `z` on KeyW) captures what its existing shortcut matcher
/// would, and the event's physical identity does not decide.
#[test]
fn key_capture_uses_the_adapters_stroke_not_the_physical_code() {
use crate::{keymap::Keystroke, prelude::*};
let end = Keystroke::parse_with("end", false).unwrap();
let z = Keystroke::parse_with("z", false).unwrap();
#[component]
fn Captured() -> impl IntoElement {
view()
.capture_keys(KeyCapture::keys([
Keystroke::parse_with("end", false).unwrap(),
Keystroke::parse_with("z", false).unwrap(),
]))
.child(view())
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Captured>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props }
if props.key_capture == KeyCapture::keys([end, z]) =>
{
Some(*id)
}
_ => None,
})
.expect("the capture rule mounts");
// The transition's DOM codes name other US-layout keys (`Numpad1` is
// `1`, `KeyW` is `w`); the adapter's stroke alone matches.
let numeric_one = Keystroke::parse_with("1", false).unwrap();
let w = Keystroke::parse_with("w", false).unwrap();
assert!(c.key_captured(host, Some(&end)));
assert!(!c.key_captured(host, Some(&numeric_one)));
assert!(c.key_captured(host, Some(&z)));
assert!(!c.key_captured(host, Some(&w)));
// No shortcut names it: only `All` captures it.
assert!(!c.key_captured(host, None));
}
#[test]
fn key_interest_walks_portaled_overlay_logical_ancestors() {
use crate::prelude::*;
#[component]
fn Portals() -> impl IntoElement {
let popup = || {
overlay()
.test_id("capturing-portal")
.child(view().test_id("inside").focusable(true))
};
view()
.child(
view()
.test_id("holder")
.capture_keys(KeyCapture::All)
.child(popup()),
)
.child(
view()
.test_id("listener")
.on_key_down(|_: &KeyEvent| {})
.child(
overlay()
.test_id("listening-portal")
.child(view().test_id("heard").focusable(true)),
),
)
.child(
overlay()
.test_id("unrelated-portal")
.child(view().test_id("outside").focusable(true)),
)
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Portals>());
let batch = c.commit().unwrap();
let view = |wanted: &str| {
batch
.items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(wanted) => {
Some(*id)
}
_ => None,
})
.unwrap_or_else(|| panic!("{wanted} is mounted"))
};
let (holder, inside, heard, outside) = (
view("holder"),
view("inside"),
view("heard"),
view("outside"),
);
// The overlay content is not a native child of the view it is in, but
// it is its logical descendant: interest and capture follow the
// logical ancestor, and never the unrelated sibling portal.
assert!(c.key_interest(inside));
assert!(c.key_interest(heard));
assert!(!c.key_interest(outside));
assert!(c.key_captured(inside, None));
assert!(!c.key_captured(outside, None));
// The engine's notification path keeps the same logical ancestor.
let mut path = Vec::new();
c.key_path(inside, &mut path);
assert!(path.contains(&holder), "{path:?}");
// The overlays whose logical ancestry has key interest carry the
// routing override; the unrelated one carries none.
let routed_parent = |name| {
let id = view(name);
batch
.items
.iter()
.rev()
.find_map(|item| match item {
MountItem::ViewProps { id: target, props } if *target == id => {
Some(props.key_parent)
}
_ => None,
})
.expect("the portal's final native props")
};
assert_eq!(routed_parent("capturing-portal"), Some(holder));
assert_eq!(routed_parent("listening-portal"), Some(view("listener")));
assert_eq!(routed_parent("unrelated-portal"), None);
}
#[test]
fn context_menus_reach_rust_listeners_with_their_positions() {
use crate::prelude::*;
#[component]
fn Row() -> impl IntoElement {
let at = signal(String::new());
view()
.on_context_menu(move |e: &ContextMenuEvent| {
at.set(format!(
"{} {} {} {}",
e.position.x.0, e.position.y.0, e.page_position.x.0, e.page_position.y.0
))
})
.child(text(move || at.get()))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Row>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if events.contains(EventKind::ContextMenu) => {
Some(*id)
}
_ => None,
})
.expect("the listening view mounts ContextMenu in its event mask");
let event = crate::ContextMenuEvent {
position: point(px(4.0), px(5.0)),
page_position: point(px(14.0), px(25.0)),
pointer_type: Some(crate::PointerType::Mouse),
..Default::default()
};
assert!(c.component_event(
host,
EventKind::ContextMenu,
&EventPayload::ContextMenu(event)
));
let delivered = c.commit().unwrap();
assert!(delivered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == "4 5 14 25")));
}
#[test]
fn pinches_reach_rust_listeners_with_their_delta_and_phase() {
use crate::prelude::*;
#[component]
fn Canvas() -> impl IntoElement {
let at = signal(String::new());
view()
.on_pinch(move |e: &PinchEvent| {
at.set(format!(
"{} {} {} {}",
e.position.x.0,
e.page_position.y.0,
e.delta.0,
e.phase.name()
))
})
.child(text(move || at.get()))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Canvas>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if events.contains(EventKind::Pinch) => Some(*id),
_ => None,
})
.expect("the listening view mounts Pinch in its event mask");
let event = crate::PinchEvent::new(
point(px(4.0), px(5.0)),
point(px(14.0), px(25.0)),
crate::geometry::Percentage(0.5),
crate::PinchPhase::Move,
Default::default(),
);
assert!(c.component_event(host, EventKind::Pinch, &EventPayload::Pinch(event)));
let delivered = c.commit().unwrap();
assert!(delivered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == "4 25 0.5 move")));
}
#[test]
fn wheels_reach_rust_listeners_with_their_delta() {
use crate::prelude::*;
#[component]
fn Canvas() -> impl IntoElement {
let at = signal(String::new());
view()
.on_wheel(move |e: &WheelEvent| {
let (dx, dy) = e.delta.xy();
at.set(format!(
"{} {} {dx} {dy} {} {}",
e.position.x.0,
e.page_position.y.0,
e.delta.precise(),
e.modifiers.ctrl
))
})
.child(text(move || at.get()))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Canvas>());
let batch = c.commit().unwrap();
let host = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Events { id, events } if events.contains(EventKind::Wheel) => Some(*id),
_ => None,
})
.expect("the listening view mounts Wheel in its event mask");
let event = crate::WheelEvent::new(
point(px(4.0), px(5.0)),
point(px(14.0), px(25.0)),
crate::WheelDelta::Lines(point(0.0, -2.0)),
crate::keymap::Modifiers {
ctrl: true,
..Default::default()
},
);
assert!(c.component_event(host, EventKind::Wheel, &EventPayload::Wheel(event)));
let delivered = c.commit().unwrap();
assert!(delivered.items.iter().any(|item| matches!(item,
MountItem::Text { text, .. } if text.text == "4 25 0 -2 false true")));
}
/// A container `2` with `style` and empty children `4`, `6`, ... with
/// theirs, laid out at the root; the children's frames.
fn grid_frames(
container: &[(&str, StyleValue<'_>)],
children: &[&[(&str, StyleValue<'_>)]],
) -> Vec<Bounds<Points>> {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, container),
];
for (i, child) in children.iter().enumerate() {
let id = 4 + 2 * i as NodeId;
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(id, child));
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
(0..children.len())
.map(|i| frame_of(&batch, 4 + 2 * i as NodeId).expect("a frame"))
.collect()
}
#[test]
fn grids_place_items_by_line_name() {
let s = StyleValue::Str;
let grid = [
("display", s("grid")),
("width", StyleValue::Number(300.0)),
("gridTemplateColumns", s("[a] 40px [b] 60px [c] 1fr [d]")),
];
let f = grid_frames(
&grid,
&[
&[("gridColumnStart", s("b"))],
&[("gridColumn", s("a / c"))],
&[("gridColumn", s("b / span d"))],
&[("gridColumnStart", s("c")), ("gridColumnEnd", s("d"))],
],
);
let xw = |r: Bounds<Points>| (r.origin.x.0, r.size.width.0);
assert_eq!(xw(f[0]), (40.0, 60.0));
assert_eq!(xw(f[1]), (0.0, 100.0));
assert_eq!(xw(f[2]), (40.0, 260.0));
assert_eq!(xw(f[3]), (100.0, 200.0));
// Several names per line, names in repetitions.
let f = grid_frames(
&[
("display", s("grid")),
("width", StyleValue::Number(300.0)),
(
"gridTemplateColumns",
s("[full-start] 20px [main-start] repeat(2, [col] 1fr) [main-end] 20px [full-end]"),
),
],
&[
&[("gridColumn", s("main-start / main-end"))],
&[("gridColumn", s("2 col / full-end"))],
&[("gridColumn", s("full-start / full-end"))],
],
);
assert_eq!(xw(f[0]), (20.0, 260.0));
assert_eq!(xw(f[1]), (150.0, 150.0));
assert_eq!(xw(f[2]), (0.0, 300.0));
}
#[test]
fn grid_auto_tracks_stretch_unless_aligned() {
let s = StyleValue::Str;
let n = StyleValue::Number;
let grid = [
("display", s("grid")),
("width", n(300.0)),
("height", n(200.0)),
("gridTemplateColumns", s("1fr 1fr")),
];
// CSS's `normal`: the auto rows share the container's height.
let f = grid_frames(&grid, &[&[], &[], &[]]);
assert_eq!((f[0].origin.y.0, f[0].size.height.0), (0.0, 100.0));
assert_eq!((f[2].origin.y.0, f[2].size.height.0), (100.0, 100.0));
let mut normal = grid.to_vec();
normal.push(("alignContent", s("normal")));
assert_eq!(grid_frames(&normal, &[&[]])[0].size.height.0, 200.0);
// Columns too, without a template.
let f = grid_frames(&grid[..3], &[&[]]);
assert_eq!(f[0].size.width.0, 300.0);
// A value set explicitly applies.
let mut start = grid.to_vec();
start.push(("alignContent", s("flex-start")));
assert_eq!(grid_frames(&start, &[&[]])[0].size.height.0, 0.0);
let mut start = grid[..3].to_vec();
start.push(("justifyContent", s("start")));
assert_eq!(grid_frames(&start, &[&[]])[0].size.width.0, 0.0);
// Flex containers keep React Native's `flex-start` for wrapped lines.
let f = grid_frames(
&[
("flexDirection", s("row")),
("flexWrap", s("wrap")),
("width", n(300.0)),
("height", n(200.0)),
],
&[&[("width", n(200.0))], &[("width", n(200.0))]],
);
assert_eq!((f[0].size.height.0, f[1].origin.y.0), (0.0, 0.0));
}
/// A container `2` with `classes` and empty children `4`, `6`, ... with
/// theirs, laid out at the root; the children's frames.
fn class_frames(classes: &str, children: &[&str]) -> Vec<Bounds<Points>> {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, classes),
];
for (i, child) in children.iter().enumerate() {
let id = 4 + 2 * i as NodeId;
ops.push(Op::Create { id, tag: Tag::View });
ops.push(class_op(id, child));
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
(0..children.len())
.map(|i| frame_of(&batch, 4 + 2 * i as NodeId).expect("a frame"))
.collect()
}
/// The alignment classes lay out as their Tailwind CSS declarations do in
/// a browser.
#[test]
fn alignment_classes_lay_out_as_in_a_browser() {
let yh = |r: Bounds<Points>| (r.origin.y.0, r.size.height.0);
let grid = "grid grid-cols-2 w-[300px] h-[200px]";
// Unset (`normal`) and `content-normal`: the auto rows stretch.
let f = class_frames(grid, &["", "", ""]);
assert_eq!((yh(f[0]), yh(f[2])), ((0.0, 100.0), (100.0, 100.0)));
let f = class_frames(&format!("{grid} content-normal"), &["", "", ""]);
assert_eq!(yh(f[2]), (100.0, 100.0));
// `content-start` (`align-content: flex-start`) packs them at the start.
let f = class_frames(&format!("{grid} content-start"), &["h-5", "", "h-8"]);
assert_eq!((yh(f[0]), yh(f[2])), ((0.0, 20.0), (20.0, 32.0)));
// `justify-normal` stretches auto columns; `place-content-start`
// packs both axes.
let free = "grid w-[300px] h-[200px]";
let f = class_frames(&format!("{free} justify-normal"), &[""]);
assert_eq!((f[0].size.width.0, f[0].size.height.0), (300.0, 200.0));
let f = class_frames(&format!("{free} place-content-start"), &[""]);
assert_eq!((f[0].size.width.0, f[0].size.height.0), (0.0, 0.0));
let f = class_frames(&format!("{free} place-content-end"), &["w-10 h-5"]);
assert_eq!((f[0].origin.x.0, f[0].origin.y.0), (260.0, 180.0));
// Items: `place-items-end`, `justify-items-start`.
let cells = "grid grid-cols-[100px] grid-rows-[40px] w-[300px]";
let f = class_frames(&format!("{cells} place-items-end"), &["w-10 h-5"]);
assert_eq!((f[0].origin.x.0, f[0].origin.y.0), (60.0, 20.0));
let f = class_frames(&format!("{cells} justify-items-start"), &["w-10"]);
assert_eq!((f[0].origin.x.0, f[0].size.height.0), (0.0, 40.0));
// Flex containers: unset keeps React Native's `flex-start` for wrapped
// lines, as before; `content-start` is the same, and `content-normal`
// stretches the lines, as CSS's `normal` does there.
let flex = "flex flex-wrap w-[300px] h-[200px]";
let lines = ["w-[200px]", "w-[200px]"];
let f = class_frames(flex, &lines);
assert_eq!((yh(f[0]), yh(f[1])), ((0.0, 0.0), (0.0, 0.0)));
let f = class_frames(&format!("{flex} content-start"), &lines);
assert_eq!((yh(f[0]), yh(f[1])), ((0.0, 0.0), (0.0, 0.0)));
let f = class_frames(&format!("{flex} content-normal"), &lines);
assert_eq!((yh(f[0]), yh(f[1])), ((0.0, 100.0), (100.0, 100.0)));
// `justify-normal` is `flex-start` in a flex container.
let f = class_frames("flex w-[300px] justify-normal", &["w-10"]);
assert_eq!(f[0].origin.x.0, 0.0);
}
#[test]
fn start_and_end_follow_the_writing_direction() {
let s = StyleValue::Str;
let n = StyleValue::Number;
let item = [("width", n(50.0)), ("height", n(20.0))];
let grid = |justify: &'static str, direction: &'static str| {
[
("display", s("grid")),
("width", n(300.0)),
("height", n(100.0)),
("gridTemplateColumns", s("100px")),
("gridTemplateRows", s("40px")),
("justifyItems", s(justify)),
("alignItems", s("end")),
("direction", s(direction)),
]
};
let f = grid_frames(&grid("start", "ltr"), &[&item]);
assert_eq!((f[0].origin.x.0, f[0].origin.y.0), (0.0, 20.0));
let f = grid_frames(&grid("end", "ltr"), &[&item]);
assert_eq!(f[0].origin.x.0, 50.0);
// Right to left, the track is at the right and its start is its right.
let f = grid_frames(&grid("start", "rtl"), &[&item]);
assert_eq!(f[0].origin.x.0, 250.0);
let f = grid_frames(&grid("end", "rtl"), &[&item]);
assert_eq!(f[0].origin.x.0, 200.0);
// Per item, and `self-start` / `self-end`.
let f = grid_frames(
&grid("start", "ltr"),
&[&[
("width", n(50.0)),
("justifySelf", s("self-end")),
("alignSelf", s("start")),
]],
);
assert_eq!((f[0].origin.x.0, f[0].origin.y.0), (50.0, 0.0));
// Tracks: `justifyContent: end` puts the column at the end.
let mut end = grid("start", "ltr").to_vec();
end.push(("justifyContent", s("end")));
assert_eq!(grid_frames(&end, &[&item])[0].origin.x.0, 200.0);
let mut end = grid("start", "rtl").to_vec();
end.push(("justifyContent", s("end")));
assert_eq!(grid_frames(&end, &[&item])[0].origin.x.0, 50.0);
// In flex containers too.
let f = grid_frames(
&[
("width", n(300.0)),
("alignItems", s("end")),
("justifyContent", s("end")),
("height", n(100.0)),
],
&[&item],
);
assert_eq!((f[0].origin.x.0, f[0].origin.y.0), (250.0, 80.0));
}
/// What builders take: listeners without arguments, children in an
/// `Option`, a `Vec`, an array or an iterator.
mod builders {
use super::*;
use crate::{
element::{Listener, Root},
prelude::*,
};
/// The mount items of `C`'s first frame and of the frames after a press
/// on each text of `taps`, in order.
fn run<C: Component>(
props: impl Fn() -> C::Props + Send + Sync + 'static,
taps: &[&str],
) -> Vec<String> {
let mut c = core();
c.mount_root(&Root::new::<C>(props));
let mut nodes = std::collections::HashMap::new();
let mut out = Vec::new();
let mut batch = c.commit().unwrap();
for tap in taps.iter().map(Some).chain([None]) {
for item in &batch.items {
if let MountItem::Text { id, text, .. } = item {
nodes.insert(text.text.clone(), *id);
}
}
out.push(format!("{:?}", batch.items));
let Some(tap) = tap else { break };
let node = *nodes
.get(*tap)
.unwrap_or_else(|| panic!("no text {tap:?} in {nodes:?}"));
assert!(c.component_event(node, EventKind::Press, &EventPayload::None));
batch = c.commit().unwrap_or_default();
}
out
}
/// A pressable text, through a helper that passes a listener on.
fn tap<M>(label: &'static str, on_press: impl IntoListener<crate::PressEvent, M>) -> Text {
text(label).on_press(on_press)
}
#[component]
fn ListenersOfEvents() -> impl IntoElement {
let n = signal(0);
view()
.child(text("one").on_press(move |_: &()| n.update(|n| *n += 1)))
.child(tap("ten", move |_: &()| n.update(|n| *n += 10)))
.child(tap(
"hundred",
Listener::from(move |_: &()| n.update(|n| *n += 100)),
))
.child(input().on_focus(move |_: &()| n.set(0)))
.child(text(move || format!("n {}", n.get())))
}
#[component]
fn ListenersWithout() -> impl IntoElement {
let n = signal(0);
view()
.child(text("one").on_press(move || n.update(|n| *n += 1)))
.child(tap("ten", move || n.update(|n| *n += 10)))
.child(tap(
"hundred",
Listener::from(move |_: &()| n.update(|n| *n += 100)),
))
.child(input().on_focus(move || n.set(0)))
.child(text(move || format!("n {}", n.get())))
}
#[test]
fn listeners_of_events_without_data_take_closures_without_arguments() {
let taps = ["one", "ten", "hundred", "one"];
let of_events = run::<ListenersOfEvents>(|| (), &taps);
assert_eq!(run::<ListenersWithout>(|| (), &taps), of_events);
assert!(of_events[4].contains("\"n 112\""), "{}", of_events[4]);
}
#[component]
fn ChildrenOneByOne() -> impl IntoElement {
view()
.child(text("a"))
.child(text("c"))
.child(text("d"))
.child(text("e"))
.child(text("f"))
.child(text("row 0"))
.child(text("row 1"))
.child(text("x").child("y").child("z"))
.child(dynamic(|| vec![text("left"), text("right")]))
}
#[component]
fn ChildrenTogether() -> impl IntoElement {
view()
.child(Some(text("a")))
.child(None::<Text>)
.child(vec![text("c"), text("d")])
.child(["e", "f"].map(text))
.child((0..2).map(|i| text(format!("row {i}"))))
.child(text("x").child(["y", "z"]))
.child(dynamic(|| [text("left"), text("right")]))
}
#[test]
fn options_vecs_arrays_and_iterators_are_children() {
let one_by_one = run::<ChildrenOneByOne>(|| (), &[]);
assert_eq!(run::<ChildrenTogether>(|| (), &[]), one_by_one);
assert!(one_by_one[0].contains("\"row 1\""));
assert!(one_by_one[0].contains("\"right\""));
}
/// The setters of host elements' own options, each given a closure
/// of `flipped`.
#[component]
fn BoundOptions() -> impl IntoElement {
let flipped = signal(false);
let pick =
move |a: &'static str, b: &'static str| move || if flipped.get() { b } else { a };
view()
.child(text("flip").on_press(move || flipped.set(true)))
.child(
text("lines")
.number_of_lines(move || if flipped.get() { 2_u32 } else { 1 })
.style_when(flipped, |s| s.select_text())
.max_font_size_multiplier(move || if flipped.get() { 3.0_f32 } else { 1.5 }),
)
.child(
image("a.png")
.object_fit(move || {
if flipped.get() {
crate::ResizeMode::Contain
} else {
crate::ResizeMode::Cover
}
})
.placeholder(pick("before.png", "after.png"))
.fade_duration(move || if flipped.get() { 300.0_f32 } else { 100.0 }),
)
.child(web_view(pick(
"https://before.test/",
"https://after.test/",
)))
.child(video(pick(
"https://before.test/v.mp4",
"https://after.test/v.mp4",
)))
.child(native("map").prop("zoom", move || {
serde_json::json!(if flipped.get() { 9 } else { 4 })
}))
}
#[test]
fn host_options_take_signals_and_closures() {
let frames = run::<BoundOptions>(|| (), &["flip"]);
for before in [
"before.png",
"https://before.test/",
"https://before.test/v.mp4",
"Number(4)",
"Cover",
"fade_ms: Some(100.0)",
"max_lines: 1",
] {
assert!(frames[0].contains(before), "{before} in {}", frames[0]);
}
for after in [
"after.png",
"https://after.test/",
"https://after.test/v.mp4",
"Number(9)",
"resize_mode: Contain",
"fade_ms: Some(300.0)",
"max_lines: 2",
"selectable: Some(true)",
] {
assert!(frames[1].contains(after), "{after} in {}", frames[1]);
}
for gone in ["before.png", "before.test"] {
assert!(!frames[1].contains(gone), "{gone} in {}", frames[1]);
}
}
#[test]
fn a_status_bar_style_is_a_setting() {
let setting = crate::StatusBarStyle::Light.into_reactive();
assert_eq!(
setting.get(),
StatusBarSetting::default().foreground(crate::StatusBarStyle::Light)
);
}
}
/// Render functions (`Option<Renderer<T>>` props) and the app's classes on
/// a view's elements (`app_class`).
mod renders {
use serde_json::json;
use super::*;
use crate::{
Prop,
element::{AnyValue, Props, Registry, Rendered, Renderer, Root, dynamic},
prelude::*,
};
/// Renders each item (`key:label`) with the app's function, keyed by
/// its key; in one paragraph when `inline`.
#[derive(Clone, PartialEq, Props)]
struct ShelfProps {
#[prop(default)]
items: crate::element::Prop<Vec<String>>,
#[prop(default)]
inline: bool,
render_item: crate::element::Prop<Option<Renderer<String>>>,
}
fn split(item: &str) -> (String, String) {
let (key, label) = item.split_once(':').unwrap_or((item, item));
(key.to_owned(), label.to_owned())
}
#[component]
fn Shelf(props: ShelfProps) -> impl IntoElement {
let rows = each(
props.items,
|item: &String| split(item).0,
move |item, _| {
// (A row's root is a node: an `Each` keeps rows by it.)
view().child(dynamic(move || -> Option<Rendered> {
let (key, label) = split(&item.get());
props.render_item.get().map(|r| r.render(key, label))
}))
},
);
if props.inline {
text("on the shelf: ").child(rows).into_element()
} else {
view().child(rows).into_element()
}
}
fn core_with_shelf(inline: bool) -> Core<FakeEngine> {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Shelf>();
c.set_components(registry);
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Shelf>().into()),
},
Op::SetProp {
id: 2,
prop: Prop::RustProp(
"renderItem",
Some(AnyValue::new(Some(Renderer::<String>::__js_of(
"renderItem",
2,
)))),
),
},
items(&["a:Apple", "b:Banana"]),
];
if inline {
ops.push(Op::SetProp {
id: 2,
prop: rust_prop::<ShelfProps>("inline", Some(json!(true))),
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
c
}
fn items(items: &[&str]) -> Op {
Op::SetProp {
id: 2,
prop: rust_prop::<ShelfProps>("items", Some(json!(items))),
}
}
/// What the core asked JS: `$render key value` / `$unrender key`.
fn asked(c: &mut Core<FakeEngine>) -> Vec<String> {
js_events(c)
.into_iter()
.filter_map(|(host, _, payload)| match payload {
EventPayload::Native { name, data } if name.starts_with("$") => {
assert_eq!(host, 2);
assert_eq!(data["prop"], "renderItem");
let key = data["key"].as_str().unwrap().to_owned();
Some(match data.get("value") {
Some(v) => format!("{name} {key} {}", v.as_str().unwrap()),
None => format!("{name} {key}"),
})
}
_ => None,
})
.collect()
}
/// JS's answer to `$render key`: holder `holder` with a text of
/// `label`, inserted into the host.
fn holder(holder: NodeId, key: &str, label: &str) -> Vec<Op> {
vec![
Op::Create {
id: holder,
tag: Tag::View,
},
Op::SetProp {
id: holder,
prop: Prop::ComponentRender(format!("renderItem\u{1f}{key}").into()),
},
Op::Create {
id: holder + 2,
tag: Tag::Text,
},
Op::CreateText {
id: holder + 4,
text: label.into(),
},
Op::Insert {
parent: holder + 2,
child: holder + 4,
before: None,
},
Op::Insert {
parent: holder,
child: holder + 2,
before: None,
},
Op::Insert {
parent: 2,
child: holder,
before: None,
},
]
}
fn parent_of(c: &Core<FakeEngine>, id: NodeId) -> Option<NodeId> {
let key = c.key(id).ok()?;
let parent = c.nodes[key as usize].parent;
(parent != NO_KEY).then(|| c.nodes[parent as usize].id)
}
#[test]
fn js_renders_each_key_once_per_value_and_releases_it() {
let mut c = core_with_shelf(false);
c.commit().unwrap();
assert_eq!(asked(&mut c), ["$render a Apple", "$render b Banana"]);
apply(&mut c, holder(10, "a", "Apple"));
apply(&mut c, holder(20, "b", "Banana"));
c.commit().unwrap();
// Each holder is the only child of its placeholder, a view of the
// core's in the component's view.
let (a, b) = (parent_of(&c, 10).unwrap(), parent_of(&c, 20).unwrap());
assert_eq!((a % 2, b % 2), (1, 1));
assert_ne!(a, b);
// In their rows.
let row = |p| parent_of(&c, p).and_then(|r| parent_of(&c, r));
assert_eq!(row(a), row(b));
assert!(asked(&mut c).is_empty());
// An equal value asks nothing; a new one asks again; the holder of
// the new render replaces the old one.
apply(&mut c, vec![items(&["a:Apple", "b:Banana"])]);
let _ = c.commit();
assert!(asked(&mut c).is_empty());
apply(&mut c, vec![items(&["a:Avocado", "b:Banana"])]);
let _ = c.commit();
assert_eq!(asked(&mut c), ["$render a Avocado"]);
apply(&mut c, holder(30, "a", "Avocado"));
apply(
&mut c,
vec![
Op::Remove {
parent: 2,
child: 10,
},
Op::Release { id: 10 },
],
);
c.commit().unwrap();
assert_eq!(parent_of(&c, 30), Some(a));
// A key that leaves is released once.
apply(&mut c, vec![items(&["b:Banana"])]);
let _ = c.commit();
assert_eq!(asked(&mut c), ["$unrender a"]);
assert_eq!(parent_of(&c, 30), None, "out of the tree");
assert!(c.key(a).is_err(), "the placeholder went");
apply(
&mut c,
vec![
Op::Remove {
parent: 2,
child: 30,
},
Op::Release { id: 30 },
],
);
let _ = c.commit();
assert!(asked(&mut c).is_empty());
// Back: rendered again.
apply(&mut c, vec![items(&["a:Apple", "b:Banana"])]);
let _ = c.commit();
assert_eq!(asked(&mut c), ["$render a Apple"]);
// The host goes: nothing is left of its renders.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
let _ = c.commit();
assert!(c.components.renders.is_empty());
}
#[test]
fn a_holder_coming_after_its_key_left_stays_out_of_the_tree() {
let mut c = core_with_shelf(false);
c.commit().unwrap();
asked(&mut c);
apply(&mut c, vec![items(&["b:Banana"])]);
let _ = c.commit();
assert_eq!(asked(&mut c), ["$unrender a"]);
// JS answers the first ask after the core moved on.
apply(&mut c, holder(10, "a", "Apple"));
let _ = c.commit();
assert_eq!(parent_of(&c, 10), None);
}
#[test]
fn renders_in_a_paragraph_are_inline_views() {
let mut c = core_with_shelf(true);
c.commit().unwrap();
assert_eq!(asked(&mut c), ["$render a Apple", "$render b Banana"]);
apply(&mut c, holder(10, "a", "Apple"));
let batch = c.commit().unwrap();
let place = parent_of(&c, 10).unwrap();
// The row is an inline view of the paragraph.
let paragraph = parent_of(&c, parent_of(&c, place).unwrap()).unwrap();
let key = c.key(paragraph).unwrap();
assert_eq!(c.nodes[key as usize].kind, Kind::Text);
// Laid out as an attachment of the paragraph: it has a frame.
assert!(frame_of(&batch, place).is_some(), "{:?}", batch.items);
}
/// One render placed straight in a paragraph (as `TextView` places
/// `renderCustom`'s inline nodes).
#[derive(Clone, PartialEq, Props)]
struct MentionProps {
render_item: crate::element::Prop<Option<Renderer<String>>>,
}
#[component]
fn Mention(props: MentionProps) -> impl IntoElement {
text("Hi ").child(dynamic(move || -> Option<Rendered> {
props
.render_item
.get()
.map(|r| r.render("a", "Ann".to_owned()))
}))
}
/// The placeholder and JS's holder are not the app's views: the
/// content's `verticalAlign` places the render in its line.
#[test]
fn a_render_in_a_paragraph_sits_by_its_contents_vertical_align() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Mention>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Mention>().into()),
},
Op::SetProp {
id: 2,
prop: Prop::RustProp(
"renderItem",
Some(AnyValue::new(Some(Renderer::<String>::__js_of(
"renderItem",
2,
)))),
),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
assert_eq!(asked(&mut c), ["$render a Ann"]);
// JS's holder (10) of the content, a chip (12) set in the middle.
let chip = |align: &'static str| {
style_op(
12,
&[
("width", StyleValue::Number(30.0)),
("height", StyleValue::Number(20.0)),
("verticalAlign", StyleValue::Str(align)),
],
)
};
apply(
&mut c,
vec![
Op::Create {
id: 10,
tag: Tag::View,
},
Op::SetProp {
id: 10,
prop: Prop::ComponentRender("renderItem\u{1f}a".into()),
},
Op::Create {
id: 12,
tag: Tag::View,
},
chip("middle"),
Op::Insert {
parent: 10,
child: 12,
before: None,
},
Op::Insert {
parent: 2,
child: 10,
before: None,
},
],
);
c.commit().unwrap();
let place = parent_of(&c, 10).unwrap();
let paragraph = parent_of(&c, place).unwrap();
let align = |c: &mut Core<FakeEngine>| {
let layout = c.nodes[c.key(paragraph).unwrap() as usize].layout.unwrap();
let cx = c.text_cx(layout);
assert_eq!(cx.text.attachments.len(), 1);
cx.alignments.get(cx.text.attachments[0].index)
};
assert_eq!(align(&mut c), crate::VerticalAlign::Middle);
// A change of the content's builds the text again.
apply(&mut c, vec![chip("text-top")]);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Text { id, .. } if *id == paragraph)),
"{:?}",
batch.items
);
assert_eq!(align(&mut c), crate::VerticalAlign::TextTop);
}
/// A popup's list: a scroll view as long as its rows (up to 300 pt),
/// the rows in its viewport, each drawn by the app's function, keyed by
/// their items' keys.
#[derive(Clone, PartialEq, Props)]
struct PickerProps {
#[prop(default)]
items: crate::element::Prop<Vec<String>>,
render_item: crate::element::Prop<Option<Renderer<String>>>,
}
#[component]
fn Picker(props: PickerProps) -> impl IntoElement {
let (items, render) = (props.items, props.render_item);
view().max_h(px(300.0)).child(
scroll().flex_shrink(1.0).min_h(px(0.0)).child(
virtual_list(
move || items.with(Vec::len),
move |at| {
view().child(dynamic(move || -> Option<Rendered> {
let (key, label) = items.with(|i| split(&i[at.index()]));
render.get().map(|r| r.render(key, label))
}))
},
)
.keys(move || items.with(|i| i.iter().map(|i| split(i).0).collect::<Vec<_>>()))
.viewport(ListViewport::Parent),
),
)
}
#[test]
fn a_lists_rows_drawn_by_js_are_measured_once_their_drawing_arrives() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Picker>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Picker>().into()),
},
Op::SetProp {
id: 2,
prop: Prop::RustProp(
"renderItem",
Some(AnyValue::new(Some(Renderer::<String>::__js_of(
"renderItem",
2,
)))),
),
},
Op::SetProp {
id: 2,
prop: rust_prop::<PickerProps>("items", Some(json!(["a:Apple", "b:Banana"]))),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
// Asked in no particular order.
let mut renders = asked(&mut c);
renders.sort();
assert_eq!(renders, ["$render a Apple", "$render b Banana"]);
let scroll = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create {
id,
kind: crate::ViewKind::Scroll,
} => Some(*id),
_ => None,
})
.expect("the scroll view");
// The rows hold only their placeholders: they keep their estimates
// (50 pt) instead of measuring nothing, which would leave the
// scroll view no viewport to render them in.
let height = |batch: &MountBatch| frame_of(batch, scroll).map(|f| f.size.height.0);
assert_eq!(height(&batch), Some(100.0), "{:?}", batch.items);
// JS's drawings arrive: the rows are measured in this commit (16 pt
// each), the scroll view follows and the rows are placed.
apply(&mut c, holder(10, "a", "Apple"));
apply(&mut c, holder(20, "b", "Banana"));
let batch = c.commit().unwrap();
assert_eq!(height(&batch), Some(32.0), "{:?}", batch.items);
let cell = |holder: NodeId| {
let mut key = c.key(holder).unwrap();
loop {
let parent = c.nodes[key as usize].parent;
assert_ne!(parent, NO_KEY, "in a cell");
if c.nodes[parent as usize].list.is_some() {
return c.nodes[key as usize].id;
}
key = parent;
}
};
let rows: Vec<(f32, f32)> = [10, 20]
.into_iter()
.map(|h| {
let frame = frame_of(&batch, cell(h)).expect("the row is placed");
(frame.origin.y.0, frame.size.height.0)
})
.collect();
assert_eq!(rows, [(0.0, 16.0), (16.0, 16.0)], "{:?}", batch.items);
// What JS drew is laid out in them.
for holder in [10, 20] {
let frame = frame_of(&batch, holder).expect("the holder is laid out");
assert_eq!(frame.size.height.0, 16.0);
}
}
#[test]
fn a_row_drawn_by_js_stays_in_its_cell_when_rows_before_it_go() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Picker>();
c.set_components(registry);
let fruits = [
"a:Apple", "b:Banana", "c:Cherry", "d:Date", "e:Elder", "f:Fig",
];
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Picker>().into()),
},
Op::SetProp {
id: 2,
prop: Prop::RustProp(
"renderItem",
Some(AnyValue::new(Some(Renderer::<String>::__js_of(
"renderItem",
2,
)))),
),
},
Op::SetProp {
id: 2,
prop: rust_prop::<PickerProps>("items", Some(json!(fruits))),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
assert_eq!(asked(&mut c).len(), 6);
for (i, fruit) in fruits.iter().enumerate() {
let (key, label) = split(fruit);
apply(&mut c, holder(10 * (i as NodeId + 1), &key, &label));
}
c.commit().unwrap();
let (elder, fig) = (parent_of(&c, 50).unwrap(), parent_of(&c, 60).unwrap());
// A filter keeps the last two: their cells move up to rows 0 and 1.
// The freed cells of Apple and Banana read the rows now at their
// old indices, Elder and Fig, and place them too; the rows' own
// cells keep showing them.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: rust_prop::<PickerProps>("items", Some(json!(["e:Elder", "f:Fig"]))),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
(parent_of(&c, 50), parent_of(&c, 60)),
(Some(elder), Some(fig)),
"{:?}",
batch.items
);
let mut renders = asked(&mut c);
renders.sort();
assert_eq!(
renders,
["$unrender a", "$unrender b", "$unrender c", "$unrender d"]
);
}
/// A Rust view passing a closure: rendered on the spot.
#[derive(Clone, PartialEq, Props)]
struct ShelvesProps {}
#[component]
fn Shelves(_props: ShelvesProps) -> impl IntoElement {
shelf()
.items(vec!["a:Apple".to_owned(), "b:Banana".to_owned()])
.render_item(|label| text(format!("[{label}]")))
}
#[test]
fn a_rust_renderer_renders_in_place() {
let mut c = core();
c.mount_root(&Root::new::<Shelves>(|| ShelvesProps {}));
let batch = c.commit().unwrap();
let texts: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.clone()),
_ => None,
})
.collect();
assert_eq!(texts, ["[Apple]", "[Banana]"]);
assert!(js_events(&mut c).is_empty());
}
/// A view styling a part with the app's classes.
#[derive(Clone, PartialEq, Props)]
struct CardProps {
#[prop(default)]
heading_class: crate::element::Prop<Option<SharedString>>,
}
#[component]
fn Card(props: CardProps) -> impl IntoElement {
view().child(
view()
.bg(crate::element::palette::RED.shade(500))
.border_2()
.app_class(props.heading_class),
)
}
fn core_with_card(class: &str) -> Core<FakeEngine> {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Card>();
c.set_components(registry);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Component(std::any::type_name::<Card>().into()),
},
card_class(class),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c
}
fn card_class(class: &str) -> Op {
Op::SetProp {
id: 2,
prop: rust_prop::<CardProps>("headingClass", Some(json!(class))),
}
}
/// The heading's view: the host's only child.
fn heading(c: &Core<FakeEngine>) -> NodeId {
let key = c.key(2).unwrap();
let child = c.nodes[key as usize].children[0];
c.nodes[child as usize].id
}
#[test]
fn the_apps_classes_go_after_an_elements_own_styles() {
let mut c = core_with_card("bg-white dark:bg-black");
let batch = c.commit().unwrap();
let id = heading(&c);
let style = view_style_of(&batch, id).unwrap();
// The app's background wins; the view's own border stays.
assert_eq!(style.background_color, Color(0xffff_ffff));
assert_eq!(style.borders.widths.to_array().map(|w| w.0), [2.0; 4]);
// Dark: the app's dark variant.
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, id).unwrap().background_color,
Color(0x0000_00ff)
);
// Another class from the app: applied again, on the same node.
apply(&mut c, vec![card_class("bg-red-500 dark:bg-white")]);
let batch = c.commit().unwrap();
assert_eq!(heading(&c), id);
assert_eq!(
view_style_of(&batch, id).unwrap().background_color,
Color(0xffff_ffff)
);
// None: the view's own.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: rust_prop::<CardProps>("headingClass", None),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, id).unwrap().background_color,
Color::from(crate::element::palette::RED.shade(500))
);
}
}
mod rust_selectable_view {
use std::cell::Cell;
use super::*;
use crate::{element::Root, prelude::*};
thread_local! {
static AREA: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
#[component]
fn Area() -> impl IntoElement {
let area = signal(true);
AREA.set(Some(area));
view()
.child(view().selectable(move || area.get()).child(text("inside")))
.child(view().child(text("outside")))
}
/// `Element::selectable_view` reaches the platform in the view's props,
/// follows its signal, and views without it get no props for it.
#[test]
fn a_selectable_view_is_a_view_prop() {
let mut c = core();
c.mount_root(&Root::of::<Area>());
let batch = c.commit().unwrap();
let areas: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::ViewProps { id, props } if props.selectable_view => Some(*id),
_ => None,
})
.collect();
assert_eq!(areas.len(), 1, "{:?}", batch.items);
assert!(
!batch.items.iter().any(
|item| matches!(item, MountItem::ViewProps { props, .. } if !props.selectable_view)
),
"views without the flag get no props: {:?}",
batch.items
);
{
let _entered = c.components.runtime.enter();
AREA.get().unwrap().set(false);
}
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(
|item| matches!(item, MountItem::ViewProps { id, props } if *id == areas[0] && !props.selectable_view)
));
}
}
mod rust_continues_text {
use std::cell::Cell;
use super::*;
use crate::{element::Root, prelude::*};
thread_local! {
static CONTINUES: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
#[component]
fn Wrapped() -> impl IntoElement {
let continues = signal(true);
CONTINUES.set(Some(continues));
view().selectable(true).children([
text("a long li").select_text(),
text("ne wrapped")
.select_text()
.continues_text(move || continues.get()),
])
}
/// `Element::continues_text` reaches the platform in the text's view
/// props and follows its signal; the part it continues gets none.
#[test]
fn a_continued_text_is_a_view_prop() {
let mut c = core();
c.mount_root(&Root::of::<Wrapped>());
let batch = c.commit().unwrap();
let parts: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::ViewProps { id, props } if props.continues_text => Some(*id),
_ => None,
})
.collect();
assert_eq!(parts.len(), 1, "{:?}", batch.items);
let second = batch.items.iter().find_map(|item| match item {
MountItem::Text { id, text, .. } if text.text == "ne wrapped" => Some(*id),
_ => None,
});
assert_eq!(second, Some(parts[0]), "{:?}", batch.items);
{
let _entered = c.components.runtime.enter();
CONTINUES.get().unwrap().set(false);
}
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(
|item| matches!(item, MountItem::ViewProps { id, props } if *id == parts[0] && !props.continues_text)
));
}
}
/// Creates `id` of `tag` with `style`, in `parent`.
fn add(
c: &mut Core<FakeEngine>,
id: NodeId,
tag: Tag,
parent: NodeId,
s: &[(&str, StyleValue<'_>)],
) {
apply(
c,
vec![
Op::Create { id, tag },
style_op(id, s),
Op::Insert {
parent,
child: id,
before: None,
},
],
);
}
fn inserts(batch: &MountBatch) -> Vec<(NodeId, NodeId, Option<NodeId>)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert {
parent,
child,
before,
} => Some((*parent, *child, *before)),
_ => None,
})
.collect()
}
fn overlay_prop(id: NodeId, prop: crate::OverlayProp) -> Op {
Op::SetProp {
id,
prop: Prop::Overlay(prop),
}
}
#[test]
fn hint_open_changes_sync_the_overlay_once() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::Overlay,
},
overlay_prop(
4,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
c.commit();
assert_eq!(c.overlay_state.shown, 0);
apply(
&mut c,
vec![overlay_prop(4, crate::OverlayProp::Open(Some(true)))],
);
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(ROOT_ID, 4, None)));
assert_eq!(c.overlay_state.shown, 1);
// A commit changing nothing does not take the shown hint out and put it
// back, nor work out its host again.
assert!(!c.overlay_state.hosts_dirty);
assert!(!c.overlay_state.listeners_dirty);
assert!(c.commit().is_none(), "no overlay work and no mount batch");
apply(
&mut c,
vec![overlay_prop(4, crate::OverlayProp::Open(Some(false)))],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: 4 }))
);
assert_eq!(c.overlay_state.shown, 0);
}
#[test]
fn an_overlay_released_before_sync_leaves_no_dirty_flags() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::Overlay,
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
Op::Release { id: 4 },
],
);
c.commit();
assert!(!c.overlay_state.hosts_dirty);
assert!(!c.overlay_state.listeners_dirty);
}
#[test]
fn nested_overlays_follow_their_overlay_ancestors_host() {
let mut c = core();
add(&mut c, 4, Tag::Overlay, ROOT_ID, &[]);
add(&mut c, 6, Tag::Overlay, 4, &[]);
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(ROOT_ID, 4, None)));
assert!(inserts(&batch).contains(&(ROOT_ID, 6, None)));
assert_eq!(c.overlay_state.shown, 2);
// Out of the tree, both leave their native host; back in, the outer
// one is in before the inner one that follows its host.
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 4,
}],
);
let batch = c.commit().unwrap();
for id in [4, 6] {
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: at } if *at == id)),
"missing Remove for {id}"
);
}
assert_eq!(c.overlay_state.shown, 0);
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
}],
);
let batch = c.commit().unwrap();
let at = batch.items.iter().filter_map(|i| match i {
MountItem::Insert { child, .. } => Some(*child),
_ => None,
});
let position = |id| at.clone().position(|child| child == id);
assert!(position(4).is_some());
assert!(position(6).is_some());
assert!(position(4) < position(6));
assert_eq!(c.overlay_state.shown, 2);
}
#[test]
fn depth_ordered_overlay_sync_covers_independent_overlays() {
let mut c = core();
// A depth-two hint inside two shown overlays.
add(&mut c, 2, Tag::Overlay, ROOT_ID, &[]);
add(&mut c, 4, Tag::Overlay, 2, &[]);
apply(
&mut c,
vec![
Op::Create {
id: 14,
tag: Tag::Overlay,
},
overlay_prop(
14,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
),
Op::Insert {
parent: 4,
child: 14,
before: None,
},
// A detached chain, its inner overlay created first: the sync's
// depth order, not creation order, opens the outer one first.
Op::Create {
id: 22,
tag: Tag::Overlay,
},
Op::Create {
id: 20,
tag: Tag::Overlay,
},
Op::Insert {
parent: 20,
child: 22,
before: None,
},
],
);
c.commit();
apply(
&mut c,
vec![
overlay_prop(14, crate::OverlayProp::Open(Some(true))),
Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
},
],
);
let batch = c.commit().unwrap();
let inserts: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert { child, .. } if matches!(child, 14 | 20 | 22) => Some(*child),
_ => None,
})
.collect();
assert_eq!(inserts, [20, 22, 14]);
}
#[test]
fn a_late_created_explicit_hint_anchor_starts_listening() {
let mut c = toolbar_core(&[]);
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::Overlay,
},
overlay_prop(
4,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
),
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(20)),
),
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
c.commit();
assert!(hint_watched(&c, &[20]).is_empty());
add(
&mut c,
20,
Tag::View,
ROOT_ID,
&[("height", StyleValue::Number(40.0))],
);
c.commit();
assert_eq!(hint_watched(&c, &[20]), [20]);
}
#[test]
fn creating_an_explicit_hint_anchor_marks_overlay_listeners_dirty() {
let mut c = toolbar_core(&[]);
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::Overlay,
},
overlay_prop(
4,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
),
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(20)),
),
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
c.commit();
assert!(!c.overlay_state.listeners_dirty);
apply(
&mut c,
vec![Op::Create {
id: 20,
tag: Tag::View,
}],
);
assert!(c.overlay_state.listeners_dirty);
assert!(!c.overlay_state.hosts_dirty);
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
}],
);
c.commit();
assert_eq!(hint_watched(&c, &[20]), [20]);
}
#[test]
fn an_off_tree_hint_sharing_an_anchor_takes_no_hover() {
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = toolbar_core(&[10]);
for id in [20, 30] {
apply(
&mut c,
vec![
Op::Create {
id,
tag: Tag::Overlay,
},
overlay_prop(
id,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(500))),
),
overlay_prop(
id,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(10)),
),
Op::Listen {
id,
event: EventKind::Show,
enabled: true,
},
Op::Listen {
id,
event: EventKind::Dismiss,
enabled: true,
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
],
);
}
c.commit();
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 30,
}],
);
c.commit();
assert!(c.overlay(c.key(20).unwrap()).is_some_and(|s| s.in_view));
assert!(c.overlay(c.key(30).unwrap()).is_some_and(|s| !s.in_view));
js_events(&mut c);
let mouse = EventPayload::Mouse(crate::MouseEvent::default());
c.component_event(10, EventKind::MouseEnter, &mouse);
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(500));
c.run_component_tasks();
c.commit();
let events = js_events(&mut c);
assert!(
events
.iter()
.any(|(id, kind, _)| *id == 20 && *kind == EventKind::Show),
"the hint in the view shows: {events:?}"
);
assert!(
!events
.iter()
.any(|(id, kind, _)| *id == 30 && matches!(kind, EventKind::Show | EventKind::Dismiss)),
"the off-tree hint takes no hover: {events:?}"
);
c.component_event(10, EventKind::MouseLeave, &mouse);
c.commit();
let events = js_events(&mut c);
assert!(
events
.iter()
.any(|(id, kind, _)| *id == 20 && *kind == EventKind::Dismiss),
"the hint in the view hides: {events:?}"
);
assert!(
!events
.iter()
.any(|(id, kind, _)| *id == 30 && matches!(kind, EventKind::Show | EventKind::Dismiss)),
"the off-tree hint reports nothing: {events:?}"
);
}
#[test]
fn an_off_tree_hint_sharing_an_anchor_takes_no_keyboard_focus() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
for os in [crate::platform::Os::Windows, crate::platform::Os::Linux] {
let mut c = core_on(os);
add(&mut c, 8, Tag::View, ROOT_ID, &[]);
add(&mut c, 10, Tag::View, ROOT_ID, &[]);
for id in [20, 30] {
apply(
&mut c,
vec![
Op::Create {
id,
tag: Tag::Overlay,
},
overlay_prop(
id,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(500))),
),
overlay_prop(
id,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(10)),
),
Op::Listen {
id,
event: EventKind::Show,
enabled: true,
},
Op::Listen {
id,
event: EventKind::Dismiss,
enabled: true,
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
],
);
}
c.commit();
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 30,
}],
);
c.commit();
js_events(&mut c);
c.set_input_modality(InputModality::Keyboard);
c.set_states(10, FOCUSED);
c.commit();
let events = js_events(&mut c);
assert!(
events
.iter()
.any(|(id, kind, _)| *id == 20 && *kind == EventKind::Show),
"{os:?}: the hint in the view shows: {events:?}"
);
assert!(
!events.iter().any(|(id, ..)| *id == 30),
"{os:?}: the off-tree hint takes no focus: {events:?}"
);
c.set_states(8, FOCUSED);
c.set_states(10, 0);
c.commit();
let events = js_events(&mut c);
assert!(
events
.iter()
.any(|(id, kind, _)| *id == 20 && *kind == EventKind::Dismiss),
"{os:?}: the hint in the view hides: {events:?}"
);
assert!(
!events.iter().any(|(id, ..)| *id == 30),
"{os:?}: the off-tree hint reports nothing: {events:?}"
);
}
}
#[test]
fn focus_and_tree_changes_in_one_commit_use_the_current_in_view_state() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
fn core_with_hint(os: crate::platform::Os) -> Core<FakeEngine> {
let mut c = core_on(os);
add(&mut c, 10, Tag::View, ROOT_ID, &[]);
apply(
&mut c,
vec![
Op::Create {
id: 20,
tag: Tag::Overlay,
},
overlay_prop(
20,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(500))),
),
overlay_prop(
20,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(10)),
),
Op::Listen {
id: 20,
event: EventKind::Show,
enabled: true,
},
Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
},
],
);
c.commit();
c
}
for os in [crate::platform::Os::Windows, crate::platform::Os::Linux] {
// Out in the last commit, back in and focused in this one: Show.
let mut c = core_with_hint(os);
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 20,
}],
);
c.commit();
js_events(&mut c);
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
}],
);
c.set_input_modality(InputModality::Keyboard);
c.set_states(10, FOCUSED);
c.commit();
let events = js_events(&mut c);
assert!(
events
.iter()
.any(|(id, kind, _)| *id == 20 && *kind == EventKind::Show),
"{os:?}: reinserted and focused in one commit: {events:?}"
);
// In during the last commit, out and focused in this one: no Show.
let mut c = core_with_hint(os);
js_events(&mut c);
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 20,
}],
);
c.set_input_modality(InputModality::Keyboard);
c.set_states(10, FOCUSED);
c.commit();
let events = js_events(&mut c);
assert!(
!events.iter().any(|(id, ..)| *id == 20),
"{os:?}: removed and focused in one commit: {events:?}"
);
}
}
#[test]
fn nested_focus_and_tree_changes_in_one_commit_use_live_in_view_state() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
fn core_with_nested_hint() -> Core<FakeEngine> {
let mut c = core_on(crate::platform::Os::Windows);
add(&mut c, 10, Tag::View, ROOT_ID, &[]);
apply(
&mut c,
vec![
Op::Create {
id: 40,
tag: Tag::Overlay,
},
Op::Create {
id: 50,
tag: Tag::Overlay,
},
overlay_prop(
50,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(500))),
),
overlay_prop(
50,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(10)),
),
Op::Listen {
id: 50,
event: EventKind::Show,
enabled: true,
},
Op::Insert {
parent: 40,
child: 50,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 40,
before: None,
},
],
);
c.commit();
c
}
// Out in the last commit, back in and focused in this one: Show.
let mut c = core_with_nested_hint();
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 40,
}],
);
c.commit();
js_events(&mut c);
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 40,
before: None,
}],
);
c.set_input_modality(InputModality::Keyboard);
c.set_states(10, FOCUSED);
c.commit();
let events = js_events(&mut c);
assert!(
events
.iter()
.any(|(id, kind, _)| *id == 50 && *kind == EventKind::Show),
"nested overlay reinserted and focused in one commit: {events:?}"
);
// In during the last commit, out and focused in this one: no Show.
let mut c = core_with_nested_hint();
js_events(&mut c);
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 40,
}],
);
c.set_input_modality(InputModality::Keyboard);
c.set_states(10, FOCUSED);
c.commit();
let events = js_events(&mut c);
assert!(
!events.iter().any(|(id, ..)| *id == 50),
"nested overlay removed and focused in one commit: {events:?}"
);
}
#[test]
fn hiding_the_last_anchored_overlay_clears_its_native_anchor() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(
&mut c,
4,
Tag::Overlay,
ROOT_ID,
&[("width", Number(20.0)), ("height", Number(20.0))],
);
apply(
&mut c,
vec![overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
)],
);
c.commit();
let key = c.key(4).unwrap();
assert!(c.overlay(key).is_some_and(|s| s.native_anchor.is_some()));
assert_eq!(c.overlay_state.shown, 1);
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 4,
}],
);
let batch = c.commit().unwrap();
assert_eq!(c.overlay_state.shown, 0);
assert!(c.overlay(key).is_some_and(|s| s.native_anchor.is_none()));
assert!(
batch.items.iter().any(|i| matches!(
i,
MountItem::ViewProps { id, props } if *id == 4 && props.overlay_anchor.is_none()
)),
"the clearing props go out before the overlay is removed"
);
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == 4)),
"the hidden overlay leaves its host"
);
}
#[test]
fn fixed_views_are_laid_out_in_their_root_view() {
let mut c = core();
// A padded box below another; a `fixed` bar inside it.
view_with_classes(&mut c, 2, "h-[100px]");
view_with_classes(&mut c, 3, "p-[20px] h-[200px]");
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::View,
},
class_op(4, "fixed inset-x-0 bottom-0 h-[40px]"),
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Create {
id: 5,
tag: Tag::View,
},
class_op(5, "h-[10px]"),
Op::Insert {
parent: 3,
child: 5,
before: None,
},
],
);
let batch = c.commit().unwrap();
// Against the surface (320 x 480), in the root view's native view,
// out of its parent's layout (5 is the first in flow).
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 440.0, 320.0, 40.0)));
let ins = inserts(&batch);
assert!(ins.contains(&(ROOT_ID, 4, None)), "{ins:?}");
assert!(!ins.iter().any(|&(p, c, _)| p == 3 && c == 4), "{ins:?}");
assert_eq!(frame_of(&batch, 5), Some(rect(20.0, 20.0, 280.0, 10.0)));
// No longer fixed: back in its parent, laid out there.
c.apply(class_op(4, "absolute inset-x-0 bottom-0 h-[40px]"))
.unwrap();
let batch = c.commit().unwrap();
let ins = inserts(&batch);
assert!(ins.contains(&(3, 4, Some(5))), "{ins:?}");
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 160.0, 320.0, 40.0)));
// And fixed again.
c.apply(class_op(4, "fixed inset-x-0 bottom-0 h-[40px]"))
.unwrap();
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(ROOT_ID, 4, None)));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 440.0, 320.0, 40.0)));
}
#[test]
fn fixing_a_view_in_a_scroll_view_unculls_its_subtree() {
let mut c = core();
// Scroll view (2) -> wrapper (3) -> toolbar (4) with an existing item (5),
// plus a tall spacer (6) and an off-screen descendant (7) that starts culled.
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "h-[1200px]"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
class_op(4, "flex-row h-[40px]"),
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Create {
id: 5,
tag: Tag::View,
},
class_op(5, "w-[40px] h-[40px]"),
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
class_op(6, "h-[1000px]"),
Op::Insert {
parent: 3,
child: 6,
before: None,
},
Op::Create {
id: 7,
tag: Tag::View,
},
class_op(7, "h-[40px]"),
Op::Insert {
parent: 3,
child: 7,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&3));
assert!(created_in(&batch).contains(&4));
assert!(created_in(&batch).contains(&5));
assert!(!created_in(&batch).contains(&7));
// In the same commit: promote wrapper (3) to `position: fixed` and insert a
// new child (8) into toolbar (4). Before `sync_fixed()` runs, `insert` sees
// the outer scroll view as the culling scope and holds back (8); once (3)
// becomes fixed (`is_layout_root()`), the outer scroll view skips it.
apply(
&mut c,
vec![
class_op(3, "fixed inset-0"),
Op::Create {
id: 8,
tag: Tag::View,
},
class_op(8, "w-[60px] h-[40px]"),
Op::Insert {
parent: 4,
child: 8,
before: None,
},
],
);
let batch = c.commit().unwrap();
let created = created_in(&batch);
assert!(
created.contains(&8),
"newly inserted child must be created: {created:?}"
);
assert!(
created.contains(&7),
"previously culled descendant must be created: {created:?}"
);
let ins = inserts(&batch);
assert!(ins.contains(&(ROOT_ID, 3, None)), "{ins:?}");
assert!(ins.contains(&(4, 8, None)), "{ins:?}");
assert!(ins.contains(&(3, 7, None)), "{ins:?}");
assert_eq!(frame_of(&batch, 8), Some(rect(40.0, 0.0, 60.0, 40.0)));
}
#[test]
fn perspective_gives_children_depth_from_the_center() {
use crate::transform::TransformKind as T;
let mut c = core();
view_with_classes(&mut c, 2, "perspective-[400px] w-[200px] h-[200px]");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "size-[100px] rotate-y-45"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
class_op(4, "size-[100px] rotate-12"),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
let batch = c.commit().unwrap();
let steps = |batch: &MountBatch, id| {
view_style_of(batch, id).map(|v| {
v.transform
.ops()
.iter()
.map(|op| (op.kind, op.value))
.collect::<Vec<_>>()
})
};
// 3's center is 50 left of and 50 above the parent's: the perspective
// is seen from the parent's center, before 3's own rotation.
assert_eq!(
steps(&batch, 3).unwrap(),
[
(T::TranslateX, 50.0),
(T::TranslateY, 50.0),
(T::Perspective, 400.0),
(T::TranslateX, -50.0),
(T::TranslateY, -50.0),
(T::RotateY, 45.0),
]
);
// A view that stays in its plane is as it was.
assert_eq!(steps(&batch, 4).unwrap(), [(T::Rotate, 12.0)]);
// The parent's own transform does not get it.
assert_eq!(
view_style_of(&batch, 2).map(|v| v.transform.ops().len()),
None
);
// Without it, the children's own transforms.
c.apply(class_op(2, "w-[200px] h-[200px]")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(steps(&batch, 3).unwrap(), [(T::RotateY, 45.0)]);
}
/// Each character half its font size wide, one line: lengths in `ch`.
struct SizedEngine;
impl TextEngine for SizedEngine {
type Prepared = f32;
fn prepare(&self, text: &AttributedText) -> f32 {
text.spans
.iter()
.map(|s| (s.end - s.start) as f32 * s.style.font_size.0 / 2.0)
.sum()
}
fn measure(&self, w: &f32, _: Option<Points>) -> Size<Points> {
size_pt(*w, 16.0)
}
fn layout(&self, _: &f32, _: Size<Points>) -> TextLayout {
TextLayout(Arc::new(()))
}
}
#[test]
fn prose_is_65ch_of_the_font() {
let mut c = Core::new(SizedEngine, size_pt(2000.0, 480.0));
// Built from the inside out, as JSX does: the font is in place when
// the commit comes.
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, "max-w-prose w-full h-[10px]"),
Op::Create {
id: 4,
tag: Tag::View,
},
class_op(4, "max-w-prose w-full h-[10px] text-[10px]"),
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, "text-[20px]"),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let width = |batch: &MountBatch, id| frame_of(batch, id).map(|f| f.size.width.0);
// 65 times the `0` of the font: the inherited 20pt one's (10pt), its
// own 10pt one's (5pt).
assert_eq!(width(&batch, 3), Some(650.0));
assert_eq!(width(&batch, 4), Some(325.0));
// The font around it changes: so does `ch`.
c.apply(class_op(2, "text-[16px]")).unwrap();
let batch = c.commit().unwrap();
assert_eq!(width(&batch, 3), Some(520.0));
}
#[test]
fn static_views_ignore_their_insets() {
let mut c = core();
view_with_classes(&mut c, 2, "relative top-4 left-2 size-[10px] static");
view_with_classes(&mut c, 3, "static top-4 size-[10px]");
view_with_classes(&mut c, 4, "static md:relative top-4 size-[10px]");
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 10.0, 10.0)));
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 10.0, 10.0, 10.0)));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 20.0, 10.0, 10.0)));
c.set_viewport(size_pt(800.0, 480.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 36.0, 10.0, 10.0)));
}
#[test]
fn content_height_uses_committed_in_flow_geometry_when_overlays_open_and_close() {
use StyleValue::{Number, Str};
let mut c = core();
assert_eq!(c.content_height(), None);
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(100.0))]);
add(&mut c, 4, Tag::View, 2, &[("padding", Number(5.0))]);
c.commit().unwrap();
assert_eq!(c.content_height(), Some(Points(100.0)));
// The overlay is mounted under the surface root, not its logical parent.
add(
&mut c,
6,
Tag::Overlay,
4,
&[("left", Number(10.0)), ("top", Number(300.0))],
);
add(
&mut c,
8,
Tag::View,
6,
&[("width", Number(50.0)), ("height", Number(20.0))],
);
// Out-of-flow views directly in the logical root do not size it either.
for (id, position) in [(10, "absolute"), (12, "fixed")] {
add(
&mut c,
id,
Tag::View,
ROOT_ID,
&[
("position", Str(position)),
("top", Number(400.0)),
("height", Number(20.0)),
],
);
}
// A top-level modal is a separate layout root even without out-of-flow styling.
add(&mut c, 14, Tag::Modal, ROOT_ID, &[]);
c.set_root_size(14, size_pt(200.0, 300.0), EdgeInsets::default());
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 6), Some(rect(10.0, 300.0, 50.0, 20.0)));
assert_eq!(frame_of(&batch, 14), Some(rect(0.0, 0.0, 200.0, 300.0)));
assert_eq!(c.content_height(), Some(Points(100.0)));
apply(
&mut c,
vec![Op::Remove {
parent: 4,
child: 6,
}],
);
c.commit().unwrap();
assert_eq!(c.content_height(), Some(Points(100.0)));
apply(&mut c, vec![style_op(2, &[("height", Number(160.0))])]);
c.commit().unwrap();
assert_eq!(c.content_height(), Some(Points(160.0)));
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 2,
}],
);
c.commit().unwrap();
assert_eq!(c.content_height(), None);
}
#[test]
fn overlays_show_in_their_root_view_above_its_children() {
use StyleValue::Number;
let mut c = core();
// A clipping box with an overlay deep inside.
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[
("height", Number(100.0)),
("overflow", StyleValue::Str("hidden")),
],
);
add(&mut c, 4, Tag::View, 2, &[("padding", Number(5.0))]);
add(
&mut c,
6,
Tag::Overlay,
4,
&[("left", Number(10.0)), ("top", Number(300.0))],
);
add(
&mut c,
8,
Tag::View,
6,
&[("width", Number(50.0)), ("height", Number(20.0))],
);
let batch = c.commit().unwrap();
let creates = batch.items.iter().find_map(|i| match i {
MountItem::Create { id: 6, kind } => Some(*kind),
_ => None,
});
assert_eq!(creates, Some(ViewKind::View));
let ins = inserts(&batch);
assert!(ins.contains(&(ROOT_ID, 6, None)), "{ins:?}");
assert!(!ins.iter().any(|&(p, c, _)| p == 4 && c == 6));
assert!(ins.contains(&(6, 8, None)));
// `position: fixed` in the root view, out of its parent's layout.
assert_eq!(frame_of(&batch, 6), Some(rect(10.0, 300.0, 50.0, 20.0)));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 0.0, 320.0, 10.0)));
// Measured in the root view.
let m = c.measure(8).unwrap();
assert_eq!(m.page, point(px(10.0), px(300.0)));
// The root view's children go below the overlays.
add(&mut c, 10, Tag::View, ROOT_ID, &[("height", Number(10.0))]);
let batch = c.commit().unwrap();
assert_eq!(inserts(&batch), vec![(ROOT_ID, 10, Some(6))]);
// Out of the tree: out of the root view; back in: on top.
add(&mut c, 12, Tag::Overlay, ROOT_ID, &[]);
c.commit().unwrap();
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 2,
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: 6 }))
);
apply(
&mut c,
vec![Op::Insert {
parent: ROOT_ID,
child: 2,
before: Some(10),
}],
);
let batch = c.commit().unwrap();
let ins = inserts(&batch);
assert!(ins.contains(&(ROOT_ID, 2, Some(10))), "{ins:?}");
assert!(ins.contains(&(ROOT_ID, 6, None)), "{ins:?}");
assert_eq!(c.overlays.last().map(|&k| c.nodes[k as usize].id), Some(6));
// Released with its parent's subtree.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 6 },
],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id: 6 }))
);
assert_eq!(c.overlays.len(), 1);
// `display: none` around it hides it.
add(&mut c, 14, Tag::View, ROOT_ID, &[]);
add(&mut c, 16, Tag::Overlay, 14, &[]);
c.commit().unwrap();
apply(
&mut c,
vec![style_op(14, &[("display", StyleValue::Str("none"))])],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: 16 }))
);
}
/// The `tab_after` overlay `id`'s view was last mounted with in `batch`
/// (`None` when its props were not mounted).
fn tab_after_in(batch: &MountBatch, id: NodeId) -> Option<Option<NodeId>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: at, props } if *at == id => Some(props.tab_after),
_ => None,
})
}
#[test]
fn shown_overlays_go_in_the_tab_order_after_what_comes_before_them() {
use StyleValue::Number;
let mut c = core();
let sized = [("height", Number(10.0))];
// A popover: its trigger (with a label), a backdrop overlay, then the
// popup overlay with a field; a button after the popover.
add(&mut c, 2, Tag::View, ROOT_ID, &[]);
add(&mut c, 4, Tag::View, 2, &sized);
add(&mut c, 6, Tag::View, 4, &sized);
add(&mut c, 8, Tag::Overlay, 2, &[]);
add(&mut c, 10, Tag::Overlay, 2, &[]);
add(&mut c, 12, Tag::View, 10, &sized);
add(&mut c, 14, Tag::View, ROOT_ID, &sized);
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(ROOT_ID, 10, None)));
// After the trigger's label, not the backdrop.
assert_eq!(tab_after_in(&batch, 10), Some(Some(6)));
assert_eq!(tab_after_in(&batch, 8), Some(Some(6)));
// A commit that changes nothing around them mounts nothing.
apply(&mut c, vec![style_op(14, &[("height", Number(12.0))])]);
let batch = c.commit().unwrap();
assert_eq!(tab_after_in(&batch, 10), None);
// A view inserted between the trigger and the popup: after it.
add(&mut c, 16, Tag::View, 2, &sized);
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 16,
before: Some(8),
}],
);
let batch = c.commit().unwrap();
assert_eq!(tab_after_in(&batch, 10), Some(Some(16)));
// Nothing before it in its parent: after the parent.
apply(
&mut c,
vec![
Op::Remove {
parent: 2,
child: 4,
},
Op::Remove {
parent: 2,
child: 16,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(tab_after_in(&batch, 10), Some(Some(2)));
// A menu (a list moving the focus with its own keys) keeps its place.
apply(
&mut c,
vec![
Op::Create {
id: 18,
tag: Tag::Overlay,
},
Op::SetProp {
id: 18,
prop: Prop::Accessibility(AccessibilityProp::Role(crate::AccessibilityRole::Menu)),
},
Op::Insert {
parent: 2,
child: 18,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(ROOT_ID, 18, None)));
assert_eq!(tab_after_in(&batch, 18).flatten(), None);
}
/// The `available` the last `onPosition` of overlay `id` told it.
fn told_room(
events: &[(NodeId, EventKind, EventPayload)],
id: NodeId,
) -> Option<(String, Size<Points>)> {
events
.iter()
.rev()
.find_map(|(at, kind, payload)| match payload {
EventPayload::Map(m) if *at == id && *kind == EventKind::Position => {
let placement = m.iter().find_map(|(k, v)| match (k, v) {
(&"placement", PayloadValue::Str(s)) => Some(s.to_string()),
_ => None,
})?;
let available = m.iter().find_map(|(k, v)| match (k, v) {
(&"available", PayloadValue::Size(s)) => Some(*s),
_ => None,
})?;
Some((placement, available))
}
_ => None,
})
}
#[test]
fn overlays_held_to_the_room_they_were_told_flip_at_their_natural_size() {
use StyleValue::Number;
let mut c = core();
// Up to the window's edges: no snap margin.
c.set_snap_to_window_margin(crate::geometry::px(0.0));
// A trigger low in a 320 × 480 screen: 56 points below it (less the
// offset), 376 above.
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(380.0))]);
add(
&mut c,
6,
Tag::View,
ROOT_ID,
&[("width", Number(80.0)), ("height", Number(40.0))],
);
add(&mut c, 10, Tag::Overlay, 6, &[]);
add(
&mut c,
12,
Tag::View,
10,
&[("width", Number(120.0)), ("height", Number(40.0))],
);
apply(
&mut c,
vec![
overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(6)),
),
overlay_prop(10, crate::OverlayProp::Align(crate::overlay::Align::Start)),
overlay_prop(10, crate::OverlayProp::Offset(px(4.0))),
Op::Listen {
id: 10,
event: EventKind::Position,
enabled: true,
},
],
);
// It fits below: there.
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 424.0, 120.0, 40.0)));
let events = js_events(&mut c);
let (placement, room) = told_room(&events, 10).expect("onPosition");
assert_eq!(placement, "bottom");
assert_eq!(room.height, px(56.0));
// The app holds it to that room (a list scrolling past it), as
// `nsh-base`'s popups do.
apply(&mut c, vec![style_op(10, &[("maxHeight", Number(56.0))])]);
// Its 40 points fit under that: nothing moves, so maybe no batch.
c.commit();
// The core sees it held to the room it was told: its max height is
// that room, the one the last `onPosition` carried.
let key = c.key(10).unwrap();
let state = c.overlay(key).expect("overlay");
assert_eq!(state.told.map(|t| t.height), Some(px(56.0)));
let layout = c.nodes[key as usize].layout.expect("laid out");
assert_eq!(
c.layout.style(layout).max_size.height,
taffy::LengthPercentageAuto::length(56.0)
);
// Its content grows past the room below, fitting above: it goes
// above, at its whole height once the app gives it the room there.
apply(
&mut c,
vec![style_op(
12,
&[("width", Number(120.0)), ("height", Number(300.0))],
)],
);
let batch = c.commit().unwrap();
// Measured without the room it was told: its natural 300 points.
let state = c.overlay(key).expect("overlay");
assert_eq!(state.natural, Some(px(300.0)));
assert_eq!(frame_of(&batch, 10).map(|f| f.origin.y), Some(px(76.0)));
let events = js_events(&mut c);
let (placement, room) = told_room(&events, 10).expect("onPosition");
assert_eq!(placement, "top");
assert_eq!(room.height, px(376.0));
apply(&mut c, vec![style_op(10, &[("maxHeight", Number(376.0))])]);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 76.0, 120.0, 300.0)));
// Taller than either side's room: the larger one, above, limited to
// it (the app's max height), from the top of the screen.
apply(
&mut c,
vec![style_op(
12,
&[("width", Number(120.0)), ("height", Number(450.0))],
)],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 0.0, 120.0, 376.0)));
let events = js_events(&mut c);
assert!(told_room(&events, 10).is_none_or(|(placement, _)| placement == "top"));
// Short again: it stays above while it fits there (the side asked for
// has no room for it), at its own height.
apply(
&mut c,
vec![style_op(
12,
&[("width", Number(120.0)), ("height", Number(100.0))],
)],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 276.0, 120.0, 100.0)));
}
#[test]
fn anchored_overlays_go_beside_their_anchor_and_follow_it() {
use StyleValue::Number;
let mut c = core();
add(
&mut c,
2,
Tag::Scroll,
ROOT_ID,
&[("height", Number(480.0))],
);
add(&mut c, 4, Tag::View, 2, &[("height", Number(100.0))]);
add(
&mut c,
6,
Tag::View,
2,
&[
("width", Number(80.0)),
("height", Number(40.0)),
("marginLeft", Number(20.0)),
],
);
add(&mut c, 8, Tag::View, 2, &[("height", Number(1000.0))]);
add(&mut c, 10, Tag::Overlay, 6, &[]);
add(
&mut c,
12,
Tag::View,
10,
&[("width", Number(120.0)), ("height", Number(60.0))],
);
apply(
&mut c,
vec![
overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(6)),
),
overlay_prop(10, crate::OverlayProp::Align(crate::overlay::Align::Start)),
overlay_prop(10, crate::OverlayProp::Offset(px(4.0))),
Op::Listen {
id: 10,
event: EventKind::Position,
enabled: true,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(20.0, 144.0, 120.0, 60.0)));
let events = js_events(&mut c);
assert!(events.iter().any(|(id, kind, payload)| *id == 10
&& *kind == EventKind::Position
&& matches!(payload, EventPayload::Map(m) if m.contains(&("placement", PayloadValue::Str("bottom".into()))))));
// The scroll view scrolled: it follows.
c.set_scroll_offset(2, point(px(0.0), px(30.0)), 0);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(20.0, 114.0, 120.0, 60.0)));
// Near the bottom of the screen it goes above.
c.set_scroll_offset(2, point(px(0.0), px(-300.0)), 0);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(20.0, 336.0, 120.0, 60.0)));
let events = js_events(&mut c);
assert!(events.iter().any(|(_, kind, payload)| *kind == EventKind::Position
&& matches!(payload, EventPayload::Map(m) if m.contains(&("placement", PayloadValue::Str("top".into()))))));
// Kept inside the safe area less the margin.
c.set_scroll_offset(2, point(px(0.0), px(0.0)), 0);
c.set_safe_area(EdgeInsets {
left: px(30.0),
..EdgeInsets::default()
});
apply(
&mut c,
vec![overlay_prop(10, crate::OverlayProp::Margin(px(8.0)))],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10).map(|f| f.origin.x), Some(px(38.0)));
// A point anchor.
apply(
&mut c,
vec![overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Point(point(
px(200.0),
px(50.0),
))),
)],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(192.0, 54.0, 120.0, 60.0)));
// A box anchor (an input's caret): below its bottom.
apply(
&mut c,
vec![overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Bounds(rect(
200.0, 50.0, 1.0, 20.0,
))),
)],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(192.0, 74.0, 120.0, 60.0)));
}
#[test]
fn anchored_overlays_go_within_the_area_the_platform_shows_them_in() {
use StyleValue::Number;
// A 320 × 480 root, 100 points from the left of a 1280 × 800 window and
// 50 from its top (the web's `overlays: "viewport"`), with a 40 point
// trigger near its bottom, 120 points from its left.
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(420.0))]);
add(
&mut c,
4,
Tag::View,
ROOT_ID,
&[
("width", Number(80.0)),
("height", Number(40.0)),
("marginLeft", Number(120.0)),
],
);
add(&mut c, 10, Tag::Overlay, 4, &[]);
add(
&mut c,
12,
Tag::View,
10,
&[("width", Number(360.0)), ("height", Number(200.0))],
);
apply(
&mut c,
vec![
overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(4)),
),
overlay_prop(10, crate::OverlayProp::Align(crate::overlay::Align::Start)),
overlay_prop(10, crate::OverlayProp::Margin(px(8.0))),
Op::Listen {
id: 10,
event: EventKind::PressOutside,
enabled: true,
},
],
);
// In the root view: no room below, above it, and wider than the root,
// from the margin.
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(8.0, 220.0, 360.0, 200.0)));
// Over the window: below the trigger, past the root's bottom, and
// from the trigger's start, past the root's right edge.
c.set_overlay_area(Some(rect(-100.0, -50.0, 1280.0, 800.0)));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(120.0, 460.0, 360.0, 200.0)));
// The page moved the root down to 300 points from the window's top:
// no room below in the window, above it.
c.set_overlay_area(Some(rect(-100.0, -300.0, 1280.0, 800.0)));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(120.0, 220.0, 360.0, 200.0)));
// Near the window's right edge: kept inside it less the margin.
c.set_overlay_area(Some(rect(-900.0, -50.0, 1280.0, 800.0)));
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 10).map(|f| f.origin.x),
Some(px(380.0 - 360.0 - 8.0))
);
// A press on the page around the root: outside the overlay.
js_events(&mut c);
let pressed = c.presses_beyond_root(point(px(500.0), px(-20.0)));
assert_eq!(pressed.len(), 1);
assert_eq!(pressed[0].0, 10);
// A press a view's native content took (a web view's page): outside
// the overlay on another view, inside it on its anchor or its content.
let page = point(px(10.0), px(10.0));
let pressed = c.presses_on_native(2, page);
assert_eq!(pressed.len(), 1);
assert_eq!(pressed[0].0, 10);
assert!(c.presses_on_native(4, page).is_empty());
assert!(c.presses_on_native(12, page).is_empty());
// Back to the root view.
c.set_overlay_area(None);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(8.0, 220.0, 360.0, 200.0)));
}
#[test]
fn anchored_overlays_keep_clear_of_the_software_keyboard() {
use StyleValue::{Number, Str};
// A 320 × 480 root with a 34 point bottom safe area, and a 40 point
// trigger 240 points from its top.
let mut c = core();
c.set_environment(env_with_keyboard(0.0, 250.0));
c.set_safe_area(EdgeInsets {
bottom: px(34.0),
..EdgeInsets::default()
});
add(
&mut c,
4,
Tag::View,
ROOT_ID,
&[
("width", Number(80.0)),
("height", Number(40.0)),
("marginTop", Number(240.0)),
],
);
// A popover below the trigger, and one as tall as its room lets it be.
add(&mut c, 10, Tag::Overlay, 4, &[]);
add(
&mut c,
12,
Tag::View,
10,
&[("width", Number(120.0)), ("height", Number(150.0))],
);
add(&mut c, 20, Tag::Overlay, 4, &[("maxHeight", Str("100%"))]);
add(
&mut c,
22,
Tag::View,
20,
&[("width", Number(120.0)), ("height", Number(600.0))],
);
for id in [10, 20] {
apply(
&mut c,
vec![
overlay_prop(
id,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(4)),
),
overlay_prop(id, crate::OverlayProp::Align(crate::overlay::Align::Start)),
overlay_prop(id, crate::OverlayProp::Margin(px(8.0))),
],
);
}
// Room below the trigger above the safe area: there.
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(8.0, 280.0, 120.0, 150.0)));
assert_eq!(
frame_of(&batch, 20).map(|f| f.size.height),
Some(px(480.0 - 34.0 - 16.0))
);
// The keyboard comes up 200 points (the safe area under it included):
// no room left below the trigger above it, so the popover flips above,
// and the tall one gets only the room above the keyboard.
c.set_environment(env_with_keyboard(200.0, 250.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(8.0, 90.0, 120.0, 150.0)));
assert_eq!(
frame_of(&batch, 20).map(|f| f.size.height),
Some(px(480.0 - 200.0 - 16.0))
);
let room = c.nodes[c.key(20).unwrap() as usize].frame;
assert!(room.bottom() <= px(480.0 - 200.0 - 8.0), "{room:?}");
// It moves with the keyboard's own motion.
assert!(
matches!(
&batch.items[0],
MountItem::LayoutAnimation(crate::LayoutAnimation {
update: Some(t), .. }) if t.curve == crate::LayoutCurve::Keyboard
),
"{:?}",
batch.items
);
// The keyboard goes: back below the trigger.
c.set_environment(env_with_keyboard(0.0, 250.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(8.0, 280.0, 120.0, 150.0)));
assert_eq!(
frame_of(&batch, 20).map(|f| f.size.height),
Some(px(480.0 - 34.0 - 16.0))
);
}
#[test]
fn an_anchored_overlay_wider_than_its_room_wraps_within_the_margin() {
use StyleValue::Number;
let mut c = core();
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[
("width", Number(80.0)),
("height", Number(40.0)),
("marginLeft", Number(120.0)),
],
);
// A popup of a long paragraph: as wide as its root view (320) would
// let it be, and wider than the room it keeps from the edges.
add(&mut c, 10, Tag::Overlay, 2, &[]);
add(&mut c, 12, Tag::Text, 10, &[]);
apply(
&mut c,
vec![
Op::CreateText {
id: 13,
text: "x".repeat(80),
},
Op::Insert {
parent: 12,
child: 13,
before: None,
},
overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
overlay_prop(10, crate::OverlayProp::Margin(px(8.0))),
Op::Listen {
id: 10,
event: EventKind::Position,
enabled: true,
},
],
);
let batch = c.commit().unwrap();
// Laid out in the room it is placed in: 8 from either edge, its text
// wrapped to that width (640 wide: three lines of 304).
assert_eq!(frame_of(&batch, 10), Some(rect(8.0, 40.0, 304.0, 48.0)));
// The safe area narrows that room: laid out again in it.
c.set_safe_area(EdgeInsets {
left: px(30.0),
right: px(10.0),
..EdgeInsets::default()
});
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(38.0, 40.0, 264.0, 48.0)));
// So does a larger margin.
c.set_safe_area(EdgeInsets::default());
apply(
&mut c,
vec![overlay_prop(10, crate::OverlayProp::Margin(px(20.0)))],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(20.0, 40.0, 280.0, 48.0)));
// Without an anchor it is a `position: fixed` box of the whole root
// view, margin or not.
apply(
&mut c,
vec![
overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::None),
),
style_op(
10,
&[
("left", Number(0.0)),
("right", Number(0.0)),
("bottom", Number(0.0)),
],
),
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 448.0, 320.0, 32.0)));
}
#[test]
fn a_framed_terminal_popup_keeps_its_frame_within_the_margin() {
use StyleValue::{Number, Str};
let mut c = core();
c.set_environment(crate::element::Environment {
cell: Some(crate::geometry::size_pt(8.0, 16.0)),
dark: true,
..Default::default()
});
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[
("width", Number(80.0)),
("height", Number(32.0)),
("marginLeft", Number(120.0)),
],
);
// A popup with a fill and no border, which a terminal frames one Cell
// outside its box, holding a paragraph wider than the room it keeps
// from the edges (8…312).
add(
&mut c,
10,
Tag::Overlay,
2,
&[("backgroundColor", Str("#25262a"))],
);
add(&mut c, 12, Tag::Text, 10, &[]);
apply(
&mut c,
vec![
Op::CreateText {
id: 13,
text: "x".repeat(80),
},
Op::Insert {
parent: 12,
child: 13,
before: None,
},
overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
overlay_prop(10, crate::OverlayProp::Margin(px(8.0))),
],
);
let batch = c.commit().unwrap();
let f = frame_of(&batch, 10).expect("the popup's frame");
// Its text wraps within the frame's room (36 of the area's 38 Cells),
// and the frame, a Cell each side of the box, stays within the area.
assert!(f.size.width.0 <= 288.0, "wrapped within its frame: {f:?}");
assert!(
f.origin.x.0 - 8.0 >= 8.0,
"the frame starts at the margin: {f:?}"
);
assert!(
f.origin.x.0 + f.size.width.0 + 8.0 <= 312.0,
"the frame ends at the margin: {f:?}"
);
}
#[test]
fn a_caret_is_located_in_the_root_view() {
use StyleValue::Number;
let mut c = core();
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[("paddingTop", Number(30.0)), ("paddingLeft", Number(12.0))],
);
add(
&mut c,
4,
Tag::Input,
2,
&[("width", Number(200.0)), ("height", Number(40.0))],
);
c.commit().unwrap();
let mut payload = EventPayload::caret(rect(25.0, 10.0, 1.0, 18.0));
c.locate_caret(4, &mut payload);
let EventPayload::Map(fields) = &payload else {
panic!("a map");
};
assert!(fields.contains(&("bounds", PayloadValue::Bounds(rect(25.0, 10.0, 1.0, 18.0)))));
assert!(fields.contains(&(
"pageBounds",
PayloadValue::Bounds(rect(37.0, 40.0, 1.0, 18.0))
)));
// A caret the platform could not place: empty, where the input is.
let mut payload = EventPayload::None;
c.locate_caret(4, &mut payload);
let EventPayload::Map(fields) = &payload else {
panic!("a map");
};
assert!(fields.contains(&("bounds", PayloadValue::Bounds(Bounds::default()))));
assert!(fields.contains(&(
"pageBounds",
PayloadValue::Bounds(rect(12.0, 30.0, 0.0, 0.0))
)));
// A selection's box gets its place in the root view the same way; a
// payload with none (nothing selected) stays as it is.
let mut payload = EventPayload::Map(vec![
("text", PayloadValue::Str("ab".into())),
("bounds", PayloadValue::Bounds(rect(5.0, 2.0, 30.0, 18.0))),
]);
c.locate_selection(4, &mut payload);
let EventPayload::Map(fields) = &payload else {
panic!("a map");
};
assert!(fields.contains(&(
"pageBounds",
PayloadValue::Bounds(rect(17.0, 32.0, 30.0, 18.0))
)));
let mut payload = EventPayload::Map(vec![("text", PayloadValue::Str(String::new()))]);
c.locate_selection(4, &mut payload);
assert_eq!(
payload,
EventPayload::Map(vec![("text", PayloadValue::Str(String::new()))])
);
}
fn touch_down(path: Vec<NodeId>) -> EventPayload {
EventPayload::Touch(Box::new(crate::TouchEvent {
phase: crate::TouchPhase::Start,
timestamp: 0.0,
points: vec![crate::TouchPoint {
id: 1,
target: path[0],
path,
page: point(px(5.0), px(6.0)),
location: point(px(5.0), px(6.0)),
changed: true,
pointer_type: crate::PointerType::Touch,
pressure: 0.5,
tilt_x: 0.0,
tilt_y: 0.0,
coalesced: Vec::new(),
eraser: false,
barrel: false,
}],
modifiers: Default::default(),
activated: None,
}))
}
#[test]
fn a_back_gesture_an_overlay_takes_stays_the_overlays() {
use crate::{BackPhase, BackProgressEvent, PanEdge, geometry::Percentage};
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[]);
add(&mut c, 4, Tag::Overlay, 2, &[]);
apply(
&mut c,
vec![
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
Op::Listen {
id: 4,
event: EventKind::Cancel,
enabled: true,
},
Op::Listen {
id: ROOT_ID,
event: EventKind::BackProgress,
enabled: true,
},
],
);
c.commit();
let step =
|phase| BackProgressEvent::new(phase, Percentage(0.5), Some(PanEdge::Left)).payload();
// The overlay takes the press: JS's listeners hear none of the steps,
// even once the overlay stops listening during the gesture.
assert!(c.component_event(ROOT_ID, EventKind::BackProgress, &step(BackPhase::Start)));
apply(
&mut c,
vec![Op::Listen {
id: 4,
event: EventKind::Cancel,
enabled: false,
}],
);
c.commit();
assert!(c.component_event(ROOT_ID, EventKind::BackProgress, &step(BackPhase::Move)));
assert!(c.component_event(ROOT_ID, EventKind::BackProgress, &step(BackPhase::Cancel)));
// Without it, the next gesture is the app's.
assert!(!c.component_event(ROOT_ID, EventKind::BackProgress, &step(BackPhase::Start)));
assert!(!c.component_event(ROOT_ID, EventKind::BackProgress, &step(BackPhase::Move)));
}
#[test]
fn overlays_hear_presses_outside_and_cancel_from_the_top() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(&mut c, 4, Tag::Overlay, 2, &[]);
add(&mut c, 6, Tag::Overlay, 4, &[]);
apply(
&mut c,
vec![
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
Op::Listen {
id: 4,
event: EventKind::PressOutside,
enabled: true,
},
Op::Listen {
id: 4,
event: EventKind::Cancel,
enabled: true,
},
Op::Listen {
id: 6,
event: EventKind::Cancel,
enabled: true,
},
],
);
let batch = c.commit().unwrap();
// The overlays, the anchor and the root listen to touches.
for id in [ROOT_ID, 2, 4, 6] {
let events = batch.items.iter().find_map(|i| match i {
MountItem::Events { id: i, events } if *i == id => Some(*events),
_ => None,
});
assert!(events.is_some_and(|e| e.contains(EventKind::Touch)), "{id}");
}
// Escape is bound, back listened to.
let keymap = batch.items.iter().find_map(|i| match i {
MountItem::Keymap(k) => Some(k.clone()),
_ => None,
});
assert!(keymap.is_some_and(|k| k.bindings().iter().any(|b| b.id == overlay::ESCAPE_BINDING)));
js_events(&mut c);
for (path, outside) in [
(vec![ROOT_ID], true),
(vec![2, ROOT_ID], false),
(vec![4, ROOT_ID], false),
(vec![6, ROOT_ID], false),
] {
c.component_event(ROOT_ID, EventKind::Touch, &touch_down(path.clone()));
let events = js_events(&mut c);
let pressed = events
.iter()
.any(|(id, kind, _)| *id == 4 && *kind == EventKind::PressOutside);
assert_eq!(pressed, outside, "{path:?}");
}
// The top one listening hears Escape and back.
c.component_event(
ROOT_ID,
EventKind::KeyCommand,
&EventPayload::Value(PayloadValue::Number(overlay::ESCAPE_BINDING as f64)),
);
c.commit();
let events = js_events(&mut c);
assert!(
events.contains(&(6, EventKind::Cancel, EventPayload::None)),
"{events:?}"
);
assert!(!events.iter().any(|(id, ..)| *id == 4));
apply(
&mut c,
vec![Op::Listen {
id: 6,
event: EventKind::Cancel,
enabled: false,
}],
);
c.commit();
assert!(c.component_event(ROOT_ID, EventKind::BackPress, &EventPayload::None));
c.commit();
let events = js_events(&mut c);
assert!(
events.contains(&(4, EventKind::Cancel, EventPayload::None)),
"{events:?}"
);
// Closed: nothing is listened to any more.
apply(
&mut c,
vec![Op::Remove {
parent: 2,
child: 4,
}],
);
let batch = c.commit().unwrap();
let root_events = batch.items.iter().find_map(|i| match i {
MountItem::Events {
id: ROOT_ID,
events,
} => Some(*events),
_ => None,
});
assert!(root_events.is_some_and(|e| !e.contains(EventKind::Touch)));
}
#[test]
fn a_secondary_click_is_a_press_outside_the_overlays_it_misses() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(&mut c, 4, Tag::Overlay, 2, &[]);
add(&mut c, 6, Tag::Overlay, 4, &[]);
add(&mut c, 8, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(&mut c, 10, Tag::View, 8, &[]);
add(&mut c, 12, Tag::View, 6, &[]);
add(&mut c, 14, Tag::View, 2, &[]);
apply(
&mut c,
vec![
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
Op::Listen {
id: 4,
event: EventKind::PressOutside,
enabled: true,
},
],
);
c.commit().unwrap();
js_events(&mut c);
let menu = |pointer_type| {
crate::ContextMenuEvent::new(
point(px(1.0), px(2.0)),
point(px(5.0), px(46.0)),
Default::default(),
pointer_type,
)
};
let mouse = Some(crate::PointerType::Mouse);
for (id, pointer_type, outside) in [
// Another view, and a view inside it.
(8, mouse, true),
(10, mouse, true),
// The anchor and what is in it, the overlay, one inside it.
(2, mouse, false),
(14, mouse, false),
(4, mouse, false),
(12, mouse, false),
// The keyboard and a long press do not press.
(10, None, false),
(10, Some(crate::PointerType::Touch), false),
] {
let events = c.context_menu_presses_outside(id, &menu(pointer_type));
let pressed = events
.iter()
.find_map(|(at, payload)| (*at == 4).then_some(payload));
assert_eq!(pressed.is_some(), outside, "{id} {pointer_type:?}");
if let Some(payload) = pressed {
assert_eq!(
payload,
&EventPayload::Map(vec![(
"pagePosition",
PayloadValue::Point(point(px(5.0), px(46.0)))
)])
);
}
}
}
#[test]
fn overlays_in_a_modal_show_in_it() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::Modal, ROOT_ID, &[]);
add(&mut c, 4, Tag::View, 2, &[("height", Number(40.0))]);
add(
&mut c,
6,
Tag::Overlay,
4,
&[("right", Number(0.0)), ("bottom", Number(0.0))],
);
add(
&mut c,
8,
Tag::View,
6,
&[("width", Number(10.0)), ("height", Number(10.0))],
);
c.set_root_size(2, size_pt(200.0, 300.0), EdgeInsets::default());
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(2, 6, None)));
assert_eq!(frame_of(&batch, 6), Some(rect(190.0, 290.0, 10.0, 10.0)));
}
#[test]
fn an_anchored_overlay_lands_on_whole_device_pixels() {
use StyleValue::Number;
for ratio in [1.0, 2.0, 3.0] {
let mut c = core();
at_ratio(&mut c, ratio);
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(480.0))]);
add(&mut c, 10, Tag::Overlay, 2, &[]);
add(
&mut c,
12,
Tag::View,
10,
&[("width", Number(120.0)), ("height", Number(60.0))],
);
// A pointer between pixels, as a context menu opens at.
apply(
&mut c,
vec![overlay_prop(
10,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Point(point(
px(100.38),
px(50.71),
))),
)],
);
let batch = c.commit().unwrap();
let frame = frame_of(&batch, 10).expect("overlay frame");
for v in [frame.origin.x.0, frame.origin.y.0] {
let pixels = v * ratio;
assert!(
(pixels - pixels.round()).abs() < 1.0e-3,
"{v} is not on a device pixel at {ratio}"
);
}
// Still centred on the pointer (100.38 - 120 / 2), within a pixel.
assert!((frame.origin.x.0 - 40.38).abs() <= 1.0 / ratio);
}
}
#[test]
fn overlays_with_a_cover_lay_that_view_over_the_anchor() {
use StyleValue::Number;
let mut c = core();
// A trigger 80 × 30 at (40, 100).
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[
("marginLeft", Number(40.0)),
("marginTop", Number(100.0)),
("width", Number(80.0)),
("height", Number(30.0)),
],
);
// A list of three 20-point rows under 4 points of padding.
add(&mut c, 8, Tag::Overlay, ROOT_ID, &[]);
add(
&mut c,
10,
Tag::View,
8,
&[("width", Number(100.0)), ("padding", Number(4.0))],
);
for id in [12, 14, 16] {
add(&mut c, id, Tag::View, 10, &[("height", Number(20.0))]);
}
apply(
&mut c,
vec![
overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
overlay_prop(8, crate::OverlayProp::Cover(Some(14))),
],
);
let batch = c.commit().unwrap();
// At the trigger's start, the second row (4, 24 in the list) with
// its middle on the trigger's.
assert_eq!(frame_of(&batch, 8), Some(rect(40.0, 81.0, 100.0, 68.0)));
// A row added before it moves it in the list: it is found again.
add(&mut c, 18, Tag::View, 10, &[("height", Number(20.0))]);
apply(
&mut c,
vec![Op::Insert {
parent: 10,
child: 18,
before: Some(12),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(40.0, 61.0, 100.0, 88.0)));
}
#[test]
fn overlays_beside_a_row_go_outside_the_menu_around_it() {
use StyleValue::Number;
let mut c = core();
// A menu 100 wide at (20, 0) with 6 points of padding, a 20-tall row in
// it.
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[
("marginLeft", Number(20.0)),
("width", Number(100.0)),
("padding", Number(6.0)),
("alignSelf", StyleValue::Str("flex-start")),
],
);
add(&mut c, 4, Tag::View, 2, &[("height", Number(20.0))]);
add(&mut c, 8, Tag::Overlay, ROOT_ID, &[]);
add(
&mut c,
10,
Tag::View,
8,
&[("width", Number(40.0)), ("height", Number(30.0))],
);
apply(
&mut c,
vec![
overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Beside {
node: 4,
edges: 2,
}),
),
overlay_prop(
8,
crate::OverlayProp::Placement(crate::overlay::Placement::Right),
),
overlay_prop(8, crate::OverlayProp::Align(crate::overlay::Align::Start)),
overlay_prop(8, crate::OverlayProp::Offset(crate::geometry::px(4.0))),
// At the window's top edge: no snap margin to keep.
overlay_prop(8, crate::OverlayProp::Margin(crate::geometry::px(0.0))),
],
);
let batch = c.commit().unwrap();
// Past the menu's right edge (120) by the offset, level with the row
// (6), not past the row's edge (114).
assert_eq!(frame_of(&batch, 8), Some(rect(124.0, 6.0, 40.0, 30.0)));
}
#[test]
fn overlays_anchored_to_content_go_by_what_the_wrapper_draws() {
use StyleValue::Number;
let mut c = core();
// Up to the window's edges: no snap margin.
c.set_snap_to_window_margin(crate::geometry::px(0.0));
// A wrapper the root stretches, around an 80 × 30 trigger.
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[("paddingTop", Number(50.0))],
);
add(&mut c, 4, Tag::View, 2, &[]);
add(
&mut c,
6,
Tag::View,
4,
&[
("width", Number(80.0)),
("height", Number(30.0)),
("alignSelf", StyleValue::Str("flex-start")),
],
);
add(&mut c, 8, Tag::Overlay, 2, &[]);
add(
&mut c,
10,
Tag::View,
8,
&[("width", Number(40.0)), ("height", Number(20.0))],
);
apply(
&mut c,
vec![overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Content(4)),
)],
);
let batch = c.commit().unwrap();
// Centered below the trigger (0, 50, 80 × 30), not the 320-wide wrapper.
assert_eq!(frame_of(&batch, 8), Some(rect(20.0, 80.0, 40.0, 20.0)));
// Against the wrapper itself: centered on its width.
apply(
&mut c,
vec![overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(4)),
)],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(140.0, 80.0, 40.0, 20.0)));
// A trigger with padding and a border around its label: its whole box,
// so the overlay's start lines up with the trigger's edge.
add(
&mut c,
12,
Tag::View,
2,
&[
("paddingLeft", Number(10.0)),
("paddingRight", Number(10.0)),
("borderWidth", Number(1.0)),
("alignSelf", StyleValue::Str("flex-start")),
],
);
add(
&mut c,
14,
Tag::View,
12,
&[("width", Number(30.0)), ("height", Number(16.0))],
);
apply(
&mut c,
vec![
overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Content(12)),
),
overlay_prop(8, crate::OverlayProp::Align(crate::overlay::Align::Start)),
],
);
let batch = c.commit().unwrap();
// The trigger (0, 80, 52 × 18) below the first one.
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 98.0, 40.0, 20.0)));
// A trigger 28 points tall, its 16-point label centered: below its
// own bottom edge, not its label's.
add(
&mut c,
16,
Tag::View,
2,
&[
("height", Number(28.0)),
("justifyContent", StyleValue::Str("center")),
("alignSelf", StyleValue::Str("flex-start")),
],
);
add(
&mut c,
18,
Tag::View,
16,
&[("width", Number(30.0)), ("height", Number(16.0))],
);
apply(
&mut c,
vec![overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Content(16)),
)],
);
let batch = c.commit().unwrap();
// The trigger (0, 98, 30 × 28) below the second one.
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 126.0, 40.0, 20.0)));
}
/// The texts a batch lays out.
fn texts_of(batch: &MountBatch) -> Vec<String> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.clone()),
_ => None,
})
.collect()
}
/// Whether the batch mounts `id` listening to `kind`.
fn mounts_listening(batch: &MountBatch, id: NodeId, kind: EventKind) -> Option<bool> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Events { id: i, events } if *i == id => Some(events.contains(kind)),
_ => None,
})
}
#[test]
fn tooltips_show_after_the_pointer_rests_and_hide_when_it_leaves_or_presses() {
use StyleValue::Number;
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[
("marginTop", Number(100.0)),
("width", Number(80.0)),
("height", Number(40.0)),
],
);
apply(
&mut c,
vec![
// The app's element, out of the tree.
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 6,
text: "Saves it".into(),
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(4)),
},
],
);
let batch = c.commit().unwrap();
// The element follows the pointer; the tooltip waits out of the view.
assert_eq!(
mounts_listening(&batch, 2, EventKind::MouseEnter),
Some(true)
);
assert!(texts_of(&batch).is_empty(), "{:?}", texts_of(&batch));
c.component_event(
2,
EventKind::MouseEnter,
&EventPayload::Mouse(crate::MouseEvent::default()),
);
c.run_component_tasks();
assert!(c.commit().is_none());
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(499));
c.run_component_tasks();
assert!(c.commit().is_none());
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(1));
c.run_component_tasks();
let batch = c.commit().unwrap();
assert_eq!(texts_of(&batch), ["Saves it"]);
// In the root view, above the element.
let overlay = inserts(&batch)
.into_iter()
.find(|&(p, ..)| p == ROOT_ID)
.map(|(_, child, _)| child)
.expect("the tooltip's overlay in the root view");
let frame = frame_of(&batch, overlay).unwrap();
assert_eq!(frame.bottom(), px(96.0));
// Leaving hides it.
c.component_event(
2,
EventKind::MouseLeave,
&EventPayload::Mouse(crate::MouseEvent::default()),
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == overlay))
);
// A press hides it too, until the pointer comes again.
c.component_event(
2,
EventKind::MouseEnter,
&EventPayload::Mouse(crate::MouseEvent::default()),
);
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(500));
c.run_component_tasks();
assert!(c.commit().is_some());
c.component_event(ROOT_ID, EventKind::Touch, &touch_down(vec![2, ROOT_ID]));
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == overlay))
);
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(1000));
c.run_component_tasks();
assert!(c.commit().is_none());
// No tooltip: the element no longer follows the pointer.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::None),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
mounts_listening(&batch, 2, EventKind::MouseEnter),
Some(false)
);
}
#[test]
fn tooltips_wait_for_nothing_on_touch_screens() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
apply(
&mut c,
vec![
// The app's element, out of the tree.
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 6,
text: "Saves it".into(),
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(4)),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(mounts_listening(&batch, 2, EventKind::MouseEnter), None);
}
#[test]
fn a_tooltip_element_is_shown_as_it_is() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(&mut c, 4, Tag::Text, ROOT_ID, &[]);
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 4,
},
Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(4)),
},
// Shown whatever the pointer does.
Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(4)),
},
],
);
c.commit();
let key = c.key(4).unwrap();
let overlay = c.nodes[key as usize].parent;
assert_eq!(c.nodes[overlay as usize].kind, Kind::Overlay);
assert_eq!(c.nodes[c.nodes[overlay as usize].parent as usize].id, 2);
// Another element in its place: the first leaves (still JS's).
apply(
&mut c,
vec![
Op::Create {
id: 8,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(8)),
},
],
);
c.commit();
assert_eq!(c.nodes[c.key(4).unwrap() as usize].parent, NO_KEY);
// Released with the element.
let made = c.overlay_state.tooltips[&2];
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
c.commit();
assert!(c.overlay_state.tooltips.is_empty());
assert!(c.key(made.overlay).is_err());
}
#[test]
fn a_tooltip_element_that_is_a_hint_overlay_is_the_tooltip_itself() {
use StyleValue::Number;
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
// As `nsh-base`'s `Tooltip` makes it: a hint overlay, out of the tree.
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::Overlay,
},
overlay_prop(
4,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
),
Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(4)),
},
],
);
let wrapper = c.overlay_state.tooltips[&2].overlay;
c.commit();
let made = c.overlay_state.tooltips[&2];
assert_eq!(made.overlay, 4);
assert!(c.key(wrapper).is_err(), "the core's own overlay is gone");
let key = c.key(4).unwrap();
assert_eq!(c.nodes[c.nodes[key as usize].parent as usize].id, 2);
// Another tooltip: it leaves the element, still JS's.
apply(
&mut c,
vec![
Op::Create {
id: 8,
tag: Tag::View,
},
Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(8)),
},
],
);
c.commit();
assert_eq!(c.nodes[c.key(4).unwrap() as usize].parent, NO_KEY);
assert_ne!(c.overlay_state.tooltips[&2].overlay, 4);
}
/// Gives element `id` a `tooltip` saying `says`: the app's element, a
/// text `content` out of the tree (its run `content + 2`).
fn give_tooltip(c: &mut Core<FakeEngine>, id: NodeId, content: NodeId, says: &str) {
apply(
c,
vec![
Op::Create {
id: content,
tag: Tag::Text,
},
Op::CreateText {
id: content + 2,
text: says.into(),
},
Op::Insert {
parent: content,
child: content + 2,
before: None,
},
Op::SetProp {
id,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(content)),
},
],
);
}
/// A core on `os`'s desktop.
fn core_on(os: crate::platform::Os) -> Core<FakeEngine> {
let mut c = core();
c.set_environment(crate::element::Environment {
os,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
c
}
/// Whether the `tooltip` of element `id` is shown: its hint overlay is
/// in a root view.
fn tooltip_shown(c: &Core<FakeEngine>, id: NodeId) -> bool {
let overlay = c.overlay_state.tooltips[&id].overlay;
c.key(overlay)
.ok()
.and_then(|k| c.overlay(k))
.is_some_and(|s| s.host.is_some())
}
#[test]
fn modal_focus_restoration_does_not_show_a_tooltip_until_new_user_input() {
use StyleValue::Number;
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let mut c = core_on(crate::platform::Os::Windows);
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(&mut c, 8, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
give_tooltip(&mut c, 2, 4, "Choose gateway");
c.commit();
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
c.commit();
add(&mut c, 20, Tag::Modal, ROOT_ID, &[]);
add(&mut c, 22, Tag::View, 20, &[("height", Number(40.0))]);
c.commit();
c.set_states(22, FOCUSED);
c.set_states(2, 0);
c.commit();
// Escape closes the modal; restoring focus must not become a tooltip activation.
c.set_input_modality(InputModality::Keyboard);
apply(
&mut c,
vec![Op::Remove {
parent: ROOT_ID,
child: 20,
}],
);
c.commit();
c.set_states(2, FOCUSED);
c.set_states(22, 0);
c.commit();
assert!(
c.focus_visible,
"restored keyboard focus still has its ring"
);
assert!(
!tooltip_shown(&c, 2),
"restoring focus reopened the tooltip"
);
c.set_input_modality(InputModality::Keyboard);
c.set_states(8, FOCUSED);
c.set_states(2, 0);
c.commit();
c.set_input_modality(InputModality::Keyboard);
c.set_states(2, FOCUSED);
c.set_states(8, 0);
c.commit();
assert!(
tooltip_shown(&c, 2),
"fresh keyboard navigation still opens the tooltip"
);
}
#[test]
fn a_tooltip_shows_for_the_focus_the_keyboard_moved_only() {
use StyleValue::Number;
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let mut c = core_on(crate::platform::Os::Windows);
// A trigger with a tooltip (2), and a view with none (8).
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(&mut c, 8, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
give_tooltip(&mut c, 2, 4, "Saves it");
c.commit();
assert!(!tooltip_shown(&c, 2));
// A press gives the trigger the focus (a click, or the app's
// `focus()` after one): no hint for that focus.
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
c.commit();
assert!(!tooltip_shown(&c, 2), "a press's focus shows no hint");
// A key typed with the focus where it is shows the focus, not the
// hint: only a move decides.
c.set_input_modality(InputModality::Keyboard);
c.commit();
assert!(focus_visible(&c, 2));
assert!(!tooltip_shown(&c, 2), "a key alone shows no hint");
// Tab to the next view, and Shift+Tab back: the keyboard's focus
// shows it at once, as the platforms report the move (the view it
// reaches first).
c.set_states(8, FOCUSED);
c.set_states(2, 0);
c.commit();
assert!(!tooltip_shown(&c, 2));
c.set_states(2, FOCUSED);
c.set_states(8, 0);
let batch = c.commit().unwrap();
assert!(tooltip_shown(&c, 2), "the keyboard's focus shows it");
assert_eq!(texts_of(&batch), ["Saves it"]);
// A press elsewhere takes the focus and hides it; a press back on the
// trigger shows none.
c.set_input_modality(InputModality::Pointer);
c.set_states(8, FOCUSED);
c.set_states(2, 0);
c.commit();
assert!(!tooltip_shown(&c, 2));
c.set_states(2, FOCUSED);
c.set_states(8, 0);
c.commit();
assert!(!tooltip_shown(&c, 2));
}
#[test]
fn a_click_that_focuses_the_trigger_leaves_its_tooltip_to_the_pointer() {
use StyleValue::Number;
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Linux,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
give_tooltip(&mut c, 2, 4, "Saves it");
c.commit();
let mouse = EventPayload::Mouse(crate::MouseEvent::default());
let rest = |c: &mut Core<FakeEngine>| {
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(500));
c.run_component_tasks();
c.commit();
};
// The pointer rests on the trigger: its tooltip shows.
c.component_event(2, EventKind::MouseEnter, &mouse);
rest(&mut c);
assert!(tooltip_shown(&c, 2));
// A click: the button goes down on the trigger, which hides the hint,
// and gives it the focus, as AppKit gives a clicked stop the focus.
c.set_input_modality(InputModality::Pointer);
c.component_event(ROOT_ID, EventKind::Touch, &touch_down(vec![2, ROOT_ID]));
c.set_states(2, FOCUSED);
c.commit();
assert!(
!tooltip_shown(&c, 2),
"the click hid it, and the focus it gave shows none"
);
// The pointer leaves, the focus staying: nothing is left up.
c.component_event(2, EventKind::MouseLeave, &mouse);
rest(&mut c);
assert!(!tooltip_shown(&c, 2), "nothing stays once the pointer left");
// The pointer coming again shows it after its delay, and leaving
// hides it, the focus still on the trigger.
c.component_event(2, EventKind::MouseEnter, &mouse);
rest(&mut c);
assert!(tooltip_shown(&c, 2));
c.component_event(2, EventKind::MouseLeave, &mouse);
c.commit();
assert!(!tooltip_shown(&c, 2));
}
#[test]
fn a_click_into_a_field_shows_its_focus_but_leaves_its_tooltip_to_the_pointer() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Input,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
give_tooltip(&mut c, 2, 4, "Your name");
c.commit();
c.set_input_modality(InputModality::Pointer);
c.set_states(2, FOCUSED);
c.commit();
// `focus-visible:` shows on a field that edits whatever gave it the
// focus; its hint does not.
assert!(focus_visible(&c, 2));
assert!(!tooltip_shown(&c, 2));
}
#[test]
fn a_focus_before_any_input_shows_its_ring_but_no_tooltip() {
use crate::tailwind::state::FOCUSED;
// The app's first focus (an `autoFocus` at launch) comes after no
// input: it shows `focus-visible:`, as a browser's `autofocus` does,
// but no hint, as WinUI shows none for a focus the user did not move.
for os in [crate::platform::Os::Windows, crate::platform::Os::Linux] {
let mut c = core_on(os);
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[("height", StyleValue::Number(40.0))],
);
give_tooltip(&mut c, 2, 4, "Saves it");
c.commit();
c.set_states(2, FOCUSED);
c.commit();
assert!(focus_visible(&c, 2), "{os:?}");
assert!(!tooltip_shown(&c, 2), "{os:?}");
}
}
#[test]
fn the_keyboard_focus_shows_no_tooltip_on_macos_and_ios() {
use StyleValue::Number;
use crate::{platform::InputModality, tailwind::state::FOCUSED};
// AppKit's and UIKit's tooltips show only for the pointer: Tab onto
// a trigger shows its ring, never its tooltip.
for os in [crate::platform::Os::MacOs, crate::platform::Os::Ios] {
let mut c = core_on(os);
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
add(&mut c, 8, Tag::View, ROOT_ID, &[("height", Number(40.0))]);
give_tooltip(&mut c, 2, 4, "Saves it");
c.commit();
c.set_input_modality(InputModality::Keyboard);
c.set_states(8, FOCUSED);
c.commit();
c.set_states(2, FOCUSED);
c.set_states(8, 0);
c.commit();
assert!(focus_visible(&c, 2), "{os:?}");
assert!(
!tooltip_shown(&c, 2),
"{os:?}: the keyboard's focus showed it"
);
}
}
/// Gives element `id` a `tooltip` that is hint overlay `overlay` itself (as
/// `nsh-base`'s `Tooltip` makes it), waiting `delay`.
fn give_hint_tooltip(
c: &mut Core<FakeEngine>,
id: NodeId,
overlay: NodeId,
delay: std::time::Duration,
) {
apply(
c,
vec![
Op::Create {
id: overlay,
tag: Tag::Overlay,
},
overlay_prop(overlay, crate::OverlayProp::Hint(Some(delay))),
Op::SetProp {
id,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(overlay)),
},
],
);
}
/// A core on a desktop with the tools of a toolbar: views `ids` in the
/// root.
fn toolbar_core(ids: &[NodeId]) -> Core<FakeEngine> {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
for &id in ids {
add(
&mut c,
id,
Tag::View,
ROOT_ID,
&[
("width", StyleValue::Number(40.0)),
("height", StyleValue::Number(40.0)),
],
);
}
c
}
/// Those of views `ids` that a hint watches for the pointer.
fn hint_watched(c: &Core<FakeEngine>, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter()
.copied()
.filter(|&id| {
c.key(id).is_ok_and(|k| {
c.nodes[k as usize].overlay_watched & super::overlay::watch::HINT != 0
})
})
.collect()
}
/// An element listens to the pointer while its tooltip's hint is in the
/// view, whatever starts and stops listening beside it in the same commit.
#[test]
fn hint_anchors_listen_while_their_hints_are_in_the_view() {
let ids: Vec<NodeId> = (0..8).map(|i| 2 + i * 8).collect();
let mut c = toolbar_core(&ids);
for &id in &ids[..6] {
give_tooltip(&mut c, id, id + 2, "Tool");
}
c.commit();
assert_eq!(hint_watched(&c, &ids), ids[..6]);
// One hides, one loses its tooltip, one past them gains one.
apply(
&mut c,
vec![
style_op(ids[1], &[("display", StyleValue::Str("none"))]),
Op::SetProp {
id: ids[3],
prop: Prop::Tooltip(crate::overlay::TooltipContent::None),
},
],
);
give_tooltip(&mut c, ids[6], ids[6] + 2, "Tool");
c.commit();
assert_eq!(
hint_watched(&c, &ids),
[ids[0], ids[2], ids[4], ids[5], ids[6]]
);
// The hidden one shows again; one goes, and a view made in the same
// commit (which may take its key) listens for its own tooltip.
apply(
&mut c,
vec![
style_op(ids[1], &[("display", StyleValue::Str("flex"))]),
Op::Remove {
parent: ROOT_ID,
child: ids[4],
},
Op::Release { id: ids[4] },
],
);
add(
&mut c,
200,
Tag::View,
ROOT_ID,
&[("height", StyleValue::Number(40.0))],
);
give_tooltip(&mut c, 200, 202, "Tool");
c.commit();
let mut all = ids.clone();
all.push(200);
assert_eq!(
hint_watched(&c, &all),
[ids[0], ids[1], ids[2], ids[5], ids[6], 200]
);
}
/// A hint anchored explicitly to a span listens through the text block the
/// span is in now, after the span moves to another block.
#[test]
fn moving_a_hint_watched_span_rewatches_its_new_text_block() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
apply(
&mut c,
vec![
Op::Create {
id: 10,
tag: Tag::Text,
},
Op::Create {
id: 12,
tag: Tag::Text,
},
Op::Insert {
parent: ROOT_ID,
child: 10,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 12,
before: None,
},
Op::Create {
id: 14,
tag: Tag::Text,
},
Op::Insert {
parent: 10,
child: 14,
before: None,
},
Op::Create {
id: 20,
tag: Tag::Overlay,
},
overlay_prop(
20,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
),
overlay_prop(
20,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(14)),
),
Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
},
],
);
c.commit();
assert_eq!(hint_watched(&c, &[10, 12, 14]), [10, 14]);
apply(
&mut c,
vec![
Op::Remove {
parent: 10,
child: 14,
},
Op::Insert {
parent: 12,
child: 14,
before: None,
},
],
);
c.commit();
assert_eq!(hint_watched(&c, &[10, 12, 14]), [12, 14]);
}
/// Moving a span that only contains a hint's anchor still moves the
/// anchor's watch to the text block it is in now.
#[test]
fn moving_a_parent_span_rewatches_its_nested_hint_anchor_block() {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
apply(
&mut c,
vec![
Op::Create {
id: 10,
tag: Tag::Text,
},
Op::Create {
id: 12,
tag: Tag::Text,
},
Op::Insert {
parent: ROOT_ID,
child: 10,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 12,
before: None,
},
Op::Create {
id: 16,
tag: Tag::Text,
},
Op::Create {
id: 14,
tag: Tag::Text,
},
Op::Insert {
parent: 10,
child: 16,
before: None,
},
Op::Insert {
parent: 16,
child: 14,
before: None,
},
Op::Create {
id: 20,
tag: Tag::Overlay,
},
overlay_prop(
20,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
),
overlay_prop(
20,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(14)),
),
Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
},
],
);
c.commit();
assert_eq!(hint_watched(&c, &[10, 12, 14, 16]), [10, 14]);
apply(
&mut c,
vec![
Op::Remove {
parent: 10,
child: 16,
},
Op::Insert {
parent: 12,
child: 16,
before: None,
},
],
);
c.commit();
assert_eq!(hint_watched(&c, &[10, 12, 14, 16]), [12, 14]);
}
/// What telling the anchors of `n` tooltips in the view which listen
/// looked at over two commits, one changing none of them and one hiding
/// one ([`Components::watch_work`]).
fn hint_watch_work(n: u32) -> usize {
let ids: Vec<NodeId> = (0..n).map(|i| 2 + i * 8).collect();
let mut c = toolbar_core(&ids);
for &id in &ids {
give_tooltip(&mut c, id, id + 2, "Link");
}
c.commit();
c.components.watch_work.set(0);
c.commit();
apply(
&mut c,
vec![style_op(
ids[ids.len() / 2],
&[("display", StyleValue::Str("none"))],
)],
);
c.commit();
c.components.watch_work.get()
}
/// Each of a document's links has a hint whose anchor listens while it is
/// in the view, and every commit tells which anchors start and stop: it
/// walks them once, so four times the links is about four times the work.
#[test]
fn hint_anchors_are_looked_at_once_a_commit() {
let (few, many) = (hint_watch_work(400), hint_watch_work(1_600));
assert!(
many <= 5 * few.max(1),
"{few} for 400 links, {many} for 1,600"
);
}
/// A commit that changes nothing, with `n` tooltips' hints in the view
/// twelve views deep, as a document's links are: on a desktop, where
/// their anchors listen to the pointer, and on a phone, where they do not.
/// `cargo test --release -p nsh-core --lib bench_hint_overlays_per_commit
/// -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_hint_overlays_per_commit() {
use crate::platform::{Idiom, Os};
for (os, idiom) in [(Os::MacOs, Idiom::Desktop), (Os::Ios, Idiom::Phone)] {
for n in [250u32, 1_000, 2_000, 4_000] {
let mut c = core();
c.set_environment(crate::element::Environment {
os,
idiom,
..crate::element::Environment::default()
});
let mut parent = ROOT_ID;
for depth in 0..12 {
let id = 1_000_000 + depth * 2;
add(&mut c, id, Tag::View, parent, &[]);
parent = id;
}
for i in 0..n {
let id = 2 + i * 8;
add(
&mut c,
id,
Tag::View,
parent,
&[("height", StyleValue::Number(20.0))],
);
give_tooltip(&mut c, id, id + 2, "Link");
}
c.commit();
c.commit();
let runs = 200;
let best = (0..5)
.map(|_| {
let start = std::time::Instant::now();
for _ in 0..runs {
c.commit();
}
start.elapsed() / runs
})
.min()
.unwrap();
eprintln!(
"{idiom:?} {n} tooltips ({} anchors listening): {best:?} a commit",
c.overlay_state.hinting.len(),
);
}
}
}
/// The ops attaching `rows` chains of `depth` views below `parent`, deepest
/// first as a reconciler builds a subtree and attaches it upward.
fn deep_rows_ops(rows: u32, depth: u32, parent: NodeId, first: NodeId) -> Vec<Op> {
let mut ops = Vec::new();
for row in 0..rows {
let base = first + row * depth;
for level in 0..depth {
ops.push(Op::Create {
id: base + level,
tag: Tag::View,
});
}
for level in (1..depth).rev() {
ops.push(Op::Insert {
parent: base + level - 1,
child: base + level,
before: None,
});
}
ops.push(Op::Insert {
parent,
child: base,
before: None,
});
}
ops
}
/// One unrelated tooltip beside a large tree: the tree's mount and moves
/// must not scan its subtrees once per node only because the tooltip exists.
/// `cargo test --release -p nsh-core --lib bench_overlay_tree_mount_and_move
/// -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_overlay_tree_mount_and_move() {
const DEPTH: u32 = 6;
const CONTAINER: NodeId = 900_000;
const MOVED_TO: NodeId = 900_002;
const FIRST: NodeId = 100_000;
for rows in [2_000u32, 4_000] {
let mut mounts = Vec::new();
let mut moves = Vec::new();
for _ in 0..5 {
let mut c = toolbar_core(&[2]);
give_tooltip(&mut c, 2, 4, "Unrelated");
add(&mut c, CONTAINER, Tag::View, ROOT_ID, &[]);
add(&mut c, MOVED_TO, Tag::View, ROOT_ID, &[]);
c.commit();
let ops = deep_rows_ops(rows, DEPTH, CONTAINER, FIRST);
let start = std::time::Instant::now();
apply(&mut c, ops);
c.commit().unwrap();
mounts.push(start.elapsed());
let mut moving = Vec::new();
for row in 0..rows {
let id = FIRST + row * DEPTH;
moving.push(Op::Remove {
parent: CONTAINER,
child: id,
});
moving.push(Op::Insert {
parent: MOVED_TO,
child: id,
before: None,
});
}
let start = std::time::Instant::now();
apply(&mut c, moving);
c.commit().unwrap();
moves.push(start.elapsed());
}
eprintln!(
"{rows} rows x depth {DEPTH}, one tooltip: mount {:?}, move {:?}",
mounts.iter().min().unwrap(),
moves.iter().min().unwrap()
);
}
}
/// Rust rows each of a width of its own, as a chart's bars are: the core
/// keeps each style's lowered rules, found by the style's hash
/// (`Components::lowered`).
mod own_widths {
use super::*;
use crate::{element::Root, prelude::*};
#[derive(Clone, PartialEq, Props)]
struct BarsProps {
#[prop(default)]
n: u32,
}
#[component]
fn Bars(props: BarsProps) -> impl IntoElement {
view().children((0..props.n).map(|i| view().w(px(1.0 + i as f32)).h(px(4.0))))
}
/// The mount of `n` bars, the first commit included.
/// `cargo test --release -p nsh-core --lib bench_bars_of_their_own_widths
/// -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_bars_of_their_own_widths() {
for n in [250u32, 1_000, 2_000, 4_000] {
let best = (0..5)
.map(|_| {
let mut c = core();
let start = std::time::Instant::now();
c.mount_root(&Root::new::<Bars>(move || BarsProps { n }));
c.commit().unwrap();
start.elapsed()
})
.min()
.unwrap();
eprintln!("{n} bars: {best:?} a mount");
}
}
}
#[test]
fn a_tooltip_shows_at_once_after_the_pointer_left_one_it_showed() {
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = toolbar_core(&[2, 8, 14]);
give_tooltip(&mut c, 2, 4, "Move");
give_tooltip(&mut c, 8, 10, "Pen");
give_tooltip(&mut c, 14, 16, "Text");
c.commit();
let mouse = EventPayload::Mouse(crate::MouseEvent::default());
let wait = |c: &mut Core<FakeEngine>, ms: u64| {
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(ms));
c.run_component_tasks();
c.commit();
};
// The pointer rests on the first tool: its tooltip shows after its
// delay.
c.component_event(2, EventKind::MouseEnter, &mouse);
wait(&mut c, 499);
assert!(!tooltip_shown(&c, 2));
wait(&mut c, 1);
assert!(tooltip_shown(&c, 2));
// It moves on to the next tool: that one's shows at once.
c.component_event(2, EventKind::MouseLeave, &mouse);
c.component_event(8, EventKind::MouseEnter, &mouse);
c.commit();
assert!(!tooltip_shown(&c, 2));
assert!(tooltip_shown(&c, 8), "at once after one the pointer showed");
// Off the toolbar for a moment, then on the third: still at once.
c.component_event(8, EventKind::MouseLeave, &mouse);
wait(&mut c, 299);
assert!(!tooltip_shown(&c, 8));
c.component_event(14, EventKind::MouseEnter, &mouse);
c.commit();
assert!(tooltip_shown(&c, 14), "within the grace period");
// Back to the tool it just left: at once too.
c.component_event(14, EventKind::MouseLeave, &mouse);
c.component_event(14, EventKind::MouseEnter, &mouse);
c.commit();
assert!(tooltip_shown(&c, 14));
// Away for the whole grace period: the next waits its delay again.
c.component_event(14, EventKind::MouseLeave, &mouse);
wait(&mut c, 300);
c.component_event(2, EventKind::MouseEnter, &mouse);
wait(&mut c, 499);
assert!(!tooltip_shown(&c, 2), "the grace period is over");
wait(&mut c, 1);
assert!(tooltip_shown(&c, 2));
// The pointer comes to a tool inside another whose tooltip it shows
// (it left none): at once.
let inner = 20;
add(
&mut c,
inner,
Tag::View,
2,
&[("height", StyleValue::Number(10.0))],
);
give_tooltip(&mut c, inner, 22, "Inner");
c.commit();
c.component_event(inner, EventKind::MouseEnter, &mouse);
c.commit();
assert!(
tooltip_shown(&c, inner),
"while one the pointer showed is up"
);
assert!(tooltip_shown(&c, 2));
}
#[test]
fn a_press_or_escape_ends_the_tooltips_grace_period_and_the_focus_starts_none() {
use crate::{platform::InputModality, tailwind::state::FOCUSED};
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = toolbar_core(&[2, 8, 26]);
// Windows: its tooltips follow the keyboard's focus too.
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Windows,
idiom: crate::platform::Idiom::Desktop,
..crate::element::Environment::default()
});
give_tooltip(&mut c, 2, 4, "Move");
give_tooltip(&mut c, 8, 10, "Pen");
c.commit();
let mouse = EventPayload::Mouse(crate::MouseEvent::default());
let wait = |c: &mut Core<FakeEngine>, ms: u64| {
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(ms));
c.run_component_tasks();
c.commit();
};
let escape = |c: &mut Core<FakeEngine>| {
c.component_event(
ROOT_ID,
EventKind::KeyCommand,
&EventPayload::Value(PayloadValue::Number(overlay::ESCAPE_BINDING as f64)),
);
c.commit();
};
// Shown on the first tool, then at once on the second.
c.component_event(2, EventKind::MouseEnter, &mouse);
wait(&mut c, 500);
c.component_event(2, EventKind::MouseLeave, &mouse);
c.component_event(8, EventKind::MouseEnter, &mouse);
c.commit();
assert!(tooltip_shown(&c, 8));
// A press on the second hides its tooltip and ends the grace period:
// back on the first, it waits its delay.
c.component_event(ROOT_ID, EventKind::Touch, &touch_down(vec![8, ROOT_ID]));
c.commit();
assert!(!tooltip_shown(&c, 8));
c.component_event(8, EventKind::MouseLeave, &mouse);
c.component_event(2, EventKind::MouseEnter, &mouse);
c.commit();
assert!(!tooltip_shown(&c, 2), "a press ends the grace period");
wait(&mut c, 500);
assert!(tooltip_shown(&c, 2));
// Escape the same: shown at once on the second, Escape hides it, and
// the first waits again.
c.component_event(2, EventKind::MouseLeave, &mouse);
c.component_event(8, EventKind::MouseEnter, &mouse);
c.commit();
assert!(tooltip_shown(&c, 8));
escape(&mut c);
assert!(!tooltip_shown(&c, 8), "Escape hides it");
c.component_event(8, EventKind::MouseLeave, &mouse);
c.component_event(2, EventKind::MouseEnter, &mouse);
c.commit();
assert!(!tooltip_shown(&c, 2), "Escape ends the grace period");
wait(&mut c, 500);
assert!(tooltip_shown(&c, 2));
c.component_event(2, EventKind::MouseLeave, &mouse);
wait(&mut c, 300);
// The keyboard's focus shows the first at once; the pointer coming to
// the second waits its delay, and the focus leaving starts nothing.
c.set_input_modality(InputModality::Keyboard);
c.set_states(2, FOCUSED);
c.commit();
assert!(
tooltip_shown(&c, 2),
"the keyboard's focus shows it at once"
);
c.component_event(8, EventKind::MouseEnter, &mouse);
c.commit();
assert!(!tooltip_shown(&c, 8), "a hint the focus shows starts none");
c.component_event(8, EventKind::MouseLeave, &mouse);
// Tab to a view with no tooltip.
c.set_states(26, FOCUSED);
c.set_states(2, 0);
c.commit();
assert!(!tooltip_shown(&c, 2));
c.component_event(8, EventKind::MouseEnter, &mouse);
c.commit();
assert!(!tooltip_shown(&c, 8), "nor does the focus leaving");
wait(&mut c, 500);
assert!(tooltip_shown(&c, 8));
}
#[test]
fn a_tooltip_whose_delay_never_ends_takes_no_part_in_the_grace_period() {
let clock = crate::time::Clock::manual(std::time::SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = toolbar_core(&[2, 8]);
give_tooltip(&mut c, 2, 4, "Move");
give_hint_tooltip(&mut c, 8, 10, crate::overlay::HINT_ENDLESS);
c.commit();
let mouse = EventPayload::Mouse(crate::MouseEvent::default());
let wait = |c: &mut Core<FakeEngine>, ms: u64| {
clock.advance_to(crate::time::now() + std::time::Duration::from_millis(ms));
c.run_component_tasks();
c.commit();
};
c.component_event(2, EventKind::MouseEnter, &mouse);
wait(&mut c, 500);
assert!(tooltip_shown(&c, 2));
// Moving on within the grace period: an endless delay still waits.
c.component_event(2, EventKind::MouseLeave, &mouse);
c.component_event(8, EventKind::MouseEnter, &mouse);
c.commit();
assert!(!tooltip_shown(&c, 8), "an endless delay never ends");
wait(&mut c, 1000);
assert!(!tooltip_shown(&c, 8));
}
/// An image node `id` showing `source` (and `placeholder`), in the root.
fn image_ops(id: NodeId, source: ImageSource, placeholder: Option<ImageSource>) -> Vec<Op> {
let mut ops = vec![
Op::Create {
id,
tag: Tag::Image,
},
Op::SetProp {
id,
prop: Prop::Source(Some(source)),
},
];
if placeholder.is_some() {
ops.push(Op::SetProp {
id,
prop: Prop::Image(ImageProp::Placeholder(placeholder)),
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
});
ops
}
fn asset(uri: &str, scales: &[f32]) -> ImageSource {
ImageSource {
uri: uri.into(),
size: Some(crate::geometry::size_pt(40.0, 30.0)),
scales: scales.iter().copied().collect(),
data: None,
}
}
/// The source and placeholder URIs of `id`'s last image item.
fn image_uris(batch: &MountBatch, id: NodeId) -> Option<(Option<String>, Option<String>)> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Image {
id: i,
source,
options,
..
} if *i == id => Some((
source.as_ref().map(|s| s.uri.to_string()),
options.placeholder.as_ref().map(|s| s.uri.to_string()),
)),
_ => None,
})
}
fn at_ratio<M: TextEngine>(c: &mut Core<M>, pixel_ratio: f32) {
c.set_environment(crate::element::Environment {
pixel_ratio,
..Default::default()
});
}
#[test]
fn image_scales_pick_the_smallest_at_least_the_ratio_else_the_largest() {
let set: ImageScales = [1.0, 2.0, 3.0].into_iter().collect();
let picks: Vec<_> = [1.0, 1.5, 2.0, 2.625, 3.0, 3.5]
.into_iter()
.map(|r| set.pick(r))
.collect();
assert_eq!(
picks,
[
Some(1.0),
Some(2.0),
Some(2.0),
Some(3.0),
Some(3.0),
Some(3.0)
]
);
let set = |values: [f32; 2]| values.into_iter().collect::<ImageScales>();
assert_eq!(set([1.0, 1.5]).pick(1.2), Some(1.5));
assert_eq!(set([2.0, 4.0]).pick(1.0), Some(2.0));
assert_eq!(ImageScales::NONE.pick(2.0), None);
assert_eq!(
IMAGE_SCALES
.into_iter()
.collect::<ImageScales>()
.iter()
.collect::<Vec<_>>(),
IMAGE_SCALES
);
}
#[test]
fn image_scales_name_the_variants_and_keep_the_1x_file() {
let a = asset("asset:/img/a.png", &[1.0, 1.5, 2.0, 3.0, 4.0]);
let uris: Vec<_> = [1.0, 1.5, 2.0, 3.0, 4.0]
.into_iter()
.map(|r| a.uri_for(r).to_string())
.collect();
assert_eq!(
uris,
[
"asset:/img/a.png",
"asset:/img/a@1.5x.png",
"asset:/img/a@2x.png",
"asset:/img/a@3x.png",
"asset:/img/a@4x.png"
]
);
// The 1x file is the URI itself, not a copy.
assert!(std::sync::Arc::ptr_eq(&a.uri_for(1.0), &a.uri));
assert_eq!(
&*asset("asset:/x.y/b", &[1.0, 2.0]).uri_for(2.0),
"asset:/x.y/b@2x"
);
assert_eq!(
&*asset("asset:/.hidden", &[1.0, 2.0]).uri_for(2.0),
"asset:/.hidden@2x"
);
assert_eq!(
&*asset("asset:/c.d.webp", &[3.0]).uri_for(1.0),
"asset:/c.d@3x.webp"
);
}
#[test]
fn image_scales_leave_remote_and_file_uris_alone() {
for uri in [
"https://x.org/a.png",
"http://x.org/a.png",
"/tmp/a.png",
"file:///a.png",
] {
let source = asset(uri, &[1.0, 2.0, 3.0]);
assert!(
std::sync::Arc::ptr_eq(&source.uri_for(3.0), &source.uri),
"{uri}"
);
}
}
/// A query or a fragment is no part of a bundled file's name: such an
/// asset URI loads as it is, at every ratio.
#[test]
fn image_scales_leave_uris_with_a_query_or_a_fragment_alone() {
for uri in [
"asset:/a.png?v=2",
"asset:/a.png#frame",
"asset:/dir?x=1/a.png",
"asset:/a#b.png",
] {
let source = asset(uri, &[1.0, 2.0, 3.0]);
for ratio in [1.0, 2.0, 3.0] {
assert!(
std::sync::Arc::ptr_eq(&source.uri_for(ratio), &source.uri),
"{uri} at {ratio}"
);
}
let mut c = core();
at_ratio(&mut c, 3.0);
apply(&mut c, image_ops(2, source, None));
let batch = c.commit().unwrap();
assert_eq!(image_uris(&batch, 2), Some((Some(uri.into()), None)));
}
}
#[test]
fn image_scales_drop_invalid_values() {
let set: ImageScales = [f32::NAN, -2.0, 0.0, 2.5, 5.0, f32::INFINITY, 2.0]
.into_iter()
.collect();
assert_eq!(set.iter().collect::<Vec<_>>(), [2.0]);
assert!(
[f32::NAN, -1.0]
.into_iter()
.collect::<ImageScales>()
.is_empty()
);
}
/// A JSON stand-in for JS values, for the host decoding.
struct J(serde_json::Value);
/// A JSON array as [`J`]'s list.
struct L(Vec<serde_json::Value>);
impl crate::js::host::HostList for L {
type Item = J;
fn len(&self) -> usize {
self.0.len()
}
fn item(&self, i: usize) -> Option<J> {
self.0.get(i).cloned().map(J)
}
}
impl crate::js::host::HostInput for J {
type List = L;
fn is_nullish(&self) -> bool {
self.0.is_null()
}
fn is_object(&self) -> bool {
self.0.is_object() || self.0.is_array()
}
fn as_bool(&self) -> Option<bool> {
self.0.as_bool()
}
fn as_number(&self) -> Option<f64> {
self.0.as_f64()
}
fn as_string(&self) -> Option<String> {
self.0.as_str().map(str::to_owned)
}
fn field(&self, key: &str) -> Option<J> {
self.0.get(key).cloned().map(J)
}
fn as_list(&self) -> Option<L> {
self.0.as_array().cloned().map(L)
}
fn entries(&self) -> Vec<(String, J)> {
Vec::new()
}
fn truthy(&self) -> bool {
!self.0.is_null()
}
}
/// The JS shapes, through the host decoding.
#[test]
fn image_scales_decode_from_js() {
use crate::js::host::{HostCx, HostValue};
let decode = |v: serde_json::Value| ImageSource::decode(&J(v), &mut HostCx::default());
let source = decode(serde_json::json!({
"url": "asset:/a.png", "size": { "width": 40, "height": 30 }, "scales": [1, 2, "3", -1, 2.5, 3]
}))
.unwrap();
assert_eq!(source.size, Some(crate::geometry::size_pt(40.0, 30.0)));
assert_eq!(source.scales.iter().collect::<Vec<_>>(), [1.0, 2.0, 3.0]);
let plain =
decode(serde_json::json!({ "url": "asset:/a.png", "size": { "width": 40, "height": 30 } }));
assert_eq!(plain.unwrap().scales, ImageScales::NONE);
assert_eq!(
decode(serde_json::json!("https://x.org/a.png"))
.unwrap()
.scales,
ImageScales::NONE
);
let odd = decode(serde_json::json!({ "url": "asset:/a.png", "scales": "2" })).unwrap();
assert!(odd.scales.is_empty());
// Only the first entries are read.
let long = decode(serde_json::json!({
"url": "asset:/a.png", "scales": [1, 1, 1, 1, 1, 1, 1, 1, 2]
}));
assert_eq!(long.unwrap().scales.iter().collect::<Vec<_>>(), [1.0]);
}
/// `captureKeys` decodes through the one backend decoder, parsing each
/// keystroke once with the platform's `mod`, which the host resolves from
/// its environment (outside one, the `HostValue` decoder uses non-Apple
/// conventions).
#[test]
fn capture_keys_decode_from_js() {
use crate::{
KeyCapture,
js::host::{HostCx, HostValue, decode_capture_keys},
keymap::Keystroke,
};
let decode = |value: serde_json::Value, apple: bool| {
decode_capture_keys(&J(value), &mut HostCx::default(), apple)
};
assert_eq!(
decode(serde_json::json!("none"), false),
Some(KeyCapture::None)
);
assert_eq!(
decode(serde_json::json!("all"), true),
Some(KeyCapture::All)
);
assert_eq!(
decode(serde_json::json!("text"), false),
Some(KeyCapture::Text)
);
assert_eq!(
decode(serde_json::json!(["mod+k", "shift+tab"]), true),
Some(KeyCapture::keys([
Keystroke::parse_with("mod+k", true).unwrap(),
Keystroke::parse_with("shift+tab", true).unwrap(),
]))
);
// `mod` is Control where conventions are not Apple's.
assert_eq!(
decode(serde_json::json!(["mod+k"]), false),
Some(KeyCapture::keys([
Keystroke::parse_with("mod+k", false).unwrap()
]))
);
// The standard decoder takes the convention from the engine's ambient
// environment; outside one (as here) it parses non-Apple `mod`.
assert_eq!(
KeyCapture::decode(&J(serde_json::json!(["mod+k"])), &mut HostCx::default()),
Some(KeyCapture::keys([
Keystroke::parse_with("mod+k", false).unwrap()
]))
);
// Nothing and unknown strings clear the rule; invalid keystrokes are
// reported and left out.
assert_eq!(decode(serde_json::Value::Null, false), None);
let mut cx = HostCx::default();
let decoded = decode_capture_keys(&J(serde_json::json!(["a", "not+a+key"])), &mut cx, false);
assert_eq!(
decoded,
Some(KeyCapture::keys([
Keystroke::parse_with("a", false).unwrap()
]))
);
assert!(cx.warnings.iter().any(|w| w.contains("captureKeys")));
}
#[test]
fn image_scales_mount_the_variant_for_the_pixel_ratio() {
for (ratio, file) in [
(1.0, "a.png"),
(2.0, "a@2x.png"),
(2.625, "a@3x.png"),
(3.0, "a@3x.png"),
] {
let mut c = core();
at_ratio(&mut c, ratio);
let mut ops = image_ops(
2,
asset("asset:/a.png", &[1.0, 2.0, 3.0]),
Some(asset("asset:/p.png", &[1.0, 2.0])),
);
ops.extend(image_ops(3, asset("asset:/a.png", &[1.0, 2.0, 3.0]), None));
ops.push(style_op(3, &[("alignSelf", StyleValue::Str("flex-start"))]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
let placeholder = if ratio > 1.0 { "p@2x.png" } else { "p.png" };
assert_eq!(
image_uris(&batch, 2),
Some((
Some(format!("asset:/{file}")),
Some(format!("asset:/{placeholder}"))
)),
"at {ratio}"
);
// The size in points does not depend on the variant: 40 × 30, its
// edges on the device pixels of the ratio.
let size = frame_of(&batch, 3).expect("frame").size;
let pixel = 1.0 / ratio;
assert!(
(size.width.0 - 40.0).abs() <= pixel && (size.height.0 - 30.0).abs() <= pixel,
"at {ratio}: {size:?}"
);
}
}
#[test]
fn rounding_lands_on_device_pixels() {
// At one pixel per point, Taffy's rounding to whole points.
for v in [0.0, 0.4, 0.5, 1.49, 120.6, -0.5] {
assert_eq!(super::round(v, 1.0), (v + 0.5).floor(), "{v}");
}
assert_eq!(super::ceil_to_pixel(Points(21.333_334), 1.0), Points(22.0));
// At 2.625: 21 points are 55.125 pixels, rounded up to 56.
let ratio = 2.625;
let up = super::ceil_to_pixel(Points(21.0), ratio);
assert!((up.0 * ratio - 56.0).abs() < 1.0e-3, "{up:?}");
// 56 pixels measured stay 56, whatever `f32` makes of `56 / 2.625`.
let measured = Points(56.0 / ratio);
let up = super::ceil_to_pixel(measured, ratio);
assert!((up.0 * ratio - 56.0).abs() < 1.0e-3, "{up:?}");
assert!((super::round(4.0, ratio) * ratio - 11.0).abs() < 1.0e-3);
// A box under a pixel thick whose edges round to one pixel takes the
// pixel on the side most of it is on (the later one on a tie); one of
// no length, or of a length zero but for `f32`, takes none.
assert_eq!(super::edges(199.5, 0.5, 1.0), (199.0, 200.0));
assert_eq!(super::edges(10.5, 0.4, 1.0), (10.0, 11.0));
assert_eq!(super::edges(99.75, 0.5, 1.0), (100.0, 101.0));
assert_eq!(super::edges(0.0, 0.5, 1.0), (0.0, 1.0));
assert_eq!(super::edges(199.5, 0.5, 2.0), (399.0, 400.0));
assert_eq!(super::edges(10.0, 0.0, 1.0), (10.0, 10.0));
assert_eq!(super::edges(10.0, 1.0e-5, 1.0), (10.0, 10.0));
// A width a hair over a whole pixel is not taken back under it: the
// text measured again in that width would no longer fit.
assert_eq!(super::ceil_to_pixel(Points(78.000_49), 1.0), Points(79.0));
assert_eq!(super::ceil_to_pixel(Points(78.000_49), 2.0), Points(78.5));
let up = super::ceil_to_pixel(Points(78.000_49), ratio);
assert!(
up.0 >= 78.000_49 && up.0 * ratio - (78.000_49 * ratio).ceil() < 1.0e-3,
"{up:?}"
);
}
/// One line `.0` points wide, as a platform engine measures a short label;
/// in a narrower width it takes two lines.
struct HairEngine(f32);
impl TextEngine for HairEngine {
type Prepared = ();
fn prepare(&self, _: &AttributedText) {}
fn measure(&self, _: &(), max_width: Option<Points>) -> Size<Points> {
match max_width {
Some(max) if max.0 < self.0 => size_pt(max.0, 32.0),
_ => size_pt(self.0, 16.0),
}
}
fn layout(&self, _: &(), _: Size<Points>) -> TextLayout {
TextLayout(Arc::new(()))
}
}
#[test]
fn text_a_hair_over_a_pixel_wide_keeps_its_line() {
// A label CoreText measures 78.00049 points wide, in a view as wide as
// its content. Rounded to 78 points, the text was measured again in 78
// and wrapped onto a second line.
for ratio in [1.0, 2.0, 2.625] {
let mut c = Core::new(HairEngine(78.000_49), size_pt(320.0, 480.0));
at_ratio(&mut c, ratio);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::CreateText {
id: 4,
text: "label".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
style_op(2, &[("alignSelf", StyleValue::Str("flex-start"))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let size = frame_of(&batch, 3).expect("frame").size;
assert_eq!(size.height.0, 16.0, "at {ratio}: {size:?}");
assert!(size.width.0 >= 78.000_49, "at {ratio}: {size:?}");
}
}
#[test]
fn padded_text_as_wide_as_its_content_keeps_its_line_at_fractional_ratios() {
// A bordered and padded label (a stamp on a tile), absolutely placed at
// a fractional offset: its border and padding were each rounded from
// the outer edge, so at 1.1 pixels per point they took a pixel more
// than the 8.25 pixels they are, and the 24 point text wrapped in the
// content box left.
for ratio in [1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.625, 0.9] {
for tenth in 0..10 {
let left = 160.0 + tenth as f32 / 10.0;
let mut c = Core::new(HairEngine(24.0), size_pt(320.0, 480.0));
at_ratio(&mut c, ratio);
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::CreateText {
id: 4,
text: "label".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
style_op(
3,
&[
("position", StyleValue::Str("absolute")),
("left", StyleValue::Number(left)),
("top", StyleValue::Number(6.0)),
("paddingHorizontal", StyleValue::Number(6.0)),
("paddingVertical", StyleValue::Number(1.0)),
("borderWidth", StyleValue::Number(1.5)),
],
),
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
let content = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 3, content, .. } => Some(*content),
_ => None,
})
.expect("text content");
// Whole pixels, but for the last bits of an `f32` (30 pixels
// at 1.25 come to 23.999998 points).
assert!(
content.size.width.0 >= 24.0 - 1.0e-3,
"at {ratio}, left {left}: {content:?}"
);
}
}
}
/// One line at `.0` points or wider, two in anything narrower; its layout
/// keeps the width it was typeset in.
struct BorderlineEngine(f32);
impl TextEngine for BorderlineEngine {
type Prepared = ();
fn prepare(&self, _: &AttributedText) {}
fn measure(&self, _: &(), max_width: Option<Points>) -> Size<Points> {
match max_width {
Some(max) if max.0 + 0.01 < self.0 => size_pt(max.0, 32.0),
_ => size_pt(self.0, 16.0),
}
}
fn layout(&self, _: &(), size: Size<Points>) -> TextLayout {
TextLayout(Arc::new(size.width.0))
}
}
#[test]
fn stretched_text_is_typeset_in_the_width_it_was_measured_in() {
// A paragraph stretched across a list item's content, 21 points in
// (57.75 pixels at 2.75): its box rounds to a pixel narrower than the
// 299 points Taffy measured it in. A last word that fit by less than
// that pixel wrapped onto a line the box had no height for, drawn over
// the item after it.
for ratio in [2.75, 3.5, 2.625, 1.1, 1.0] {
for inset in [21.0, 10.5, 14.3] {
let measured = 320.0 - inset;
let mut c = Core::new(BorderlineEngine(measured - 0.005), size_pt(320.0, 480.0));
at_ratio(&mut c, ratio);
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::CreateText {
id: 4,
text: "paragraph".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
style_op(2, &[("paddingLeft", StyleValue::Number(inset))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let (layout, content) = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text {
id: 3,
layout,
content,
..
} => Some((layout.clone(), *content)),
_ => None,
})
.expect("text layout");
let typeset = *layout.downcast::<f32>().expect("typeset width");
// Measured in one line.
assert!(
content.size.height.0 < 24.0,
"at {ratio}, inset {inset}: {content:?}"
);
assert!(
typeset + 0.01 >= measured - 0.005,
"at {ratio}, inset {inset}: typeset in {typeset}, measured in {measured}, box {content:?}"
);
// Never further than a pixel from its box.
assert!(
((typeset - content.size.width.0) * ratio).abs() < 1.0,
"at {ratio}, inset {inset}: typeset in {typeset}, box {content:?}"
);
}
}
}
#[test]
fn frames_stay_on_device_pixels_at_fractional_ratios() {
// A view 4 points down (10.5 pixels at 2.625) holding a child as tall as
// itself: rounded to whole points, the platform rounding each frame to
// pixels in its parent made the child 79 pixels in a 78 pixel parent.
let ratio = 2.625;
let mut c = core();
at_ratio(&mut c, ratio);
let mut ops = Vec::new();
for (id, parent) in [(2, ROOT_ID), (3, 2), (4, 3)] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
ops.push(style_op(2, &[("paddingTop", StyleValue::Number(4.0))]));
ops.push(style_op(3, &[("height", StyleValue::Number(30.0))]));
ops.push(style_op(4, &[("height", StyleValue::Number(30.0))]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
let pixels = |v: Points| v.0 * ratio;
let whole = |v: f32| (v - v.round()).abs() < 1.0e-3;
let outer = frame_of(&batch, 3).expect("outer frame");
let inner = frame_of(&batch, 4).expect("inner frame");
for v in [
outer.origin.y,
outer.size.height,
inner.origin.y,
inner.size.height,
] {
assert!(whole(pixels(v)), "{} pixels", pixels(v));
}
assert_eq!(
pixels(outer.size.height).round(),
pixels(inner.size.height).round()
);
}
#[test]
fn frames_moved_by_whole_pixels_are_not_sent_again() {
// Rows of 28 points at 2.625 (73.5 pixels, every other edge on a half
// pixel) in a box a scroll moves by one pixel at a time, as DataTable's
// body moves: the rows keep their pixels, so only the box's frame is
// sent, never the rows' again with another last bit or the other pixel.
let ratio = 2.625;
let mut c = core();
at_ratio(&mut c, ratio);
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for id in 3..43 {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
ops.push(style_op(id, &[("height", StyleValue::Number(28.0))]));
}
apply(&mut c, ops);
c.commit().unwrap();
for pixel in 1..400 {
let top = (f64::from(pixel) / f64::from(ratio)) as f32;
apply(
&mut c,
vec![style_op(2, &[("marginTop", StyleValue::Number(top))])],
);
let batch = c.commit().unwrap();
let rows = batch
.items
.iter()
.filter(|i| matches!(i, MountItem::Frame { id, .. } if *id != 2))
.count();
assert_eq!(rows, 0, "{pixel} pixels down: {:?}", batch.items);
}
}
/// Half point rules at `ratio`: a column 200 wide holding a block 10.5
/// tall (4), a horizontal rule 0.5 tall (5) and a block below (6), and a
/// vertical rule 0.5 wide pinned to its right edge from 40 down (7), around
/// a child as wide as itself (8).
fn half_point_rules(ratio: f32) -> MountBatch {
let mut c = core();
at_ratio(&mut c, ratio);
let mut ops = Vec::new();
for (id, parent) in [(3, ROOT_ID), (4, 3), (5, 3), (6, 3), (7, 3), (8, 7)] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
ops.push(style_op(
3,
&[
("position", StyleValue::Str("relative")),
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(300.0)),
],
));
ops.push(style_op(4, &[("height", StyleValue::Number(10.5))]));
ops.push(style_op(5, &[("height", StyleValue::Number(0.5))]));
ops.push(style_op(6, &[("height", StyleValue::Number(10.0))]));
ops.push(style_op(
7,
&[
("position", StyleValue::Str("absolute")),
("top", StyleValue::Number(40.0)),
("bottom", StyleValue::Number(0.0)),
("right", StyleValue::Number(0.0)),
("width", StyleValue::Number(0.5)),
],
));
ops.push(style_op(8, &[("height", StyleValue::Number(10.0))]));
apply(&mut c, ops);
c.commit().unwrap()
}
#[test]
fn half_point_rules_keep_a_device_pixel_and_their_neighbours_meet() {
// One pixel per point (a 100% display, the headless default): the
// rules' edges both round to one pixel, and the rules took none.
let batch = half_point_rules(1.0);
let frame = |id| frame_of(&batch, id).expect("frame");
let (above, rule, below) = (frame(4), frame(5), frame(6));
assert_eq!(rule.size.height, Points(1.0), "{rule:?}");
// Its pixel is the one most of it is on, inside the column: the block
// above keeps its rounded edge and the block below starts on it, with
// no gap, as without the rule.
assert_eq!(rule.origin.y, Points(10.0));
assert_eq!(above.origin.y + above.size.height, Points(11.0));
assert_eq!(below.origin.y, Points(11.0));
let pinned = frame(7);
assert_eq!(pinned.size.width, Points(1.0), "{pinned:?}");
assert_eq!(pinned.origin.x + pinned.size.width, Points(200.0));
assert_eq!(pinned.size.height, Points(260.0));
// A child as wide as the rule is on the rule's pixel, not moved again.
assert_eq!(frame(8), rect(0.0, 0.0, 1.0, 10.0));
// Two pixels per point: half a point is a pixel, kept as it is.
let batch = half_point_rules(2.0);
let frame = |id| frame_of(&batch, id).expect("frame");
assert_eq!(frame(5), rect(0.0, 10.5, 200.0, 0.5));
assert_eq!(frame(6).origin.y, Points(11.0));
assert_eq!(frame(7), rect(199.5, 40.0, 0.5, 260.0));
assert_eq!(frame(8), rect(0.0, 0.0, 0.5, 10.0));
}
#[test]
fn a_rule_that_grows_a_pixel_thick_moves_its_child_back_onto_it() {
// A rule 0.5 tall 10.5 down at one pixel per point is on the pixel
// before, and its child of its height with it. Grown to a point, it is
// on its own pixels: its child, laid out as before, is a pixel above
// it, as it is in the layout, though nothing moved it.
let mut c = core();
let mut ops = Vec::new();
for (id, parent) in [(3, ROOT_ID), (4, 3), (5, 3), (6, 5)] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
ops.push(style_op(4, &[("height", StyleValue::Number(10.5))]));
ops.push(style_op(5, &[("height", StyleValue::Number(0.5))]));
ops.push(style_op(6, &[("height", StyleValue::Number(0.5))]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 5), Some(rect(0.0, 10.0, 320.0, 1.0)));
assert_eq!(frame_of(&batch, 6), Some(rect(0.0, 0.0, 320.0, 1.0)));
apply(
&mut c,
vec![style_op(5, &[("height", StyleValue::Number(1.0))])],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 5), Some(rect(0.0, 11.0, 320.0, 1.0)));
assert_eq!(frame_of(&batch, 6), Some(rect(0.0, -1.0, 320.0, 1.0)));
}
#[test]
fn image_scales_change_nothing_without_scales() {
let mut c = core();
at_ratio(&mut c, 3.0);
let plain = asset("asset:/a.png", &[]);
apply(
&mut c,
image_ops(2, plain.clone(), Some(asset("asset:/a@3x.png", &[]))),
);
let batch = c.commit().unwrap();
let source = batch.items.iter().find_map(|i| match i {
MountItem::Image { id: 2, source, .. } => source.clone(),
_ => None,
});
assert_eq!(source, Some(plain));
assert_eq!(
image_uris(&batch, 2),
Some((Some("asset:/a.png".into()), Some("asset:/a@3x.png".into())))
);
// A ratio change sends nothing for them.
at_ratio(&mut c, 2.0);
let batch = c.commit();
assert!(
batch.is_none_or(|b| !b.items.iter().any(|i| matches!(i, MountItem::Image { .. }))),
"nothing for images without scales"
);
}
/// Rust components: an `asset!` image with variants (`ImageAsset::scales`)
/// is picked as an imported one.
mod asset_variants {
use super::*;
use crate::{element::ImageAsset, prelude::*};
const FLAG: ImageAsset = ImageAsset {
url: "asset:/@demo/flag.png",
size: crate::geometry::size_pt(17.0, 12.0),
scales: &[1.0, 2.0, 3.0],
};
const PLAIN: ImageAsset = ImageAsset {
url: "asset:/@demo/plain.png",
size: crate::geometry::size_pt(10.0, 10.0),
scales: &[],
};
#[component]
fn Flags() -> impl IntoElement {
view()
.child(image(FLAG))
.child(image(PLAIN).placeholder(FLAG))
}
/// The image items' source and placeholder URIs, in mount order.
fn shown(pixel_ratio: f32) -> Vec<(Option<String>, Option<String>)> {
let mut c = core();
at_ratio(&mut c, pixel_ratio);
c.mount_root(&crate::element::Root::new::<Flags>(|| ()));
let batch = c.commit().unwrap();
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Image { id, .. } => image_uris(&batch, *id),
_ => None,
})
.collect()
}
fn some(uri: &str) -> Option<String> {
Some(uri.to_owned())
}
#[test]
fn asset_variants_pick_for_the_pixel_ratio() {
assert_eq!(
shown(3.0),
[
(some("asset:/@demo/flag@3x.png"), None),
(
some("asset:/@demo/plain.png"),
some("asset:/@demo/flag@3x.png")
)
]
);
assert_eq!(
shown(2.0),
[
(some("asset:/@demo/flag@2x.png"), None),
(
some("asset:/@demo/plain.png"),
some("asset:/@demo/flag@2x.png")
)
]
);
}
#[test]
fn asset_variants_none_keep_the_file() {
assert_eq!(
shown(1.0),
[
(some("asset:/@demo/flag.png"), None),
(
some("asset:/@demo/plain.png"),
some("asset:/@demo/flag.png")
)
]
);
let src: crate::element::ImageSrc = PLAIN.into();
assert!(src.scales.is_empty());
let src: crate::element::ImageSrc = FLAG.into();
assert_eq!(src.scales.iter().collect::<Vec<_>>(), [1.0, 2.0, 3.0]);
assert_eq!(src.size, Some((17.0, 12.0)));
}
}
mod rust_lazy_context {
use super::*;
use crate::{element::Root, prelude::*};
#[derive(Clone, PartialEq, Props)]
struct ProviderProps {
#[prop(lazy)]
children: Children,
}
#[component]
fn Provider(props: ProviderProps) -> impl IntoElement {
provide_context("provided");
let open = signal(false);
view()
.on_press(move || open.set(true))
.child(when(open, move || props.children))
}
#[component]
fn Consumer() -> impl IntoElement {
text(use_context::<&'static str>().unwrap_or("missing"))
}
#[component]
fn App() -> impl IntoElement {
provider().child(consumer())
}
#[derive(Clone, PartialEq, Props)]
struct GroupProps {
children: Children,
}
/// A provider whose children are not lazy: placed at once.
#[component]
fn Group(props: GroupProps) -> impl IntoElement {
provide_context("grouped");
view().child(props.children)
}
#[component]
fn GroupApp() -> impl IntoElement {
view().child(group().child(consumer()).child(consumer()))
}
#[test]
fn rust_children_of_a_nested_component_read_its_context() {
// The consumers are made by `GroupApp`'s view but placed by
// `Group`'s: they wait for it, and read what it provides.
let mut c = core();
c.mount_root(&Root::of::<GroupApp>());
let batch = c.commit().unwrap();
let texts: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, ["grouped", "grouped"]);
}
#[test]
fn rust_lazy_children_inherit_the_context_where_they_are_placed() {
let mut c = core();
c.mount_root(&Root::of::<App>());
let batch = c.commit().unwrap();
let trigger = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.unwrap();
c.component_event(trigger, EventKind::Press, &EventPayload::None);
let batch = c.commit().unwrap();
let texts: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.as_str()),
_ => None,
})
.collect();
assert_eq!(texts, ["provided"]);
}
}
/// What a component places in a slot of its own reads the context of the
/// component that places it, as its children and TSX's slot content do,
/// and so the context of what is above that one (its placing component's,
/// and the app's own around them).
mod rust_slot_context {
use super::*;
use crate::{
element::{Registry, Root, Slot},
prelude::*,
};
/// What a menu gives what it places: their size.
#[derive(Clone)]
struct MenuSize(&'static str);
/// What a frame gives what is in it, however deep.
#[derive(Clone)]
struct FrameTone(&'static str);
/// What the app's own component gives what its view makes.
#[derive(Clone)]
struct AppMark(&'static str);
#[derive(Clone, PartialEq, Props)]
struct FrameProps {
children: Children,
}
#[component]
fn Frame(props: FrameProps) -> impl IntoElement {
provide_context(FrameTone("frame"));
view().child(props.children)
}
#[derive(Clone, PartialEq, Props)]
struct MenuProps {
children: Children,
}
/// Provides its size and places its items.
#[component]
fn Menu(props: MenuProps) -> impl IntoElement {
provide_context(MenuSize("sm"));
view().child(props.children)
}
#[derive(Clone, PartialEq, Props)]
struct SubMenuProps {
trigger: crate::element::Prop<Option<Slot>>,
children: Children,
}
/// An item of a menu: places its trigger, then its own items.
#[component]
fn SubMenu(props: SubMenuProps) -> impl IntoElement {
view()
.child(props.trigger.place(|t| t))
.child(props.children)
}
#[derive(Clone, PartialEq, Props)]
struct LazySubMenuProps {
trigger: crate::element::Prop<Option<Slot>>,
}
/// Places its trigger once pressed.
#[component]
fn LazySubMenu(props: LazySubMenuProps) -> impl IntoElement {
let open = signal(false);
let trigger = props.trigger;
view()
.on_press(move || open.set(true))
.child(when(open, move || trigger.place(|t| t)))
}
/// Shows what it reads: the size, the tone and the app's mark.
#[component]
fn Label() -> impl IntoElement {
let size = use_context::<MenuSize>().map_or("none", |s| s.0);
let tone = use_context::<FrameTone>().map_or("none", |t| t.0);
let app = use_context::<AppMark>().map_or("none", |a| a.0);
text(format!("{size} {tone} {app}"))
}
/// The tree [`js_slot_content_reads_the_same_contexts`] mounts from JS.
#[component]
fn PlainApp() -> impl IntoElement {
frame().child(menu().child(label()).child(sub_menu().trigger(label())))
}
/// Provides a size of its own too: the menu's is nearer to what it
/// places.
#[component]
fn MarkedApp() -> impl IntoElement {
provide_context(AppMark("app"));
provide_context(MenuSize("app"));
frame().child(
menu()
.child(label())
.child(sub_menu().trigger(label()).child(label())),
)
}
#[component]
fn LazyApp() -> impl IntoElement {
provide_context(AppMark("app"));
menu().child(lazy_sub_menu().trigger(label()))
}
fn sorted(mut texts: Vec<String>) -> Vec<String> {
texts.sort();
texts
}
#[test]
fn rust_slot_content_reads_the_context_where_it_is_placed() {
// The sub-menu's trigger is made by the app's view but placed by
// the sub-menu's, in the menu's items, in the frame: it reads the
// menu's size over the app's, the frame's tone and the app's mark,
// as the items (the menu's children) do.
let mut c = core();
c.mount_root(&Root::of::<MarkedApp>());
let batch = c.commit().unwrap();
assert_eq!(texts_of(&batch), ["sm frame app"; 3]);
}
#[test]
fn rust_slot_content_placed_later_reads_the_context_where_it_is_placed() {
let mut c = core();
c.mount_root(&Root::of::<LazyApp>());
let batch = c.commit().unwrap();
assert!(texts_of(&batch).is_empty(), "{:?}", texts_of(&batch));
let sub = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.expect("the sub-menu");
c.component_event(sub, EventKind::Press, &EventPayload::None);
let batch = c.commit().unwrap();
assert_eq!(texts_of(&batch), ["sm none app"]);
}
#[test]
fn js_slot_content_reads_the_same_contexts() {
let mut rust = core();
rust.mount_root(&Root::of::<PlainApp>());
let from_rust = sorted(texts_of(&rust.commit().unwrap()));
assert_eq!(from_rust, ["sm frame none"; 2]);
// The same tree in TSX: `<Frame><Menu><Label /><SubMenu
// trigger={<Label />} /></Menu></Frame>`.
let mut c = core();
let mut registry = Registry::new();
registry.register::<Frame>();
registry.register::<Menu>();
registry.register::<SubMenu>();
registry.register::<Label>();
c.set_components(registry);
let host = |id: NodeId, name: &str| {
[
Op::Create { id, tag: Tag::View },
Op::SetProp {
id,
prop: crate::Prop::Component(name.into()),
},
]
};
let insert = |parent: NodeId, child: NodeId| Op::Insert {
parent,
child,
before: None,
};
let mut ops = Vec::new();
ops.extend(host(2, std::any::type_name::<Frame>()));
ops.extend(host(4, std::any::type_name::<Menu>()));
ops.extend(host(6, std::any::type_name::<Label>()));
ops.extend(host(8, std::any::type_name::<SubMenu>()));
ops.extend([
Op::Create {
id: 10,
tag: Tag::View,
},
Op::SetProp {
id: 10,
prop: crate::Prop::ComponentSlot("trigger".into()),
},
]);
ops.extend(host(12, std::any::type_name::<Label>()));
ops.extend([
insert(10, 12),
insert(8, 10),
insert(4, 6),
insert(4, 8),
insert(2, 4),
insert(ROOT_ID, 2),
]);
apply(&mut c, ops);
let from_js = sorted(texts_of(&c.commit().unwrap()));
assert_eq!(from_js, from_rust);
}
}
/// The tokens' `font-sans` is the font text is drawn with unless it sets
/// its own, as a page's `--font-sans` is in Tailwind; a new one lays the
/// text out again.
#[test]
fn text_takes_the_tokens_sans_font() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "hello".into(),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let text = text_item(&c.commit().unwrap()).unwrap();
assert_eq!(text.spans[0].style.font_family, None);
let mut tokens = crate::element::tokens::sample();
tokens.set_font(crate::element::FONT_SANS, "Inter");
c.set_tokens(tokens);
let text = text_item(&c.commit().unwrap()).unwrap();
assert_eq!(
text.spans[0].style.font_family,
Some(crate::style::FontFamily::new("Inter"))
);
}
/// A page: scroll view 2 (400 tall) holding a header (view 3, `header`
/// tall) and, for each of `lists`, a list in its parent's viewport (ids 4,
/// 5, …) of that many rows estimated at 50, then a footer (view 9, 10
/// tall).
fn page(c: &mut Core<FakeEngine>, header: f32, lists: &[u32]) {
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("height", StyleValue::Number(header))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
];
for (i, &count) in lists.iter().enumerate() {
let id = 4 + i as u32;
ops.extend([
Op::Create { id, tag: Tag::List },
Op::SetProp {
id,
prop: Prop::ListViewport(crate::ListViewport::Parent),
},
Op::SetProp {
id,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id,
prop: Prop::Count(count),
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
ops.extend([
Op::Create {
id: 9,
tag: Tag::View,
},
style_op(9, &[("height", StyleValue::Number(10.0))]),
Op::Insert {
parent: 2,
child: 9,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
]);
apply(c, ops);
}
/// The items list `id` has bound, in order.
fn bound_items(c: &Core<FakeEngine>, id: NodeId) -> Vec<u32> {
let list = c.nodes[c.key(id).unwrap() as usize].list.as_ref().unwrap();
let mut items: Vec<u32> = list.slots.iter().filter_map(|s| s.index).collect();
items.sort_unstable();
items
}
fn scroll_content(batch: &MountBatch, id: NodeId) -> Option<f32> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollContent { id: i, size } if *i == id => Some(size.height.0),
_ => None,
})
}
/// A list in its parent's viewport is a plain view: its props tell the
/// platforms to read its recycled cells in screen order, along its axis.
/// A list of its own is a scroll view, read so already.
#[test]
fn a_list_in_its_parents_viewport_is_read_in_screen_order() {
let screen_order = |batch: &MountBatch, id: NodeId| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewProps { id: i, props } if *i == id => Some(props.screen_order),
_ => None,
})
};
let mut c = core();
page(&mut c, 100.0, &[100]);
apply(
&mut c,
vec![
Op::Create {
id: 20,
tag: Tag::List,
},
Op::SetProp {
id: 20,
prop: Prop::Count(10),
},
Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(
screen_order(&batch, 4),
Some(Some(crate::geometry::Axis::Vertical))
);
assert_eq!(screen_order(&batch, 20).flatten(), None);
// A horizontal one is read along its axis.
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::Horizontal(true),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
screen_order(&batch, 4),
Some(Some(crate::geometry::Axis::Horizontal))
);
}
#[test]
fn a_list_below_a_header_renders_the_rows_in_the_pages_viewport() {
let mut c = core();
page(&mut c, 100.0, &[100]);
let batch = c.commit().unwrap();
// A plain view that clips its cells, at its full length in the page:
// the page's content covers it, in the same batch.
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Create {
id: 4,
kind: ViewKind::View
}
)));
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::ScrollConfig { id: 4, .. } | MountItem::ScrollContent { id: 4, .. }
)));
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::ViewStyle { id: 4, style } if style.overflow_hidden
)));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 100.0, 320.0, 5000.0)));
assert_eq!(frame_of(&batch, 9), Some(rect(0.0, 5100.0, 320.0, 10.0)));
assert_eq!(scroll_content(&batch, 2), Some(5110.0));
// The rows from the list's start to the viewport's end and a screen
// more: 0 to 700 of the list.
assert_eq!(bound_items(&c, 4), (0..=14).collect::<Vec<_>>());
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, cells[3]),
Some(rect(0.0, 150.0, 320.0, 50.0))
);
// The page scrolls: the list's rows follow, 1900 into it.
c.set_scroll_offset(2, point(px(0.0), px(2000.0)), 0);
c.commit();
assert_eq!(bound_items(&c, 4), (30..=54).collect::<Vec<_>>());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
let batch = c.commit().unwrap();
let cell = cells[bound_slot(&c, 4, 40) as usize];
assert_eq!(frame_of(&batch, cell), Some(rect(0.0, 2000.0, 320.0, 50.0)));
}
#[test]
fn a_page_lists_spare_cells_are_hidden_when_its_rows_change() {
let mut c = core();
page(&mut c, 100.0, &[100]);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
let mut batches = Vec::new();
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
batches.extend(c.commit());
// Far down the page, then other rows and back to the top, as an app
// switching what the page shows does.
c.set_scroll_offset(2, point(px(0.0), px(4000.0)), 0);
batches.extend(c.commit());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
batches.extend(c.commit());
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::Count(20),
}],
);
c.set_scroll_offset(2, point(px(0.0), px(0.0)), 0);
batches.extend(c.commit());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
batches.extend(c.commit());
// Every cell without a row is hidden, every cell with one shows.
let list = c.nodes[c.key(4).unwrap() as usize].list.as_ref().unwrap();
let mut spare = 0;
for (slot, &cell) in cells.iter().enumerate() {
let (mut style, mut props) = (false, false);
for batch in &batches {
let (s, p) = hidden_in(batch, cell);
style = s.unwrap_or(style);
props = p.unwrap_or(props);
}
let unbound = list.slots[slot].index.is_none();
spare += unbound as u32;
assert_eq!((style, props), (unbound, unbound), "cell {cell}");
}
assert!(spare > 0);
}
/// The slot list `id` bound item `index` to.
fn bound_slot(c: &Core<FakeEngine>, id: NodeId, index: u32) -> u32 {
let list = c.nodes[c.key(id).unwrap() as usize].list.as_ref().unwrap();
list.slots
.iter()
.position(|s| s.index == Some(index))
.unwrap() as u32
}
#[test]
fn lists_in_one_page_scroll_with_it() {
let mut c = core();
// 20 rows (1000) then 100 rows, below no header.
page(&mut c, 0.0, &[20, 100]);
c.commit();
assert_eq!(bound_items(&c, 4), (0..=16).collect::<Vec<_>>());
// The second starts at 1000, below the viewport and its overscan.
assert!(bound_items(&c, 5).is_empty());
let key = c.key(2).unwrap();
assert_eq!(
c.nodes[key as usize]
.scroll
.as_ref()
.unwrap()
.dependents
.len(),
2
);
// Scrolled 1500: the first list is past, the second 500 into its rows.
c.set_scroll_offset(2, point(px(0.0), px(1500.0)), 0);
c.commit();
assert!(bound_items(&c, 4).is_empty());
assert_eq!(bound_items(&c, 5), (2..=26).collect::<Vec<_>>());
}
#[test]
fn a_list_far_below_the_viewport_renders_nothing() {
let mut c = core();
page(&mut c, 2000.0, &[100]);
c.commit();
assert!(bound_items(&c, 4).is_empty());
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
assert!(binds.is_empty());
c.set_scroll_offset(2, point(px(0.0), px(1700.0)), 0);
c.commit();
assert_eq!(bound_items(&c, 4), (0..=10).collect::<Vec<_>>());
}
#[test]
fn a_page_list_loads_more_as_its_end_nears() {
let mut c = core();
page(&mut c, 1000.0, &[20]);
c.commit();
let load_more = |c: &mut Core<FakeEngine>| {
js_events(c)
.iter()
.any(|e| e.0 == 4 && e.1 == EventKind::LoadMore)
};
assert!(!load_more(&mut c));
c.set_scroll_offset(2, point(px(0.0), px(1100.0)), 0);
c.commit();
assert!(!load_more(&mut c));
// Its end 600 below the viewport's end, within a viewport.
c.set_scroll_offset(2, point(px(0.0), px(1300.0)), 0);
c.commit();
assert!(load_more(&mut c));
}
/// The scrolls of page 2 in `batch`: `ScrollBy` deltas and `ScrollTo`
/// offsets, in order.
fn page_scrolls(batch: &MountBatch) -> Vec<(bool, f32)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ScrollBy { id: 2, dy, .. } => Some((false, dy.0)),
MountItem::Command {
id: 2,
command: Command::ScrollTo { y, .. },
} => Some((true, y.0)),
_ => None,
})
.collect()
}
#[test]
fn a_page_moves_only_for_rows_wholly_above_its_viewport() {
let mut c = core();
page(&mut c, 100.0, &[100]);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
// The list's start shows: rows taller than estimated push what is
// below them down, and the page stays.
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
let batch = c.commit().unwrap();
assert!(page_scrolls(&batch).is_empty());
// (Laid out far below the viewport: no view there yet.)
assert_eq!(
c.measure(9).map(|m| m.frame),
Some(rect(0.0, 100.0 + 15.0 * 80.0 + 85.0 * 50.0, 320.0, 10.0))
);
// Far down, then back up over rows not measured yet: those wholly
// above the viewport's top keep the visible rows in place.
c.set_scroll_offset(2, point(px(0.0), px(3000.0)), 0);
c.commit();
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
c.set_scroll_offset(2, point(px(0.0), px(2200.0)), 0);
c.commit();
render_binds(&mut c, &mut next_id, &mut cells, 80.0);
let batch = c.commit().unwrap();
let scrolls = page_scrolls(&batch);
assert_eq!(scrolls.len(), 1, "one ScrollBy per commit: {scrolls:?}");
let (to, by) = scrolls[0];
assert!(!to && by > 0.0, "{scrolls:?}");
// The page's content grew first.
let grow = batch
.items
.iter()
.position(|i| matches!(i, MountItem::ScrollContent { id: 2, .. }))
.unwrap();
let scroll = batch
.items
.iter()
.position(|i| matches!(i, MountItem::ScrollBy { id: 2, .. }))
.unwrap();
assert!(grow < scroll);
// The window already moved with it: a stale report (before the
// platform applied the scroll) does not move it back.
let list = c.nodes[c.key(4).unwrap() as usize].list.as_ref().unwrap();
let local = list.offset;
c.set_scroll_offset(2, point(px(0.0), px(2200.0)), 0);
c.commit();
let list = c.nodes[c.key(4).unwrap() as usize].list.as_ref().unwrap();
assert_eq!(list.offset, local);
// Applied, it reports where it is.
c.set_scroll_offset(2, point(px(0.0), px(2200.0 + by)), 1);
c.commit();
let list = c.nodes[c.key(4).unwrap() as usize].list.as_ref().unwrap();
assert_eq!(list.offset, local);
}
#[test]
fn scroll_to_index_in_a_page_scrolls_the_page_within_its_content() {
let mut c = core();
page(&mut c, 100.0, &[100]);
c.commit();
c.apply(Op::Command {
id: 4,
command: Command::ScrollToIndex {
index: 10,
animated: false,
view_position: crate::geometry::Percentage(0.0),
view_offset: px(0.0),
},
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(page_scrolls(&batch), [(true, 600.0)]);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Command { id: 4, .. }))
);
// The window followed in the same commit.
assert_eq!(bound_items(&c, 4).first(), Some(&2));
// The last row: as far as the page scrolls (5110 - 400).
c.apply(Op::Command {
id: 4,
command: Command::ScrollToIndex {
index: 99,
animated: false,
view_position: crate::geometry::Percentage(0.0),
view_offset: px(0.0),
},
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(page_scrolls(&batch), [(true, 4710.0)]);
// The list's end at the viewport's end.
c.apply(Op::Command {
id: 4,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(page_scrolls(&batch), [(true, 4700.0)]);
}
/// A list in its parent's viewport scrolls with the plain scroll view
/// around it. Measurement counts the instant scroll the list asked for in
/// the batch, before the platform's report of it comes back.
#[test]
fn measuring_a_page_list_row_follows_the_pages_instant_scroll() {
let mut c = core();
page(&mut c, 100.0, &[100]);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
let row = cell_showing(&c, 4, 10);
assert_eq!(c.measure(row).unwrap().page.y.0, 600.0);
c.apply(Op::Command {
id: row,
command: Command::Measure { call: 9 },
})
.unwrap();
c.apply(Op::Command {
id: 4,
command: Command::ScrollToIndex {
index: 10,
animated: false,
view_position: crate::geometry::Percentage(0.0),
view_offset: px(0.0),
},
})
.unwrap();
let batch = c.commit().expect("the scroll");
assert_eq!(page_scrolls(&batch), [(true, 600.0)]);
assert_eq!(c.measure(row).unwrap().page.y.0, 0.0);
let answered = js_events(&mut c)
.into_iter()
.find_map(|(_, _, payload)| match payload {
EventPayload::Native { name, data } if &*name == "$return" && data["c"] == 9 => {
Some(data["v"].clone())
}
_ => None,
})
.expect("the measure answer");
assert_eq!(
answered["pagePosition"]["y"],
serde_json::json!(0.0),
"ref.measure() answers with the batch's coordinates"
);
// A report made before the scroll reaches the core after it: the
// instant `ScrollTo` it does not count still applies.
c.set_scroll_offset(2, point(px(0.0), px(0.0)), 0);
c.commit();
assert_eq!(c.measure(row).unwrap().page.y.0, 0.0);
c.set_scroll_offset(2, point(px(0.0), px(600.0)), u32::MAX);
c.commit();
assert_eq!(c.measure(row).unwrap().page.y.0, 0.0);
}
#[test]
fn the_viewport_is_fixed_when_the_list_is_made() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::List,
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
// In the batch that makes it: it counts.
Op::SetProp {
id: 4,
prop: Prop::ListViewport(crate::ListViewport::Parent),
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Create {
id: 4,
kind: ViewKind::View
}
)));
// Later: ignored.
c.apply(Op::SetProp {
id: 4,
prop: Prop::ListViewport(crate::ListViewport::Own),
})
.unwrap();
let list = c.nodes[c.key(4).unwrap() as usize].list.as_ref().unwrap();
assert!(list.parent);
assert_ne!(list.warned & list::ignored::VIEWPORT, 0);
assert!(c.commit().is_none());
}
#[test]
fn own_lists_have_no_spacer_and_scroll_themselves() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::Create {
id: 4,
tag: Tag::List,
},
Op::SetProp {
id: 4,
prop: Prop::Count(100),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Create {
id: 4,
kind: ViewKind::Scroll
}
)));
// No height of its own in a scroll view: nothing to show.
assert_eq!(frame_of(&batch, 4).map(|f| f.size.height.0), Some(0.0));
assert!(c.parent_lists.is_empty());
let key = c.key(4).unwrap();
let layout = c.nodes[key as usize].layout.unwrap();
assert!(c.layout.children(layout).is_empty());
let key = c.key(2).unwrap();
assert!(
c.nodes[key as usize]
.scroll
.as_ref()
.unwrap()
.dependents
.is_empty()
);
}
#[test]
fn a_page_lists_padding_and_border_place_its_cells() {
let mut c = core();
page(&mut c, 0.0, &[3]);
c.apply(style_op(
4,
&[
("paddingTop", StyleValue::Number(20.0)),
("paddingLeft", StyleValue::Number(16.0)),
("paddingRight", StyleValue::Number(16.0)),
("paddingBottom", StyleValue::Number(30.0)),
],
))
.unwrap();
let batch = c.commit().unwrap();
// Its padding around the rows, as in a browser.
assert_eq!(frame_of(&batch, 9).map(|f| f.origin.y.0), Some(200.0));
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, cells[1]),
Some(rect(16.0, 70.0, 288.0, 50.0))
);
}
#[test]
fn a_page_list_with_no_scroll_view_around_it_renders_for_the_screen() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 4,
tag: Tag::List,
},
Op::SetProp {
id: 4,
prop: Prop::ListViewport(crate::ListViewport::Parent),
},
Op::SetProp {
id: 4,
prop: Prop::Count(100),
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
c.commit();
// The screen (480 tall) and a screen more.
assert_eq!(bound_items(&c, 4), (0..=19).collect::<Vec<_>>());
}
#[test]
fn a_page_list_in_a_cell_of_a_list_follows_that_list() {
let mut c = core();
// An outer list of its own (400 tall) with one row: a list in its
// parent's viewport, below a 100 pt header in the row.
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::Count(1),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
assert_eq!(binds[0].binds, [(0, 0)]);
apply(
&mut c,
vec![
Op::Create {
id: 50,
tag: Tag::Cell,
},
Op::SetProp {
id: 50,
prop: Prop::Slot(CellSlot::Item(0)),
},
Op::Insert {
parent: 2,
child: 50,
before: None,
},
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: 50,
child: 3,
before: None,
},
Op::Create {
id: 4,
tag: Tag::List,
},
Op::SetProp {
id: 4,
prop: Prop::ListViewport(crate::ListViewport::Parent),
},
Op::SetProp {
id: 4,
prop: Prop::Count(100),
},
Op::Insert {
parent: 50,
child: 4,
before: None,
},
Op::SetProp {
id: 50,
prop: Prop::CellIndex(0),
},
],
);
let batch = c.commit().unwrap();
// The outer row is as tall as the header and the list.
assert_eq!(scroll_content(&batch, 2), Some(5100.0));
assert_eq!(bound_items(&c, 4), (0..=14).collect::<Vec<_>>());
let key = c.key(2).unwrap();
assert_eq!(
c.nodes[key as usize]
.scroll
.as_ref()
.unwrap()
.dependents
.len(),
1
);
// The outer list scrolls 2100: 2000 into the inner one.
c.set_scroll_offset(2, point(px(0.0), px(2100.0)), u32::MAX);
c.commit();
assert_eq!(bound_items(&c, 4), (32..=56).collect::<Vec<_>>());
// Released, the outer list leaves the inner one without a view.
c.apply(Op::Remove {
parent: ROOT_ID,
child: 2,
})
.unwrap();
c.apply(Op::Release { id: 2 }).unwrap();
c.commit();
let key = c.key(4).unwrap();
assert_eq!(c.nodes[key as usize].list.as_ref().unwrap().outer, None);
}
#[test]
fn a_page_list_keeps_its_scroll_commands_until_it_is_placed() {
let mut c = core();
page(&mut c, 100.0, &[100]);
c.commit();
// Out of the page: no view to scroll yet.
c.apply(Op::Remove {
parent: 2,
child: 4,
})
.unwrap();
c.apply(Op::Command {
id: 4,
command: Command::ScrollToIndex {
index: 10,
animated: false,
view_position: crate::geometry::Percentage(0.0),
view_offset: px(0.0),
},
})
.unwrap();
let batch = c.commit().unwrap();
assert!(page_scrolls(&batch).is_empty());
// Back in the page: the page scrolls to the row.
c.apply(Op::Insert {
parent: 2,
child: 4,
before: Some(9),
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(page_scrolls(&batch), [(true, 600.0)]);
}
/// The sticky cells sent to view `id` in `batch` (the last set), by cell.
fn sticky_of(batch: &MountBatch, id: NodeId) -> Option<Vec<(NodeId, f32, f32)>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::StickyCells { id: v, cells } if *v == id => {
Some(cells.iter().map(|c| (c.cell, c.start.0, c.end.0)).collect())
}
_ => None,
})
}
/// [`render_binds`] for the lists of a page: each list's cells by slot.
fn render_lists_binds(
c: &mut Core<FakeEngine>,
next_id: &mut u32,
cells: &mut rustc_hash::FxHashMap<NodeId, Vec<u32>>,
row_height: f32,
) {
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
// The overscan too, as an engine with time to spare binds it.
c.take_paced_list_binds(usize::MAX, &mut binds);
for bind in binds {
let list_cells = cells.entry(bind.list).or_default();
for (slot, index) in bind.binds {
while list_cells.len() <= slot as usize {
let id = *next_id;
*next_id += 1;
apply(
c,
vec![
Op::Create { id, tag: Tag::Cell },
Op::SetProp {
id,
prop: Prop::Slot(CellSlot::Item(list_cells.len() as u32)),
},
Op::Insert {
parent: bind.list,
child: id,
before: None,
},
],
);
list_cells.push(id);
}
let cell = list_cells[slot as usize];
c.apply(style_op(
cell,
&[("height", StyleValue::Number(row_height))],
))
.unwrap();
c.apply(Op::SetProp {
id: cell,
prop: Prop::CellIndex(index),
})
.unwrap();
}
}
}
/// Stacks the children of view `parent` as `batch` inserts and removes
/// them (`stacked`, bottom to top).
fn stack_children(stacked: &mut Vec<NodeId>, parent: NodeId, batch: Option<&MountBatch>) {
for item in batch.iter().flat_map(|b| &b.items) {
match *item {
MountItem::Insert {
parent: p,
child,
before,
} if p == parent => {
stacked.retain(|&v| v != child);
let at = before
.and_then(|b| stacked.iter().position(|&v| v == b))
.unwrap_or(stacked.len());
stacked.insert(at, child);
}
MountItem::Remove { id } => stacked.retain(|&v| v != id),
_ => {}
}
}
}
#[test]
fn page_lists_sticky_rows_stick_to_the_pages_viewport() {
let mut c = core();
// Two lists of 20 rows (1000) below a 100 pt header; rows 0 and 10 of
// each stick.
page(&mut c, 100.0, &[20, 20]);
for id in [4, 5] {
c.apply(Op::SetProp {
id,
prop: Prop::StickyIndices(vec![0, 10]),
})
.unwrap();
}
// The second list's views, bottom to top, as the batches stack them.
let mut stacked = Vec::new();
stack_children(&mut stacked, 5, c.commit().as_ref());
let (mut next_id, mut cells) = (100, rustc_hash::FxHashMap::default());
render_lists_binds(&mut c, &mut next_id, &mut cells, 50.0);
let batch = c.commit().unwrap();
stack_children(&mut stacked, 5, Some(&batch));
// The page's scroll view pins them, in its offsets: the first list's
// row 0 from 100 until row 10 pushes it out, row 10 from 600 until its
// bottom meets the list's end (1100).
let pinned = sticky_of(&batch, 2).expect("the page's sticky cells");
assert!(
pinned.contains(&(cells[&4][bound_slot(&c, 4, 0) as usize], 100.0, 550.0)),
"{pinned:?}"
);
assert!(
pinned.contains(&(cells[&4][bound_slot(&c, 4, 10) as usize], 600.0, 1050.0)),
"{pinned:?}"
);
// None for the lists themselves.
assert_eq!(sticky_of(&batch, 4), None);
// The second list's rows are not bound yet (it starts at 1100, past
// the window); scrolled there, its row 0 joins, from 1100.
c.set_scroll_offset(2, point(px(0.0), px(1200.0)), 0);
stack_children(&mut stacked, 5, c.commit().as_ref());
render_lists_binds(&mut c, &mut next_id, &mut cells, 50.0);
let batch = c.commit().unwrap();
stack_children(&mut stacked, 5, Some(&batch));
let pinned = sticky_of(&batch, 2).expect("the page's sticky cells");
assert!(
pinned.contains(&(cells[&5][bound_slot(&c, 5, 0) as usize], 1100.0, 1550.0)),
"{pinned:?}"
);
assert!(
pinned.contains(&(cells[&4][bound_slot(&c, 4, 10) as usize], 600.0, 1050.0)),
"{pinned:?}"
);
// A sticky cell goes on top of its list's other cells: only sticky
// cells are above it.
let sticky = [0, 10].map(|i| cells[&5][bound_slot(&c, 5, i) as usize]);
let at = stacked.iter().position(|&v| v == sticky[0]).unwrap();
assert!(
stacked[at + 1..].iter().all(|v| sticky.contains(v)),
"{stacked:?}"
);
// The first list leaves the page: its cells leave the page's set, and
// the second list's move up with it (it now starts at 100).
c.apply(Op::Remove {
parent: 2,
child: 4,
})
.unwrap();
let batch = c.commit().unwrap();
let pinned = sticky_of(&batch, 2).expect("the page's sticky cells");
assert!(
pinned.iter().all(|p| cells[&5].contains(&p.0)),
"{pinned:?}"
);
assert!(
pinned.contains(&(cells[&5][bound_slot(&c, 5, 0) as usize], 100.0, 550.0)),
"{pinned:?}"
);
}
/// A view (or a text) moved into a container inside a `display: none`
/// view, absolutely positioned or not, loses its old frame: its native
/// view is not left showing at its former size in a parent of no size.
#[test]
fn views_moved_into_a_hidden_subtree_lose_their_frames() {
for (tag, position) in [
(Tag::View, "relative"),
(Tag::Text, "relative"),
(Tag::View, "absolute"),
(Tag::Text, "absolute"),
] {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("display", StyleValue::Str("none"))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("position", StyleValue::Str(position))]),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Create { id: 6, tag },
style_op(6, &[("height", StyleValue::Number(20.0))]),
Op::Insert {
parent: ROOT_ID,
child: 6,
before: None,
},
];
if tag == Tag::Text {
ops.push(Op::CreateText {
id: 8,
text: "hello".into(),
});
ops.push(Op::Insert {
parent: 6,
child: 8,
before: None,
});
}
apply(&mut c, ops);
let shown = c.commit().unwrap();
assert_eq!(frame_of(&shown, 6).unwrap().size, size_pt(320.0, 20.0));
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 6,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
],
);
let hidden = c.commit().unwrap();
assert_eq!(
frame_of(&hidden, 6),
Some(Bounds::default()),
"{tag:?} in a {position} container"
);
}
}
/// The layout an incremental commit gives equals the one a core laid out
/// from scratch gives the same tree: random trees of views and texts,
/// changed by random insertions, moves, removals, style and text changes,
/// compared node by node after each commit. What makes layout incremental
/// (caches, dirty propagation, partial walks) is held to this.
mod layout_consistency {
use std::collections::{BTreeMap, HashMap};
use super::*;
/// A seeded xorshift64*: the same seed, the same trees.
struct Rng(u64);
impl Rng {
fn new(seed: u64) -> Rng {
Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n as u64) as usize
}
fn pick<T: Copy>(&mut self, of: &[T]) -> T {
of[self.below(of.len())]
}
/// True `percent`% of the time.
fn chance(&mut self, percent: u64) -> bool {
self.next() % 100 < percent
}
}
#[derive(Clone, Copy, Debug)]
enum Value {
N(f32),
S(&'static str),
}
/// A view or a text (its raw text child and content) in the model.
#[derive(Clone, Debug)]
struct Node {
parent: NodeId,
text: Option<(NodeId, String)>,
style: Vec<(&'static str, Value)>,
children: Vec<NodeId>,
}
/// The tree as the test made it.
#[derive(Default)]
struct Model {
nodes: BTreeMap<NodeId, Node>,
next: NodeId,
}
impl Model {
fn id(&mut self) -> NodeId {
self.next += 2;
self.next
}
fn children(&self, parent: NodeId) -> Vec<NodeId> {
if parent == ROOT_ID {
self.roots().to_vec()
} else {
self.nodes[&parent].children.clone()
}
}
fn roots(&self) -> &[NodeId] {
self.nodes
.get(&0)
.map_or(&[][..], |root| root.children.as_slice())
}
fn is_inside(&self, mut id: NodeId, ancestor: NodeId) -> bool {
loop {
if id == ancestor {
return true;
}
match self.nodes.get(&id) {
Some(node) if node.parent != ROOT_ID => id = node.parent,
_ => return false,
}
}
}
/// The live nodes: views and texts, the root's holder aside.
fn live(&self) -> Vec<NodeId> {
self.nodes.keys().copied().filter(|&id| id != 0).collect()
}
fn views(&self) -> Vec<NodeId> {
self.nodes
.iter()
.filter(|(id, n)| **id != 0 && n.text.is_none())
.map(|(&id, _)| id)
.collect()
}
/// The subtree of `id`, it first.
fn subtree(&self, id: NodeId) -> Vec<NodeId> {
let mut out = vec![id];
let mut at = 0;
while at < out.len() {
out.extend(self.nodes[&out[at]].children.iter().copied());
at += 1;
}
out
}
fn detach(&mut self, id: NodeId) -> NodeId {
let parent = self.nodes[&id].parent;
let holder = if parent == ROOT_ID { 0 } else { parent };
self.nodes
.get_mut(&holder)
.unwrap()
.children
.retain(|&c| c != id);
parent
}
fn attach(&mut self, id: NodeId, parent: NodeId, at: usize) -> Option<NodeId> {
let holder = if parent == ROOT_ID { 0 } else { parent };
let siblings = &mut self.nodes.get_mut(&holder).unwrap().children;
let at = at.min(siblings.len());
let before = siblings.get(at).copied();
siblings.insert(at, id);
self.nodes.get_mut(&id).unwrap().parent = parent;
before
}
/// The ops that make `id` and what it holds, detached.
fn create(&self, id: NodeId, ops: &mut Vec<Op>) {
let node = &self.nodes[&id];
ops.push(Op::Create {
id,
tag: if node.text.is_some() {
Tag::Text
} else {
Tag::View
},
});
ops.push(style_of(id, &node.style));
if let Some((raw, content)) = &node.text {
ops.push(Op::CreateText {
id: *raw,
text: content.as_str().into(),
});
ops.push(Op::Insert {
parent: id,
child: *raw,
before: None,
});
}
for &child in &node.children {
self.create(child, ops);
ops.push(Op::Insert {
parent: id,
child,
before: None,
});
}
}
/// The ops that make the whole tree on a new core.
fn build(&self) -> Vec<Op> {
let mut ops = Vec::new();
for &id in self.roots() {
self.create(id, &mut ops);
ops.push(Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
});
}
ops
}
}
fn style_of(id: NodeId, style: &[(&'static str, Value)]) -> Op {
let props: Vec<(&str, StyleValue<'_>)> = style
.iter()
.map(|&(k, v)| {
(
k,
match v {
Value::N(n) => StyleValue::Number(n),
Value::S(s) => StyleValue::Str(s),
},
)
})
.collect();
style_op(id, &props)
}
/// A random style for a view (or, `text`, a text): sizes fixed,
/// relative or free, flex and grid containers, absolute positions,
/// `display: none`, clipping, minimums and maximums.
fn random_style(rng: &mut Rng, text: bool, fractions: bool) -> Vec<(&'static str, Value)> {
use Value::{N, S};
// Fractional values, where rounding to whole points matters; the
// same number of choices either way, so a seed makes the same tree
// shapes.
let f = |whole: Value, fraction: Value| if fractions { fraction } else { whole };
let mut style = Vec::new();
let mut maybe = |rng: &mut Rng, percent, key, values: &[Value]| {
if rng.chance(percent) {
style.push((key, rng.pick(values)));
}
};
if !text {
maybe(rng, 50, "flexDirection", &[S("row"), S("column")]);
maybe(
rng,
15,
"display",
&[S("none"), S("grid"), S("block"), S("flex")],
);
maybe(rng, 30, "flexWrap", &[S("wrap"), S("nowrap")]);
maybe(
rng,
30,
"alignItems",
&[S("center"), S("flex-start"), S("stretch"), S("flex-end")],
);
maybe(
rng,
30,
"justifyContent",
&[S("center"), S("space-between"), S("flex-end")],
);
maybe(rng, 30, "padding", &[N(4.0), f(N(10.0), N(4.5))]);
maybe(rng, 30, "gap", &[N(3.0), f(N(8.0), N(2.5))]);
maybe(rng, 15, "overflow", &[S("hidden")]);
maybe(
rng,
15,
"gridTemplateColumns",
&[
S("repeat(2, 1fr)"),
S("40px 1fr"),
S("repeat(3, minmax(0, 1fr))"),
],
);
maybe(
rng,
40,
"height",
&[
N(24.0),
f(N(60.0), N(24.5)),
f(S("50%"), S("33.3%")),
S("auto"),
],
);
}
maybe(
rng,
45,
"width",
&[
N(40.0),
f(N(120.0), N(37.5)),
f(S("50%"), S("33.3%")),
S("100%"),
S("auto"),
],
);
maybe(rng, 25, "flexGrow", &[N(1.0), N(2.0)]);
maybe(rng, 25, "flexShrink", &[N(1.0), N(0.0)]);
maybe(rng, 15, "flexBasis", &[N(30.0), S("50%")]);
maybe(rng, 20, "margin", &[N(2.0), f(N(6.0), N(2.5))]);
maybe(rng, 15, "minWidth", &[N(20.0), N(90.0)]);
maybe(rng, 15, "maxWidth", &[N(60.0), N(150.0)]);
maybe(
rng,
15,
"alignSelf",
&[S("center"), S("stretch"), S("flex-end")],
);
if rng.chance(10) {
style.push(("position", S("absolute")));
style.push((
"left",
rng.pick(&[N(5.0), N(30.0), f(S("10%"), S("12.5%"))]),
));
style.push(("top", rng.pick(&[N(4.0), N(50.0)])));
}
style
}
fn random_text(rng: &mut Rng) -> String {
let words = [
"a",
"price",
"12.50",
"a longer label",
"x",
"quote board",
"—",
];
(0..1 + rng.below(4))
.map(|_| rng.pick(&words))
.collect::<Vec<_>>()
.join(" ")
}
/// The frames of every view the core laid out: what `batches` set,
/// latest last.
fn note_frames(frames: &mut HashMap<NodeId, Bounds<Points>>, batch: Option<MountBatch>) {
for item in batch.iter().flat_map(|b| &b.items) {
match item {
MountItem::Frame { id, frame } => {
frames.insert(*id, *frame);
}
MountItem::Delete { id } => {
frames.remove(id);
}
_ => {}
}
}
}
/// One random change of the tree: its ops, and what it was.
fn change(rng: &mut Rng, model: &mut Model, fractions: bool) -> (Vec<Op>, String) {
let live = model.live();
let views = model.views();
let mut ops = Vec::new();
let roll = if live.len() < 8 { 0 } else { rng.below(100) };
let what = match roll {
// Add a view or a text.
0..=34 if live.len() < 70 => {
let id = model.id();
let text = rng.chance(45);
let raw = text.then(|| model.id());
model.nodes.insert(
id,
Node {
parent: ROOT_ID,
text: raw.map(|raw| (raw, random_text(rng))),
style: random_style(rng, text, fractions),
children: Vec::new(),
},
);
let parent = if views.is_empty() || rng.chance(10) {
ROOT_ID
} else {
rng.pick(&views)
};
let at = rng.below(model.children(parent).len() + 1);
model.create(id, &mut ops);
let before = model.attach(id, parent, at);
ops.push(Op::Insert {
parent,
child: id,
before,
});
format!("add {id} to {parent}")
}
// Change a style.
0..=59 => {
let id = rng.pick(&live);
let text = model.nodes[&id].text.is_some();
let style = random_style(rng, text, fractions);
ops.push(style_of(id, &style));
model.nodes.get_mut(&id).unwrap().style = style;
format!("style {id}")
}
// Change a text.
60..=74 => {
let texts: Vec<NodeId> = live
.iter()
.copied()
.filter(|id| model.nodes[id].text.is_some())
.collect();
if texts.is_empty() {
return (ops, "nothing".into());
}
let id = rng.pick(&texts);
let content = random_text(rng);
let raw = model.nodes[&id].text.as_ref().unwrap().0;
ops.push(Op::SetText {
id: raw,
text: content.as_str().into(),
});
model.nodes.get_mut(&id).unwrap().text.as_mut().unwrap().1 = content;
format!("text {id}")
}
// Move a node elsewhere.
75..=89 => {
let id = rng.pick(&live);
let targets: Vec<NodeId> = views
.iter()
.copied()
.filter(|&v| !model.is_inside(v, id))
.chain([ROOT_ID])
.collect();
let parent = rng.pick(&targets);
let old = model.detach(id);
ops.push(Op::Remove {
parent: old,
child: id,
});
let at = rng.below(model.children(parent).len() + 1);
let before = model.attach(id, parent, at);
ops.push(Op::Insert {
parent,
child: id,
before,
});
format!("move {id} from {old} to {parent}")
}
// Remove a node and what it holds.
_ => {
let id = rng.pick(&live);
let parent = model.detach(id);
ops.push(Op::Remove { parent, child: id });
for gone in model.subtree(id) {
let node = model.nodes.remove(&gone).unwrap();
if let Some((raw, _)) = node.text {
ops.push(Op::Release { id: raw });
}
ops.push(Op::Release { id: gone });
}
format!("remove {id}")
}
};
(ops, what)
}
/// `seed`'s run: `steps` commits of changes, each compared with a
/// layout from scratch; with `fractions`, sizes and offsets that are
/// not whole points.
fn run(seed: u64, steps: usize, fractions: bool) {
let mut rng = Rng::new(seed);
let mut model = Model::default();
model.nodes.insert(
0,
Node {
parent: ROOT_ID,
text: None,
style: Vec::new(),
children: Vec::new(),
},
);
let mut c = core();
let mut frames = HashMap::new();
let mut log = Vec::new();
for step in 0..steps {
// A commit takes a few changes at once, as a turn does.
let changes = 1 + rng.below(3);
for _ in 0..changes {
let (ops, what) = change(&mut rng, &mut model, fractions);
apply(&mut c, ops);
log.push(what);
}
note_frames(&mut frames, c.commit());
let mut fresh = core();
apply(&mut fresh, model.build());
let mut expected = HashMap::new();
note_frames(&mut expected, fresh.commit());
for id in model.live() {
let got = frames.get(&id).copied().unwrap_or_default();
let want = expected.get(&id).copied().unwrap_or_default();
assert_eq!(
got,
want,
"seed {seed}, step {step}: node {id} laid out incrementally at {got:?}, from \
scratch at {want:?}; the node and the views around it: {:?}; changes so far: \
{log:?}",
{
let mut chain = Vec::new();
let mut at = id;
while let Some(node) = model.nodes.get(&at) {
chain.push((at, node.style.clone(), node.text.clone()));
if node.parent == ROOT_ID {
break;
}
at = node.parent;
}
chain
}
);
}
}
}
#[test]
fn incremental_layout_equals_layout_from_scratch() {
for seed in 0..24 {
run(seed, 60, true);
}
// A view of a hidden subtree's absolutely positioned container
// removed while the root was laid out again: Taffy's rounding pass
// reached it through a list that still held it, and panicked.
run(39, 70, false);
}
}
/// A list's cells take its rounded cross size, as every other view's frame
/// is rounded: a list at a fractional place and size gives them whole
/// points.
#[test]
fn list_cells_take_the_rounded_cross_size() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(
2,
&[
("height", StyleValue::Number(400.0)),
("width", StyleValue::Number(100.6)),
("marginLeft", StyleValue::Number(0.3)),
],
),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(3),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let first = c.commit().unwrap();
assert_eq!(frame_of(&first, 2).unwrap().size.width, px(101.0));
let (mut next, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next, &mut cells, 50.0);
let batch = c.commit().unwrap();
assert!(!cells.is_empty());
for &cell in &cells {
assert_eq!(frame_of(&batch, cell).unwrap().size.width, px(101.0));
}
}
#[test]
fn prose_respects_responsive_widths_and_inherited_font_updates() {
let mut c = Core::new(SizedEngine, size_pt(2000.0, 480.0));
for (id, tag, classes, parent) in [
(2, Tag::View, "text-[20px]", ROOT_ID),
(3, Tag::Text, "max-w-prose w-full h-[10px]", 2),
(
4,
Tag::View,
"text-[20px] max-w-prose md:max-w-[100px] w-full h-[10px]",
2,
),
(5, Tag::View, "text-[10px]", ROOT_ID),
] {
c.apply(Op::Create { id, tag }).unwrap();
c.apply(class_op(id, classes)).unwrap();
c.apply(Op::Insert {
parent,
child: id,
before: None,
})
.unwrap();
}
c.commit().unwrap();
assert_eq!(c.measure(3).unwrap().frame.size.width, px(650.0));
assert_eq!(c.measure(4).unwrap().frame.size.width, px(100.0));
c.apply(class_op(2, "text-[10px]")).unwrap();
c.commit().unwrap();
assert_eq!(c.measure(3).unwrap().frame.size.width, px(325.0));
c.apply(class_op(2, "text-[20px]")).unwrap();
c.commit().unwrap();
c.apply(Op::Insert {
parent: 5,
child: 3,
before: None,
})
.unwrap();
c.commit().unwrap();
assert_eq!(c.measure(3).unwrap().frame.size.width, px(325.0));
}
#[test]
fn space_important_margins_win_over_normal_child_styles() {
for (space, child, expected) in [
("space-x-[20px]", "mr-0", 30.0),
("space-x-[20px]!", "mr-0", 50.0),
("space-x-[20px]!", "mr-0!", 30.0),
] {
let mut c = core();
view_with_classes(
&mut c,
2,
&format!("flex flex-row w-[200px] h-[40px] {space}"),
);
for id in [3, 4] {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
c.apply(class_op(
id,
&format!("w-[30px] h-[20px] {}", if id == 3 { child } else { "" }),
))
.unwrap();
c.apply(Op::Insert {
parent: 2,
child: id,
before: None,
})
.unwrap();
}
c.commit().unwrap();
assert_eq!(
c.measure(4).unwrap().frame.origin.x,
px(expected),
"{space} {child}"
);
}
}
#[test]
fn headless_text_frames_respect_inherited_and_updated_line_heights() {
for nested in [false, true] {
let mut c = Core::new(crate::ApproxTextEngine, size_pt(300.0, 400.0));
c.apply(Op::Create {
id: 2,
tag: Tag::Text,
})
.unwrap();
c.apply(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
})
.unwrap();
if nested {
c.apply(Op::Create {
id: 3,
tag: Tag::Text,
})
.unwrap();
c.apply(Op::Insert {
parent: 2,
child: 3,
before: None,
})
.unwrap();
}
c.apply(Op::CreateText {
id: 4,
text: "Direct or nested".into(),
})
.unwrap();
c.apply(Op::Insert {
parent: if nested { 3 } else { 2 },
child: 4,
before: None,
})
.unwrap();
for (height, expected) in [(50.0, 50.0), (30.0, 30.0), (0.0, 17.0)] {
c.apply(Op::SetStyle {
id: 2,
style: style(&[
("fontSize", StyleValue::Number(14.0)),
("lineHeight", StyleValue::Number(height)),
]),
patch: Default::default(),
})
.unwrap();
c.commit().unwrap();
assert_eq!(
c.measure(2).unwrap().frame.size.height,
px(expected),
"nested={nested}, height={height}"
);
}
}
}
/// Nested spans resolve a unitless line height against their own font, but
/// the paragraph keeps the root `<Text>`'s resolved strut separately.
#[test]
fn nested_spans_do_not_redefine_the_root_line_height() {
for first_small in [true, false] {
let mut c = Core::new(crate::ApproxTextEngine, size_pt(320.0, 480.0));
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::SetStyle {
id: 2,
style: style(&[
("fontSize", StyleValue::Number(14.0)),
// Strings are CSS-like unitless multiples; numbers are points.
("lineHeight", StyleValue::Str("1.625")),
]),
patch: Default::default(),
},
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::SetStyle {
id: 3,
style: style(&[("fontSize", StyleValue::Str("0.9em"))]),
patch: Default::default(),
},
Op::CreateText {
id: 4,
text: "`code`".into(),
},
Op::CreateText {
id: 5,
text: " 中文正文".into(),
},
insert(3, 4),
];
if first_small {
ops.extend([insert(2, 3), insert(2, 5)]);
} else {
ops.extend([insert(2, 5), insert(2, 3)]);
}
ops.push(insert(ROOT_ID, 2));
for op in ops {
c.apply(op).unwrap();
}
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text),
_ => None,
})
.unwrap();
let strut = text.paragraph_strut.expect("core sets the root strut");
assert!(
(strut.line_height.0 - 22.75).abs() < 0.001,
"{first_small}: {:?}",
strut.line_height
);
assert_eq!(strut.font_size, px(14.0));
let small = text
.spans
.iter()
.map(|s| s.style.line_height.0)
.fold(f32::INFINITY, f32::min);
assert!((small - 20.475).abs() < 0.001, "{first_small}: {small}");
assert_eq!(
c.measure(2).unwrap().frame.size.height,
px(23.0),
"{first_small}"
);
}
}
/// `items-baseline` uses the body text's root-strut baseline even when the
/// whole body is a smaller inline-code span.
#[test]
fn a_baseline_row_uses_the_body_texts_root_strut() {
let mut c = Core::new(crate::ApproxTextEngine, size_pt(320.0, 480.0));
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
for op in [
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, "flex-row items-baseline"),
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::SetStyle {
id: 3,
style: style(&[
("fontSize", StyleValue::Number(10.0)),
("lineHeight", StyleValue::Number(24.375)),
]),
patch: Default::default(),
},
Op::CreateText {
id: 4,
text: "•".into(),
},
Op::Create {
id: 5,
tag: Tag::Text,
},
Op::SetStyle {
id: 5,
style: style(&[
("fontSize", StyleValue::Number(15.0)),
("lineHeight", StyleValue::Str("1.625")),
]),
patch: Default::default(),
},
Op::Create {
id: 6,
tag: Tag::Text,
},
Op::SetStyle {
id: 6,
style: style(&[("fontSize", StyleValue::Str("0.9em"))]),
patch: Default::default(),
},
Op::CreateText {
id: 7,
text: "`useState`".into(),
},
insert(3, 4),
insert(6, 7),
insert(5, 6),
insert(2, 3),
insert(2, 5),
insert(ROOT_ID, 2),
] {
c.apply(op).unwrap();
}
let batch = c.commit().unwrap();
let top = |id| frame_of(&batch, id).map(|f| f.origin.y.0);
// Approx's body baseline is 15 × 1.2 plus half of 24.375 - 15 × 1.2 =
// 21.1875. The 10pt marker's is 18.1875, so it starts 3pt lower.
assert_eq!(top(5), Some(0.0));
assert!(
(top(3).unwrap() - 3.0).abs() < 0.001,
"marker top {:?}",
top(3)
);
}
#[test]
fn percentage_line_heights_inherit_as_computed_lengths() {
for (leading, expected) in [
("leading-[150%]", 30.0),
("leading-[1.5em]", 30.0),
("leading-[1.5]", 15.0),
] {
let mut c = core();
for (id, classes, parent) in [
(2, format!("text-[20px] {leading}"), ROOT_ID),
(3, "text-[10px]".to_owned(), 2),
] {
c.apply(Op::Create { id, tag: Tag::Text }).unwrap();
c.apply(class_op(id, &classes)).unwrap();
c.apply(Op::Insert {
parent,
child: id,
before: None,
})
.unwrap();
}
c.apply(Op::CreateText {
id: 4,
text: "small".to_owned(),
})
.unwrap();
c.apply(Op::Insert {
parent: 3,
child: 4,
before: None,
})
.unwrap();
let batch = c.commit().unwrap();
let text = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text { id: 2, text, .. } => Some(text),
_ => None,
})
.unwrap();
assert_eq!(text.spans[0].style.line_height, px(expected), "{leading}");
}
}
#[test]
fn static_boxes_use_taffys_containing_block() {
let mut c = core();
for (id, classes, parent) in [
(2, "relative w-[300px] h-[300px] p-[40px]", ROOT_ID),
(3, "static w-[200px] h-[100px]", 2),
(4, "absolute top-0 left-0 size-[10px]", 3),
] {
c.apply(Op::Create { id, tag: Tag::View }).unwrap();
c.apply(class_op(id, classes)).unwrap();
c.apply(Op::Insert {
parent,
child: id,
before: None,
})
.unwrap();
}
c.commit().unwrap();
assert_eq!(c.measure(4).unwrap().page, point(px(0.0), px(0.0)));
assert_eq!(
c.measure(4).unwrap().frame.origin,
point(px(-40.0), px(-40.0))
);
c.apply(class_op(3, "relative w-[200px] h-[100px]"))
.unwrap();
c.commit().unwrap();
assert_eq!(c.measure(4).unwrap().page, point(px(40.0), px(40.0)));
}
#[test]
fn fixed_elements_keep_their_kind_and_mount_in_the_root() {
for tag in [Tag::View, Tag::Text, Tag::Image, Tag::Input, Tag::Scroll] {
let mut c = core();
view_with_classes(&mut c, 2, "p-[40px] h-[200px]");
c.apply(Op::Create { id: 3, tag }).unwrap();
c.apply(class_op(3, "fixed top-0 left-0 w-[80px] h-[20px]"))
.unwrap();
c.apply(Op::Insert {
parent: 2,
child: 3,
before: None,
})
.unwrap();
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(ROOT_ID, 3, None)), "{tag:?}");
assert_eq!(
c.measure(3).unwrap().page,
point(px(0.0), px(0.0)),
"{tag:?}"
);
assert_eq!(c.nodes[c.key(3).unwrap() as usize].kind, Kind::of(tag));
c.apply(class_op(3, "relative w-[80px] h-[20px]")).unwrap();
c.commit().unwrap();
assert_eq!(
c.measure(3).unwrap().page,
point(px(40.0), px(40.0)),
"{tag:?}"
);
}
}
#[test]
fn intrinsic_sizes_and_content_boxes_are_computed_by_taffy() {
let mut c = core();
for (id, classes) in [
(2, "box-content w-[100px] h-[20px] p-[10px] border-2"),
(3, "box-border w-[100px] h-[20px] p-[10px] border-2"),
] {
view_with_classes(&mut c, id, classes);
}
c.commit().unwrap();
assert_eq!(c.measure(2).unwrap().frame.size, size_pt(124.0, 44.0));
assert_eq!(c.measure(3).unwrap().frame.size.width, px(100.0));
for (classes, expected) in [("w-min", 48.0), ("w-max", 72.0), ("w-fit", 72.0)] {
let mut c = core();
c.apply(Op::Create {
id: 2,
tag: Tag::Text,
})
.unwrap();
c.apply(class_op(2, classes)).unwrap();
c.apply(Op::CreateText {
id: 3,
text: "longer hi".into(),
})
.unwrap();
c.apply(Op::Insert {
parent: 2,
child: 3,
before: None,
})
.unwrap();
c.apply(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
})
.unwrap();
c.commit().unwrap();
assert_eq!(
c.measure(2).unwrap().frame.size.width,
px(expected),
"{classes}"
);
}
}
#[test]
fn physical_text_alignment_survives_a_descendants_direction_change() {
let mut c = core();
view_with_classes(&mut c, 2, "text-left");
c.apply(Op::Create {
id: 3,
tag: Tag::Text,
})
.unwrap();
c.apply(style_op(3, &[("direction", StyleValue::Str("rtl"))]))
.unwrap();
c.apply(Op::CreateText {
id: 4,
text: "aligned".into(),
})
.unwrap();
c.apply(Op::Insert {
parent: 3,
child: 4,
before: None,
})
.unwrap();
c.apply(Op::Insert {
parent: 2,
child: 3,
before: None,
})
.unwrap();
let batch = c.commit().unwrap();
let align = batch.items.iter().find_map(|i| match i {
MountItem::Text { id: 3, text, .. } => Some(text.align),
_ => None,
});
assert_eq!(align, Some(TextAlign::Left));
}
#[test]
fn a_fixed_text_span_can_return_to_its_inline_parent() {
let mut c = core();
add(&mut c, 2, Tag::Text, ROOT_ID, &[]);
add(&mut c, 3, Tag::Text, 2, &[]);
c.commit();
assert!(c.nodes[c.key(3).unwrap() as usize].inline);
c.apply(class_op(3, "fixed top-0 left-0 w-[40px] h-[20px]"))
.unwrap();
let batch = c.commit().unwrap();
assert!(inserts(&batch).contains(&(ROOT_ID, 3, None)));
assert_eq!(c.measure(3).unwrap().page, point(px(0.0), px(0.0)));
c.apply(class_op(3, "relative")).unwrap();
c.commit();
let node = &c.nodes[c.key(3).unwrap() as usize];
assert!(node.inline);
assert!(node.layout.is_none());
}
#[test]
fn a_span_moved_out_of_its_text_is_laid_out_with_its_style() {
let mut c = core();
add(&mut c, 2, Tag::Text, ROOT_ID, &[]);
add(
&mut c,
3,
Tag::Text,
2,
&[("width", StyleValue::Number(40.0))],
);
c.commit();
assert!(c.nodes[c.key(3).unwrap() as usize].layout.is_none());
// Styled while a span, then a block of its own.
c.apply(style_op(3, &[("width", StyleValue::Number(60.0))]))
.unwrap();
let insert = |c: &mut Core<FakeEngine>, parent| {
c.apply(Op::Insert {
parent,
child: 3,
before: None,
})
.unwrap();
c.commit();
};
insert(&mut c, ROOT_ID);
assert_eq!(c.measure(3).unwrap().frame.size.width, px(60.0));
// A span again, and a block again, with the style it had as a block.
insert(&mut c, 2);
assert!(c.nodes[c.key(3).unwrap() as usize].layout.is_none());
insert(&mut c, ROOT_ID);
assert_eq!(c.measure(3).unwrap().frame.size.width, px(60.0));
}
/// A view of `height` in `parent`, with `style` on top.
fn child_view(
id: NodeId,
parent: NodeId,
height: f32,
style: &[(&str, StyleValue<'_>)],
) -> Vec<Op> {
let mut props = vec![("height", StyleValue::Number(height))];
props.extend_from_slice(style);
vec![
Op::Create { id, tag: Tag::View },
style_op(id, &props),
Op::Insert {
parent,
child: id,
before: None,
},
]
}
/// The ids of the views `batch` makes.
fn created_in(batch: &MountBatch) -> Vec<NodeId> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Create { id, .. } => Some(*id),
_ => None,
})
.collect()
}
#[test]
fn a_scroll_view_mounts_its_content_near_its_viewport() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// Rows of 50 in a wrapper, each with a child: 0..2000.
ops.extend(child_view(4, 2, 2000.0, &[]));
for i in 0..40u32 {
ops.extend(child_view(10 + 4 * i, 4, 50.0, &[]));
ops.extend(child_view(12 + 4 * i, 10 + 4 * i, 20.0, &[]));
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
// The viewport (0..100) and a viewport around it: rows 0..3, each with
// its child.
let made = created_in(&batch);
assert_eq!(made[..3], [2, 4, 10]);
assert!(made.contains(&12) && made.contains(&22) && made.contains(&24));
assert!(!made.contains(&26), "{made:?}");
// Far rows are laid out all the same.
assert_eq!(
c.measure(10 + 4 * 30).unwrap().frame.origin.y,
Points(1500.0)
);
// Scrolled to 1000: rows from 900 to 1200 come.
c.set_scroll_offset(2, point(Points::ZERO, Points(1000.0)), 0);
let batch = c.commit().unwrap();
let made = created_in(&batch);
let rows: Vec<u32> = made
.iter()
.filter(|&&id| (id - 10) % 4 == 0)
.map(|&id| (id - 10) / 4)
.collect();
assert_eq!(rows, (18..24).collect::<Vec<_>>());
// Each in its place, with its frame.
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Insert {
parent: 4,
child: 82,
before: None
}
)));
assert_eq!(frame_of(&batch, 82), Some(rect(0.0, 900.0, 320.0, 50.0)));
// The rows more than three viewports above (before 700) went: out of
// their parent, each view destroyed, children first.
let deleted: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Delete { id } => Some(*id),
_ => None,
})
.collect();
assert_eq!(deleted[..2], [12, 10]);
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id: 10 }))
);
// Rows between stay.
assert!(!deleted.contains(&(10 + 4 * 15)));
// Back at the top: made again where they were, with their style.
c.set_scroll_offset(2, point(Points::ZERO, Points::ZERO), 0);
let batch = c.commit().unwrap();
let made = created_in(&batch);
assert!(made.contains(&10) && made.contains(&12), "{made:?}");
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 0.0, 320.0, 50.0)));
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Insert {
parent: 4,
child: 10,
..
}
)));
}
#[test]
fn a_far_row_that_keeps_state_in_its_view_is_not_given_up() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// A row holding a field, then plain rows down to 2000.
ops.extend(child_view(4, 2, 50.0, &[]));
ops.extend([
Op::Create {
id: 6,
tag: Tag::Input,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
]);
ops.extend(child_view(8, 2, 50.0, &[]));
ops.extend(child_view(10, 2, 2000.0, &[]));
apply(&mut c, ops);
c.commit().unwrap();
c.set_scroll_offset(2, point(Points::ZERO, Points(1500.0)), 0);
let batch = c.commit().unwrap();
let deleted: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Delete { id } => Some(*id),
_ => None,
})
.collect();
// The plain row goes; the field's row stays with what it holds.
assert_eq!(deleted, [8]);
}
/// The content box `batch` sends input `id`, when it sends one.
fn input_content_of(batch: &MountBatch, id: NodeId) -> Option<Bounds<Points>> {
batch.items.iter().find_map(|i| match i {
MountItem::InputContent { id: input, content } if *input == id => Some(*content),
_ => None,
})
}
#[test]
fn a_culled_input_gets_its_content_box_when_it_is_made() {
// A scroll view's content waits until the scroll view is placed, and is
// made then with the frames it was laid out at: an input among it still
// needs its content box, or its field covers its padding.
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, 50.0, &[]));
ops.extend([
Op::Create {
id: 6,
tag: Tag::Input,
},
style_op(6, &[("padding", StyleValue::Number(6.0))]),
Op::Insert {
parent: 2,
child: 6,
before: None,
},
]);
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&6));
assert_eq!(frame_of(&batch, 6), Some(rect(0.0, 50.0, 320.0, 28.0)));
assert_eq!(
input_content_of(&batch, 6),
Some(rect(6.0, 6.0, 308.0, 16.0))
);
// One added to the placed scroll view later is made the same way.
let mut ops = child_view(8, 2, 50.0, &[]);
ops.extend([
Op::Create {
id: 10,
tag: Tag::Input,
},
style_op(10, &[("padding", StyleValue::Number(6.0))]),
Op::Insert {
parent: 8,
child: 10,
before: None,
},
]);
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&10));
assert_eq!(
input_content_of(&batch, 10),
Some(rect(6.0, 6.0, 308.0, 16.0))
);
}
#[test]
fn a_culled_scroll_view_gets_its_extent_when_it_is_made() {
// A scroll view in another's content is made once that one is placed:
// it still needs its extent, or it does not scroll.
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 6,
tag: Tag::Scroll,
},
style_op(6, &[("height", StyleValue::Number(80.0))]),
Op::Insert {
parent: 2,
child: 6,
before: None,
},
];
ops.extend(child_view(8, 6, 300.0, &[]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&6));
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::ScrollContent { id: 6, size } if *size == Size::new(px(320.0), px(300.0))))
);
}
#[test]
fn the_content_of_an_attachment_in_a_scroll_view_is_made_with_it() {
// A view inside a text is placed by the text, not where the scroll
// view's culling looks for views: what it holds is made with it (a
// `RichEditor`'s image in its paragraph), on the first layout or on a
// later one, and never waits as culled content.
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
let attached = |text: NodeId, view: NodeId, image: NodeId| {
vec![
Op::Create {
id: text,
tag: Tag::Text,
},
Op::CreateText {
id: text + 1,
text: "ab".into(),
},
Op::Insert {
parent: text,
child: text + 1,
before: None,
},
Op::Create {
id: view,
tag: Tag::View,
},
Op::Create {
id: image,
tag: Tag::Image,
},
style_op(
image,
&[
("width", StyleValue::Number(40.0)),
("height", StyleValue::Number(20.0)),
],
),
Op::Insert {
parent: view,
child: image,
before: None,
},
Op::Insert {
parent: text,
child: view,
before: None,
},
Op::Insert {
parent: 2,
child: text,
before: None,
},
]
};
ops.extend(attached(4, 6, 8));
apply(&mut c, ops);
let mut items = Vec::new();
while let Some(batch) = c.commit() {
items.extend(batch.items);
}
let inserted = |items: &[MountItem], parent: NodeId, child: NodeId| {
items.iter().any(|i| {
matches!(i, MountItem::Insert { parent: p, child: ch, .. } if *p == parent && *ch == child)
})
};
let created = |items: &[MountItem], id: NodeId| {
items
.iter()
.any(|i| matches!(i, MountItem::Create { id: c, .. } if *c == id))
};
assert!(inserted(&items, 4, 6), "the attachment is in its text");
assert!(created(&items, 8), "the image in the attachment is made");
assert!(inserted(&items, 6, 8), "and inside the attachment");
// A text added to the placed scroll view later, as an editor's
// paragraphs are.
apply(&mut c, attached(10, 12, 14));
let mut items = Vec::new();
while let Some(batch) = c.commit() {
items.extend(batch.items);
}
assert!(inserted(&items, 10, 12));
assert!(created(&items, 14));
assert!(inserted(&items, 12, 14));
}
#[test]
fn the_content_of_attachments_made_past_the_pace_comes_too() {
// A long document of paragraphs, each with a view holding an image:
// past the views a turn makes at once, what attachments hold waits for
// later turns, and comes, in sight and as the content scrolls.
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
let paragraphs = 120u32;
let ids = |i: u32| (10 + 4 * i, 11 + 4 * i, 12 + 4 * i, 13 + 4 * i);
for i in 0..paragraphs {
let (text, raw, view, image) = ids(i);
ops.extend([
Op::Create {
id: text,
tag: Tag::Text,
},
Op::CreateText {
id: raw,
text: "ab".into(),
},
Op::Insert {
parent: text,
child: raw,
before: None,
},
Op::Create {
id: view,
tag: Tag::View,
},
Op::Create {
id: image,
tag: Tag::Image,
},
style_op(
image,
&[
("width", StyleValue::Number(40.0)),
("height", StyleValue::Number(20.0)),
],
),
Op::Insert {
parent: view,
child: image,
before: None,
},
Op::Insert {
parent: text,
child: view,
before: None,
},
Op::Insert {
parent: 2,
child: text,
before: None,
},
]);
}
apply(&mut c, ops);
let mut items = Vec::new();
let mut drain = |c: &mut Core<FakeEngine>| {
for _ in 0..200 {
let Some(batch) = c.commit() else { break };
items.extend(batch.items);
}
};
drain(&mut c);
for y in [1000.0, 2000.0, 3000.0, 100_000.0] {
c.set_scroll_offset(2, point(Points::ZERO, Points(y)), 0);
drain(&mut c);
}
let inserted = |parent: NodeId, child: NodeId| {
items.iter().any(|i| {
matches!(i, MountItem::Insert { parent: p, child: ch, .. } if *p == parent && *ch == child)
})
};
let attached: Vec<u32> = (0..paragraphs)
.filter(|&i| inserted(ids(i).0, ids(i).2))
.collect();
assert!(
attached.len() > super::pace::PACE_AFTER,
"{}",
attached.len()
);
for i in attached {
let (_, _, view, image) = ids(i);
assert!(inserted(view, image), "paragraph {i}'s image");
}
}
/// A list 400 tall of eight cells 100 tall, each bound with a column of
/// 40 views: the cells in sight make more views than a turn's budget, so
/// the views of the cells out of sight wait (`pace.rs`). Returns the core
/// with views waiting, the last that waits and its parent's id.
fn paced_cells() -> (Core<FakeEngine>, NodeId, NodeId) {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(100.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(8),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
c.take_paced_list_binds(usize::MAX, &mut binds);
let mut ops = Vec::new();
for (slot, index) in binds.iter().flat_map(|b| b.binds.iter().copied()) {
let cell = 100 + slot * 100;
ops.extend([
Op::Create {
id: cell,
tag: Tag::Cell,
},
Op::SetProp {
id: cell,
prop: Prop::Slot(CellSlot::Item(slot)),
},
Op::Insert {
parent: 2,
child: cell,
before: None,
},
]);
ops.push(style_op(cell, &[("height", StyleValue::Number(100.0))]));
for v in 1..=40 {
ops.extend(child_view(cell + v, cell, 2.5, &[]));
}
ops.push(Op::SetProp {
id: cell,
prop: Prop::CellIndex(index),
});
}
apply(&mut c, ops);
c.commit().unwrap();
let &(key, view) = c.pace.waiting.last().expect("views wait");
let parent = c.nodes[c.nodes[key as usize].parent as usize].id;
(c, view, parent)
}
/// Commits until nothing waits; `view` is never made.
fn drain_paced_without(c: &mut Core<FakeEngine>, view: NodeId) {
for _ in 0..200 {
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&view));
if !c.has_paced_mounts() {
return;
}
}
panic!("views still wait");
}
#[test]
fn a_scroll_view_in_a_list_cell_makes_its_content_when_the_cell_is_placed() {
// A chat row with a code block: a cell holding a scroll view, which
// culls its content (`cull.rs`). The list gives the scroll view its
// frame as it places the cell, after culling looked at it in that
// round. Nothing lays the row out or scrolls again: its content is
// made all the same (it stayed empty until the next layout, as after
// a fling that ends on the row).
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(100.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(2),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
c.take_paced_list_binds(usize::MAX, &mut binds);
let mut ops = Vec::new();
let mut contents = Vec::new();
for (slot, index) in binds.iter().flat_map(|b| b.binds.iter().copied()) {
let cell = 100 + slot * 100;
let (scroll, content) = (cell + 1, cell + 2);
contents.push(content);
ops.extend([
Op::Create {
id: cell,
tag: Tag::Cell,
},
Op::SetProp {
id: cell,
prop: Prop::Slot(CellSlot::Item(slot)),
},
Op::Insert {
parent: 2,
child: cell,
before: None,
},
Op::Create {
id: scroll,
tag: Tag::Scroll,
},
style_op(scroll, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: cell,
child: scroll,
before: None,
},
]);
ops.extend(child_view(content, scroll, 40.0, &[]));
ops.push(Op::SetProp {
id: cell,
prop: Prop::CellIndex(index),
});
}
assert_eq!(contents.len(), 2);
apply(&mut c, ops);
let mut made = Vec::new();
for _ in 0..20 {
let Some(batch) = c.commit() else { break };
made.extend(created_in(&batch));
}
for content in contents {
assert!(
made.contains(&content),
"the content of the scroll view in a cell: {content}"
);
}
}
#[test]
fn a_waiting_view_taken_out_of_its_parent_is_not_made() {
// A view that waits, out of sight, is taken out of its parent and kept
// (a kept screen, a view moved later): it has no parent when the
// waiting views are made. It stays unmade, and the engine goes on
// (indexing its parent panicked the engine thread, every handler of
// the app with it).
let (mut c, view, parent) = paced_cells();
c.apply(Op::Remove {
parent,
child: view,
})
.unwrap();
drain_paced_without(&mut c, view);
// Put back, it is made.
c.apply(Op::Insert {
parent,
child: view,
before: None,
})
.unwrap();
let mut made = false;
for _ in 0..20 {
let Some(batch) = c.commit() else { break };
made |= created_in(&batch).contains(&view);
}
assert!(made);
}
#[test]
fn a_waiting_view_whose_parent_is_released_is_not_made() {
// Its parent goes, released before it: the view is an orphan until its
// own release comes.
let (mut c, view, parent) = paced_cells();
apply(
&mut c,
vec![
Op::Remove {
parent: 2,
child: parent,
},
Op::Release { id: parent },
],
);
drain_paced_without(&mut c, view);
}
#[test]
fn content_culling_turned_back_on_gives_up_far_rows() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// Rows of 50 in a wrapper: 0..2000.
ops.extend(child_view(4, 2, 2000.0, &[]));
for i in 0..40u32 {
ops.extend(child_view(10 + 2 * i, 4, 50.0, &[]));
}
apply(&mut c, ops);
let made = created_in(&c.commit().unwrap());
assert!(!made.contains(&(10 + 2 * 39)), "{made:?}");
// Off (a long screenshot): every row is made.
c.set_content_culling(false);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&(10 + 2 * 39)), "{made:?}");
// On again, still at the top: the rows more than three viewports
// below (from 400) go, those near stay.
c.set_content_culling(true);
let batch = c.commit().unwrap();
let deleted: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Delete { id } => Some(*id),
_ => None,
})
.collect();
assert!(deleted.contains(&(10 + 2 * 39)), "{deleted:?}");
assert!(!deleted.contains(&(10 + 2 * 7)), "{deleted:?}");
// And come back as it scrolls to them.
c.set_scroll_offset(2, point(Points::ZERO, Points(1900.0)), 0);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&(10 + 2 * 39)), "{made:?}");
}
/// A scroll view of height 100 holding `rows` rows of `height` points in a
/// wrapper (id 4), the rows' ids `10 + 2 * i`, committed (and what waits
/// made) at the top.
fn culled_rows(rows: u32, height: f32) -> Core<FakeEngine> {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, rows as f32 * height, &[]));
for i in 0..rows {
ops.extend(child_view(10 + 2 * i, 4, height, &[]));
}
apply(&mut c, ops);
for _ in 0..200 {
c.commit();
if !c.has_paced_mounts() {
break;
}
}
c
}
#[test]
fn a_fast_scroll_makes_its_content_ahead_by_its_steps() {
let row = |i: u32| 10 + 2 * i;
// Rows of 50 under a viewport of 100.
let mut c = culled_rows(80, 50.0);
// The user scrolls 200 down: a frame later the platform has moved as
// far again, and the next. The window reaches three steps further
// than the viewport and its overscan, to 1000.
c.set_scroll_offset(2, point(Points::ZERO, Points(200.0)), 0);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&row(19)), "{made:?}");
assert!(!made.contains(&row(20)), "{made:?}");
// A jump (a step of more than eight viewports, a scroll bar dragged
// across) reaches no further than the overscan: to 2200.
c.set_scroll_offset(2, point(Points::ZERO, Points(2000.0)), 0);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&row(43)), "{made:?}");
assert!(!made.contains(&row(44)), "{made:?}");
// Up: the window reaches up, from 1800 - 100 - 3 * 200.
c.set_scroll_offset(2, point(Points::ZERO, Points(1800.0)), 0);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&row(22)), "{made:?}");
assert!(!made.contains(&row(21)), "{made:?}");
}
#[test]
fn a_scroll_the_core_sent_makes_nothing_ahead() {
let row = |i: u32| 10 + 2 * i;
let mut c = culled_rows(80, 50.0);
// The core scrolls to 200 (its first issued scroll), and the platform
// reports it applied: a jump, not the user's motion.
c.apply(Op::Command {
id: 2,
command: Command::ScrollTo {
x: px(0.0),
y: px(200.0),
animated: false,
},
})
.unwrap();
c.commit();
c.set_scroll_offset(2, point(Points::ZERO, Points(200.0)), 1);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&row(7)), "{made:?}");
assert!(!made.contains(&row(8)), "{made:?}");
}
#[test]
fn where_a_fast_scroll_goes_next_is_made_at_once() {
let row = |i: u32| 10 + 2 * i;
// Rows of 2: the views past the viewport are many, and wait for the
// turn's budget (`pace.rs`), nearest first.
let mut c = culled_rows(1000, 2.0);
// Scrolled 200 down: the next step's rows (to 500) show in the next
// frame and are made at once; those further (to 1000) wait.
c.set_scroll_offset(2, point(Points::ZERO, Points(200.0)), 0);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&row(249)), "{made:?}");
assert!(!made.contains(&row(499)), "{made:?}");
}
#[test]
fn culled_text_is_estimated_and_measured_once_it_comes_near() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for i in 0..60u32 {
let id = 10 + 2 * i;
ops.extend([
Op::Create { id, tag: Tag::Text },
Op::CreateText {
id: id + 1,
text: format!("Row {i}"),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
// Only the texts near the viewport (0..100, a viewport around it) are
// measured by the engine; the rest are estimated.
let made = created_in(&batch).len() - 1;
assert!(made < 30, "{made} texts made");
let measured = c.text_engine.measures.get() as usize;
assert!(measured < 40, "{measured} of 60 measured");
// What is made is laid out at its measured size, 16 a line.
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 0.0, 320.0, 16.0)));
assert_eq!(frame_of(&batch, 12), Some(rect(0.0, 16.0, 320.0, 16.0)));
// Scrolled to the end: the texts there are measured as they come.
c.set_scroll_offset(2, point(Points::ZERO, Points(900.0)), 0);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&(10 + 2 * 59)));
assert_eq!(
frame_of(&batch, 10 + 2 * 59).map(|f| f.size.height),
Some(Points(16.0))
);
}
/// The rows JS is asked to render (`$rows`), in order.
fn asked_rows<M: TextEngine>(c: &mut Core<M>) -> Vec<NodeId> {
js_events(c)
.into_iter()
.filter_map(|(_, _, payload)| match payload {
EventPayload::Native { name, data } if &*name == "$rows" => {
Some(serde_json::from_value::<Vec<NodeId>>(data).unwrap())
}
_ => None,
})
.flatten()
.collect()
}
/// A scroll view 100 high (2) holding ten rows of 50 (10, 12, ...) and
/// then `count` placeholders of rows not rendered yet (100, 102, ...).
fn rows_and_placeholders(count: u32) -> Vec<Op> {
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for i in 0..10u32 {
ops.extend(child_view(10 + 2 * i, 2, 50.0, &[]));
}
for i in 0..count {
let id = 100 + 2 * i;
ops.extend([
Op::Create { id, tag: Tag::View },
Op::Placeholder { id },
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
ops
}
#[test]
fn placeholders_ask_for_their_rows_as_they_come_near() {
let mut c = core();
apply(&mut c, rows_and_placeholders(100));
let batch = c.commit().unwrap();
// The rows rendered fill the viewport and the one around it: no row
// is asked for, and no placeholder gets a view.
assert_eq!(asked_rows(&mut c), Vec::<NodeId>::new());
assert!(created_in(&batch).iter().all(|&id| id < 100));
// Placeholders are sized like the rows rendered beside them.
assert_eq!(c.measure(100).unwrap().frame, rect(0.0, 500.0, 320.0, 50.0));
assert_eq!(
c.measure(100 + 2 * 99).unwrap().frame,
rect(0.0, 500.0 + 99.0 * 50.0, 320.0, 50.0)
);
// Scrolled to 600 in one step: the placeholders within a viewport of
// it (500 to 800), and as far past it as the scroll's next steps go
// (eight viewports at most: to 1600), ask for their rows, once, with
// no view.
c.set_scroll_offset(2, point(Points::ZERO, Points(600.0)), 0);
let batch = c.commit();
assert!(
batch
.as_ref()
.is_none_or(|b| created_in(b).iter().all(|&id| id < 100))
);
assert_eq!(
asked_rows(&mut c),
(100..=142).step_by(2).collect::<Vec<NodeId>>()
);
c.set_scroll_offset(2, point(Points::ZERO, Points(590.0)), 0);
c.commit();
assert_eq!(asked_rows(&mut c), Vec::<NodeId>::new());
}
#[test]
fn a_row_replacing_its_placeholder_keeps_the_scroll_view_where_it_is() {
let mut c = core();
apply(&mut c, rows_and_placeholders(100));
c.commit();
c.set_scroll_offset(2, point(Points::ZERO, Points(600.0)), 0);
c.commit();
assert_eq!(asked_rows(&mut c)[0], 100);
// The first one's row, 80 high instead of 50, above the viewport.
let mut ops = child_view(1000, 2, 80.0, &[]);
ops.pop();
ops.extend([
Op::Insert {
parent: 2,
child: 1000,
before: Some(100),
},
Op::Remove {
parent: 2,
child: 100,
},
Op::Release { id: 100 },
]);
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&1000));
assert_eq!(frame_of(&batch, 1000), Some(rect(0.0, 500.0, 320.0, 80.0)));
// What showed stays in place: the scroll view goes down by 30.
let moved: f32 = page_scrolls(&batch)
.iter()
.map(|&(to, v)| if to { v - 600.0 } else { v })
.sum();
assert_eq!(moved, 30.0);
}
#[test]
fn a_placeholder_nothing_culls_asks_for_its_row_at_once() {
// In a plain view.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
Op::Placeholder { id: 4 },
Op::Insert {
parent: 2,
child: 4,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&4));
assert_eq!(asked_rows(&mut c), [4]);
// In a scroll view, with culling off (a test driver's): all of them.
let mut c = core();
c.set_content_culling(false);
apply(&mut c, rows_and_placeholders(40));
c.commit();
assert_eq!(
asked_rows(&mut c),
(0..40).map(|i| 100 + 2 * i).collect::<Vec<_>>()
);
// Culling turned off later: the ones it held back.
let mut c = core();
apply(&mut c, rows_and_placeholders(40));
c.commit();
assert_eq!(asked_rows(&mut c), Vec::<NodeId>::new());
c.set_content_culling(false);
c.commit();
assert_eq!(asked_rows(&mut c).len(), 40);
}
#[test]
fn a_culled_view_reports_its_layout_and_is_made_for_a_command() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, 1000.0, &[]));
ops.extend(child_view(6, 2, 50.0, &[]));
ops.push(Op::Listen {
id: 6,
event: EventKind::Layout,
enabled: true,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&6));
assert_eq!(
js_events(&mut c),
vec![(
6,
EventKind::Layout,
EventPayload::Layout(rect(0.0, 1000.0, 320.0, 50.0))
)]
);
c.apply(Op::Command {
id: 6,
command: Command::Focus,
})
.unwrap();
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&6));
assert_eq!(frame_of(&batch, 6), Some(rect(0.0, 1000.0, 320.0, 50.0)));
}
/// Rows of 50 in a 100-high scroll view (2) holding a wrapper (4), each
/// row (`10 + 2 * i`) moved along y by animation node `100 + i` when
/// `moved`, else made to fade by it.
fn animated_rows(rows: u32, moved: bool) -> Vec<Op> {
use crate::{
style::{Style, StyleDecl, StylePatch},
transform::TransformKind,
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, rows as f32 * 50.0, &[]));
for i in 0..rows {
let (id, value) = (10 + 2 * i, 100 + i);
ops.push(Op::Animation(AnimationOp::CreateValue {
node: value,
value: 0.0,
}));
let mut style = Box::<Style>::default();
let mut patch = StylePatch::default();
patch
.set(&mut style, "height", StyleValue::Number(50.0))
.unwrap();
if moved {
patch
.push(
&mut style,
StyleDecl::Transform(TransformKind::TranslateY, 0.0, Some(value)),
)
.unwrap();
} else {
patch
.push(
&mut style,
StyleDecl::Animated(AnimationProp::Opacity, value),
)
.unwrap();
}
ops.extend([
Op::Create { id, tag: Tag::View },
Op::SetStyle { id, style, patch },
Op::Insert {
parent: 4,
child: id,
before: None,
},
]);
}
ops
}
fn start(value: u32, driver: crate::animation::Driver) -> Op {
Op::Animation(AnimationOp::Start {
node: value,
animation: value,
driver,
})
}
fn timing_to(to: f32) -> crate::animation::Driver {
crate::animation::Driver::Timing {
to,
duration_ms: 300.0,
easing: crate::animation::Easing::EaseOut,
delay_ms: 0.0,
frame_rate: None,
}
}
#[test]
fn a_view_sliding_in_a_little_waits_out_of_reach_like_any_other() {
// A page whose rows slide 14pt up into place as they appear (a
// gallery section's `Appear`): only the rows near the viewport, their
// rectangles widened by the slide, are made, not the whole page.
let mut c = core();
let mut ops = animated_rows(40, true);
for i in 0..40 {
ops.push(start(100 + i, timing_to(14.0)));
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let made = created_in(&batch);
// The window is the viewport (0..100) and one around it (to 200): row
// 4 (200..250) slides as high as 186, row 5 (250..) never reaches it.
assert!(made.contains(&(10 + 2 * 4)), "{made:?}");
assert!(!made.contains(&(10 + 2 * 5)), "{made:?}");
assert!(!made.contains(&(10 + 2 * 39)));
// The page keeps its whole length all the same.
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::ScrollContent { id: 2, size } if size.height == px(2000.0)
)));
assert_eq!(
c.measure(10 + 2 * 30).unwrap().frame.origin.y,
Points(1500.0)
);
// Scrolled down, the rows there come.
c.set_scroll_offset(2, point(Points::ZERO, Points(1000.0)), 0);
let batch = c.commit().unwrap();
let made = created_in(&batch);
assert!(made.contains(&(10 + 2 * 20)), "{made:?}");
assert!(made.contains(&(10 + 2 * 23)), "{made:?}");
}
#[test]
fn a_culled_view_comes_when_its_animation_reaches_further() {
let mut c = core();
let mut ops = animated_rows(40, true);
ops.push(start(100 + 10, timing_to(14.0)));
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&(10 + 2 * 10)));
// Row 10 (500..550) is sent 400pt up, into the viewport: it is made in
// the commit that starts the animation, before it can show.
apply(&mut c, vec![start(100 + 10, timing_to(-400.0))]);
let batch = c.commit().unwrap();
let made = created_in(&batch);
assert!(made.contains(&(10 + 2 * 10)), "{made:?}");
assert!(!made.contains(&(10 + 2 * 11)), "{made:?}");
}
#[test]
fn a_view_moved_without_a_bound_is_made_with_its_parent() {
// A fling with no bounds may take a row anywhere: it is made wherever
// it is, as every transformed view used to be.
let mut c = core();
let mut ops = animated_rows(40, true);
ops.push(start(
100 + 30,
crate::animation::Driver::Decay {
velocity: Some(2000.0),
deceleration: 0.998,
clamp: None,
bounce: 0.0,
frame_rate: None,
},
));
apply(&mut c, ops);
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&(10 + 2 * 30)), "{made:?}");
assert!(!made.contains(&(10 + 2 * 29)), "{made:?}");
}
#[test]
fn what_a_sticky_view_holds_is_made_wherever_it_sticks() {
// A sticky view shows away from its frame, as far as its scroll view
// scrolls: what it holds is made with it, and stays while it sticks.
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// A header sticking to the top, 3000 of content, a bar sticking to the
// bottom (its frame at 3040, far below the viewport and its overscan),
// then 3000 more. Each holds a view.
ops.extend(child_view(
3,
2,
40.0,
&[
("position", StyleValue::Str("sticky")),
("top", StyleValue::Number(0.0)),
],
));
ops.extend(child_view(4, 3, 20.0, &[]));
ops.extend(child_view(5, 2, 3000.0, &[]));
ops.extend(child_view(
6,
2,
40.0,
&[
("position", StyleValue::Str("sticky")),
("bottom", StyleValue::Number(0.0)),
],
));
ops.extend(child_view(7, 6, 20.0, &[]));
ops.extend(child_view(8, 2, 3000.0, &[]));
apply(&mut c, ops);
// The bar sticks at the bottom of the viewport: its content is made.
let made = created_in(&c.commit().unwrap());
assert!(made.contains(&6) && made.contains(&7), "{made:?}");
// Scrolled past the bar, far below the header's frame: the header
// sticks at the top, its content is not given up.
c.set_scroll_offset(2, point(Points::ZERO, Points(5000.0)), 0);
let batch = c.commit().unwrap();
let deleted: Vec<NodeId> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Delete { id } => Some(*id),
_ => None,
})
.collect();
assert!(
!deleted.contains(&3) && !deleted.contains(&4),
"{deleted:?}"
);
}
#[test]
fn a_fading_view_is_culled_as_a_still_one() {
// An animated opacity moves nothing.
let mut c = core();
apply(&mut c, animated_rows(40, false));
let mut made = created_in(&c.commit().unwrap());
assert!(made.contains(&(10 + 2 * 3)), "{made:?}");
assert!(!made.contains(&(10 + 2 * 4)), "{made:?}");
// Every row comes once culling is off (a test driver): the rest in the
// commits after.
c.set_content_culling(false);
while let Some(batch) = c.commit() {
made.extend(created_in(&batch));
}
assert!((0..40).all(|i| made.contains(&(10 + 2 * i))), "{made:?}");
}
#[test]
fn a_visible_scroll_mounts_only_its_nondefault_behavior_once() {
use crate::ops::ScrollProp;
for configured in [false, true] {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
if configured {
ops.push(Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::MinZoom(0.5)),
});
}
apply(&mut c, ops);
for remount in [false, true] {
if remount {
c.remount();
}
let batch = c.commit().unwrap();
assert_eq!(created_in(&batch).contains(&2), !remount);
let behaviors: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::ScrollBehavior { id: 2, behavior } => Some(behavior.as_ref()),
_ => None,
})
.collect();
assert_eq!(behaviors.len(), usize::from(configured));
if configured {
assert_eq!(behaviors[0].min_zoom, 0.5);
}
assert!(c.commit().is_none());
}
}
}
#[test]
fn a_culled_scroll_mounts_its_behavior_when_it_enters_the_viewport() {
use crate::ops::ScrollProp;
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, 2000.0, &[]));
ops.extend([
Op::Create {
id: 6,
tag: Tag::Scroll,
},
style_op(6, &[("height", StyleValue::Number(100.0))]),
Op::SetProp {
id: 6,
prop: Prop::Scroll(ScrollProp::MinZoom(0.5)),
},
Op::SetProp {
id: 6,
prop: Prop::Scroll(ScrollProp::MaxZoom(5.0)),
},
Op::SetProp {
id: 6,
prop: Prop::Scroll(ScrollProp::Paging(true)),
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
]);
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&6));
assert!(
!batch
.items
.iter()
.any(|item| matches!(item, MountItem::ScrollBehavior { .. }))
);
c.set_scroll_offset(2, point(Points::ZERO, Points(2000.0)), 0);
for remount in [false, true] {
if remount {
c.remount();
}
let batch = c.commit().unwrap();
assert_eq!(created_in(&batch).contains(&6), !remount);
let behaviors: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::ScrollBehavior { id: 6, behavior } => Some(behavior.as_ref()),
_ => None,
})
.collect();
assert_eq!(behaviors.len(), 1, "remount={remount}");
assert_eq!((behaviors[0].min_zoom, behaviors[0].max_zoom), (0.5, 5.0));
assert!(behaviors[0].paging);
assert!(c.commit().is_none());
}
}
#[test]
fn a_culled_scroll_view_made_for_a_scroll_gets_its_content_size_first() {
// A scroll view below the viewport of the one it is in is culled; a
// scroll to it (a `contentOffset` as it comes in a pager) makes it.
// Its platform view must know its content before it scrolls, or it
// clamps the offset to an empty content and stays at the top.
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, 1000.0, &[]));
ops.extend([
Op::Create {
id: 6,
tag: Tag::Scroll,
},
style_op(6, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: 2,
child: 6,
before: None,
},
]);
ops.extend(child_view(8, 6, 300.0, &[]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&6));
c.apply(Op::Command {
id: 6,
command: Command::ScrollTo {
x: Points::ZERO,
y: Points(100.0),
animated: false,
},
})
.unwrap();
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&6));
let at = |wanted: fn(&MountItem) -> bool| batch.items.iter().position(wanted);
let content = at(|i| matches!(i, MountItem::ScrollContent { id: 6, .. }))
.expect("the content size of the scroll view made");
let scroll = at(|i| {
matches!(
i,
MountItem::Command {
id: 6,
command: Command::ScrollTo { .. }
}
)
})
.expect("its scroll, in the same batch");
assert!(content < scroll, "{:?}", batch.items);
}
#[test]
fn a_dialog_in_a_scroll_view_s_content_is_made_wherever_it_opens() {
// A dialog's modal shows over everything, not at its place in the
// content: it is made beside a row in view, and in a row far down
// that is not made yet, with the views around it.
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, 50.0, &[]));
ops.extend(child_view(6, 2, 1000.0, &[]));
ops.extend(child_view(8, 2, 50.0, &[]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&4));
assert!(!created_in(&batch).contains(&8));
apply(
&mut c,
vec![
Op::Create {
id: 10,
tag: Tag::Modal,
},
Op::Insert {
parent: 4,
child: 10,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(created_in(&batch).contains(&10));
apply(
&mut c,
vec![
Op::Create {
id: 12,
tag: Tag::Modal,
},
Op::Insert {
parent: 8,
child: 12,
before: None,
},
],
);
let batch = c.commit().unwrap();
let made = created_in(&batch);
assert!(made.contains(&8) && made.contains(&12), "{made:?}");
}
#[test]
fn sticky_views_stick_in_the_viewport_of_the_scroll_view_around_them() {
let mut c = core();
let sticky = [
("position", StyleValue::Str("sticky")),
("top", StyleValue::Number(10.0)),
];
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
];
// A 100 pt header, a sticky bar of 40 sticking 10 below the top, then
// a section of 500 whose heading (0 below its top) sticks within it.
ops.extend(child_view(3, 2, 100.0, &[]));
ops.extend(child_view(4, 2, 40.0, &sticky));
ops.extend(child_view(6, 2, 500.0, &[]));
ops.extend(child_view(
7,
6,
40.0,
&[
("position", StyleValue::Str("sticky")),
("top", StyleValue::Number(0.0)),
],
));
ops.extend(child_view(8, 6, 460.0, &[]));
ops.extend(child_view(5, 2, 2000.0, &[]));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
let pinned = sticky_of(&batch, 2).expect("the scroll view's sticky views");
// The bar sticks from 90 (its 100 less 10) until its bottom meets the
// end of the content (2640); the heading from 140 until its bottom
// meets its section's end (640).
assert!(
pinned.contains(&(4, 90.0, 90.0 + 2640.0 - 140.0)),
"{pinned:?}"
);
assert!(pinned.contains(&(7, 140.0, 140.0 + 460.0)), "{pinned:?}");
// They draw above their later siblings: made in one go, the views go
// in in that order.
let order = |parent: NodeId| -> Vec<NodeId> {
let mut order: Vec<NodeId> = Vec::new();
for item in &batch.items {
if let MountItem::Insert {
parent: p,
child,
before,
} = item
&& *p == parent
{
order.retain(|c| c != child);
let at = before
.and_then(|b| order.iter().position(|&c| c == b))
.unwrap_or(order.len());
order.insert(at, *child);
}
}
order
};
assert_eq!(order(2), [3, 6, 5, 4]);
assert_eq!(order(6), [8, 7]);
// Its insets say where it sticks: it is laid out in the flow.
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 100.0, 320.0, 40.0)));
// A view added later goes below the bar (scrolled to the end, where
// it is mounted at once).
c.set_scroll_offset(2, point(Points::ZERO, Points(2240.0)), 0);
apply(&mut c, child_view(9, 2, 10.0, &[]));
let batch = c.commit().unwrap();
assert!(batch.items.iter().any(|i| matches!(
i,
MountItem::Insert {
parent: 2,
child: 9,
before: Some(4)
}
)));
// No longer sticky: the scroll view gets the heading alone.
c.apply(style_op(4, &[("height", StyleValue::Number(40.0))]))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(sticky_of(&batch, 2), Some(vec![(7, 140.0, 600.0)]));
}
#[test]
fn sticky_views_in_a_horizontal_scroll_view_stick_at_their_left() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
];
for (id, style) in [
(3, vec![("width", StyleValue::Number(50.0))]),
(
4,
vec![
("width", StyleValue::Number(30.0)),
("position", StyleValue::Str("sticky")),
("left", StyleValue::Number(0.0)),
// Not where it sticks in a horizontal scroll view.
("top", StyleValue::Number(5.0)),
],
),
(5, vec![("width", StyleValue::Number(1000.0))]),
] {
ops.extend([
Op::Create { id, tag: Tag::View },
style_op(id, &style),
Op::Insert {
parent: 2,
child: id,
before: None,
},
]);
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(sticky_of(&batch, 2), Some(vec![(4, 50.0, 1050.0)]));
}
/// How far a sticky range from `start` to `end` moves at `offset`.
fn sticky_shift_at(start: f32, end: f32, offset: f32) -> f32 {
crate::scroll::sticky_shift(Points(offset), Points(start), Points(end)).0
}
/// A 400 pt scroll view: a 100 pt header, 1000 pt of content, and a 40 pt
/// footer at 1100 whose style is `footer`.
fn scroll_with_footer(c: &mut Core<FakeEngine>, footer: &[(&str, StyleValue<'_>)]) -> MountBatch {
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
];
ops.extend(child_view(3, 2, 100.0, &[]));
ops.extend(child_view(4, 2, 1000.0, &[]));
ops.extend(child_view(5, 2, 40.0, footer));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(c, ops);
c.commit().unwrap()
}
#[test]
fn a_bottom_sticky_footer_stays_at_the_viewport_bottom() {
let mut c = core();
let batch = scroll_with_footer(
&mut c,
&[
("position", StyleValue::Str("sticky")),
("bottom", StyleValue::Number(0.0)),
],
);
// Its place at 1100 is below the viewport: it is held at 360 (the
// viewport's end less its height), never before its containing block's
// start at 0.
assert_eq!(sticky_of(&batch, 2), Some(vec![(5, 740.0, -360.0)]));
assert_eq!(1100.0 + sticky_shift_at(740.0, -360.0, 0.0), 360.0);
assert_eq!(1100.0 + sticky_shift_at(740.0, -360.0, 300.0), 660.0);
}
#[test]
fn a_bottom_sticky_footer_stays_at_its_place_once_scrolled_to() {
let mut c = core();
let batch = scroll_with_footer(
&mut c,
&[
("position", StyleValue::Str("sticky")),
("bottom", StyleValue::Number(0.0)),
],
);
// Scrolled to its place, and past it, it stays where it is laid out.
assert_eq!(sticky_of(&batch, 2), Some(vec![(5, 740.0, -360.0)]));
assert_eq!(sticky_shift_at(740.0, -360.0, 740.0), 0.0);
assert_eq!(sticky_shift_at(740.0, -360.0, 900.0), 0.0);
}
#[test]
fn a_bottom_sticky_footer_keeps_its_inset_from_the_viewport_bottom() {
let mut c = core();
let batch = scroll_with_footer(
&mut c,
&[
("position", StyleValue::Str("sticky")),
("bottom", StyleValue::Number(12.0)),
],
);
// The same, 12 pt above the viewport's end: 348 for a 40 pt footer.
assert_eq!(sticky_of(&batch, 2), Some(vec![(5, 752.0, -348.0)]));
assert_eq!(1100.0 + sticky_shift_at(752.0, -348.0, 0.0), 348.0);
}
#[test]
fn a_bottom_sticky_footer_never_leaves_its_parent() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
];
ops.extend(child_view(3, 2, 500.0, &[]));
// A 2000 pt parent at 500, its footer at 1060.
ops.extend(child_view(4, 2, 2000.0, &[]));
ops.extend(child_view(6, 4, 560.0, &[]));
ops.extend(child_view(
5,
4,
40.0,
&[
("position", StyleValue::Str("sticky")),
("bottom", StyleValue::Number(0.0)),
],
));
ops.extend(child_view(7, 4, 1400.0, &[]));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
// Held at the viewport's bottom, 360, it would be above its parent at
// 500: it stops at the parent's start.
assert_eq!(sticky_of(&batch, 2), Some(vec![(5, 700.0, 140.0)]));
assert_eq!(1060.0 + sticky_shift_at(700.0, 140.0, 0.0), 500.0);
}
#[test]
fn a_right_sticky_column_stays_at_the_viewport_right() {
let mut c = core();
let ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("width", StyleValue::Number(50.0))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("width", StyleValue::Number(700.0))]),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(
5,
&[
("width", StyleValue::Number(30.0)),
("position", StyleValue::Str("sticky")),
("right", StyleValue::Number(0.0)),
],
),
Op::Insert {
parent: 2,
child: 5,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
apply(&mut c, ops);
let batch = c.commit().unwrap();
// At 750 in a 320 pt viewport, it is held at 290 (the viewport's end
// less its width), never before its containing block's start at 0.
assert_eq!(sticky_of(&batch, 2), Some(vec![(5, 460.0, -290.0)]));
assert_eq!(750.0 + sticky_shift_at(460.0, -290.0, 0.0), 290.0);
}
#[test]
fn top_wins_over_bottom_on_a_sticky_view() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
];
ops.extend(child_view(3, 2, 100.0, &[]));
ops.extend(child_view(
4,
2,
40.0,
&[
("position", StyleValue::Str("sticky")),
("top", StyleValue::Number(10.0)),
("bottom", StyleValue::Number(20.0)),
],
));
ops.extend(child_view(5, 2, 2000.0, &[]));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
// The top inset's range, as without the bottom inset.
assert_eq!(sticky_of(&batch, 2), Some(vec![(4, 90.0, 2090.0)]));
}
/// The animated offsets of the sticky cells sent to view `id` in `batch`.
fn sticky_offsets_of(batch: &MountBatch, id: NodeId) -> Option<Vec<(NodeId, Option<u32>)>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::StickyCells { id: v, cells } if *v == id => {
Some(cells.iter().map(|c| (c.cell, c.offset)).collect())
}
_ => None,
})
}
#[test]
fn page_lists_stick_below_an_animated_offset() {
let mut c = core();
page(&mut c, 100.0, &[20]);
apply(
&mut c,
vec![
Op::Animation(AnimationOp::CreateValue {
node: 2,
value: 56.0,
}),
Op::SetProp {
id: 4,
prop: Prop::StickyIndices(vec![0, 10]),
},
Op::SetProp {
id: 4,
prop: Prop::StickyOffsetNode(Some(2)),
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
let batch = c.commit().unwrap();
// The ranges are the list's as without an offset (the platforms add
// the value), and each cell carries the value's node.
let row0 = cells[bound_slot(&c, 4, 0) as usize];
assert!(
sticky_of(&batch, 2)
.unwrap()
.contains(&(row0, 100.0, 550.0))
);
assert!(
sticky_offsets_of(&batch, 2)
.unwrap()
.iter()
.all(|&(_, n)| n == Some(2))
);
// A number again: no node.
c.apply(Op::SetProp {
id: 4,
prop: Prop::StickyOffset(px(8.0)),
})
.unwrap();
let batch = c.commit().unwrap();
assert!(
sticky_offsets_of(&batch, 2)
.unwrap()
.iter()
.all(|&(_, n)| n.is_none())
);
assert!(sticky_of(&batch, 2).unwrap().contains(&(row0, 92.0, 542.0)));
}
#[test]
fn sticky_views_stick_at_an_animated_top() {
let mut c = core();
let mut ops = vec![
Op::Animation(AnimationOp::CreateValue {
node: 2,
value: 40.0,
}),
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
];
ops.extend(child_view(3, 2, 100.0, &[]));
let mut style = Box::<Style>::default();
let mut patch = StylePatch::default();
patch
.set(&mut style, "position", StyleValue::Str("sticky"))
.unwrap();
patch
.set(&mut style, "height", StyleValue::Number(30.0))
.unwrap();
style.animated.push((AnimationProp::StickyTop, 2));
ops.extend([
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetStyle {
id: 4,
style,
patch,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
]);
ops.extend(child_view(5, 2, 1000.0, &[]));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
// It sticks from its place (the value added by the platforms), and the
// value is the scroll view's, never the view's own binding.
assert_eq!(sticky_of(&batch, 2), Some(vec![(4, 100.0, 1100.0)]));
assert_eq!(sticky_offsets_of(&batch, 2), Some(vec![(4, Some(2))]));
assert!(!batch.items.iter().any(|i| matches!(
i,
MountItem::AnimationBindings { id: 4, bindings } if !bindings.is_empty()
)));
}
#[test]
fn an_animated_inset_across_the_scroll_axis_is_ignored() {
let mut c = core();
let mut ops = vec![
Op::Animation(AnimationOp::CreateValue {
node: 2,
value: 40.0,
}),
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
];
ops.extend(child_view(3, 2, 100.0, &[]));
let mut style = Box::<Style>::default();
let mut patch = StylePatch::default();
patch
.set(&mut style, "position", StyleValue::Str("sticky"))
.unwrap();
patch
.set(&mut style, "height", StyleValue::Number(30.0))
.unwrap();
// `left` in a vertical scroll view: it sticks nowhere.
style.animated.push((AnimationProp::StickyLeft, 2));
ops.extend([
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetStyle {
id: 4,
style,
patch,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
]);
ops.extend(child_view(5, 2, 1000.0, &[]));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(sticky_of(&batch, 2).is_none_or(|cells| cells.is_empty()));
}
#[test]
fn a_relayout_boundary_that_overflows_more_lays_its_parent_out_again() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(200.0))]),
Op::Create {
id: 3,
tag: Tag::View,
},
// A size of fixed points that does not shrink: a change inside
// cannot change it.
style_op(
3,
&[
("width", StyleValue::Number(100.0)),
("height", StyleValue::Number(50.0)),
("flexShrink", StyleValue::Number(0.0)),
],
),
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("height", StyleValue::Number(10.0))]),
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
// Within the box: its parent's layout stands.
apply(
&mut c,
vec![style_op(4, &[("height", StyleValue::Number(40.0))])],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 4).unwrap().size.height, px(40.0));
assert!(frame_of(&batch, 3).is_none());
// Out of it: the scroll view's content takes the overflow.
apply(
&mut c,
vec![style_op(4, &[("height", StyleValue::Number(500.0))])],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 4).unwrap().size.height, px(500.0));
let content = batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(size.height.0),
_ => None,
});
assert_eq!(content, Some(500.0));
}
/// A view in `parent` styled `props`.
fn styled_view(id: NodeId, parent: NodeId, props: &[(&str, StyleValue<'_>)]) -> Vec<Op> {
vec![
Op::Create { id, tag: Tag::View },
style_op(id, props),
Op::Insert {
parent,
child: id,
before: None,
},
]
}
/// Layouts are cached without the sides of their parent's size they do not
/// read (`layout_tree::reads_parent`), and follow those they do: a box at
/// most, and one at least, half the height of its block parent as only that
/// height changes (a block gives its children no height of their own), and
/// a box padded by a tenth of its parent's width, at a width of its own, as
/// only that width does.
#[test]
fn layouts_follow_the_parent_sizes_their_percentages_read() {
use StyleValue::{Number, Str};
let mut c = core();
let block = |height: f32| style_op(2, &[("display", Str("block")), ("height", Number(height))]);
let column = |width: f32| {
style_op(
6,
&[("width", Number(width)), ("alignItems", Str("flex-start"))],
)
};
let mut ops = styled_view(2, ROOT_ID, &[]);
ops.push(block(100.0));
ops.extend(styled_view(3, 2, &[("maxHeight", Str("50%"))]));
ops.extend(styled_view(4, 3, &[("height", Number(150.0))]));
ops.extend(styled_view(5, 2, &[("minHeight", Str("50%"))]));
ops.extend(styled_view(6, ROOT_ID, &[]));
ops.push(column(300.0));
ops.extend(styled_view(
7,
6,
&[
("width", Number(100.0)),
("height", Number(20.0)),
("paddingLeft", Str("10%")),
],
));
ops.extend(styled_view(8, 7, &[("height", Number(10.0))]));
apply(&mut c, ops);
c.commit();
let frame = |c: &Core<FakeEngine>, id: NodeId| c.nodes[c.key(id).unwrap() as usize].frame;
assert_eq!(frame(&c, 3).size.height, px(50.0));
assert_eq!(frame(&c, 5).size.height, px(50.0));
assert_eq!(frame(&c, 8).origin.x, px(30.0));
apply(&mut c, vec![block(200.0), column(400.0)]);
c.commit();
assert_eq!(frame(&c, 3).size.height, px(100.0));
assert_eq!(frame(&c, 5).size.height, px(100.0));
assert_eq!(frame(&c, 8).origin.x, px(40.0));
}
/// A column whose height changes as a row in it grows (a text a scroll view
/// makes, measured for real) lays that row out again, not the others: their
/// layouts are cached without their parent's height, which they do not
/// read. Four times the rows, the same work.
#[test]
fn rows_keep_their_layouts_as_their_column_grows() {
let work = |rows: u32| {
let mut c = core();
let mut ops = styled_view(2, ROOT_ID, &[]);
for i in 0..rows {
let (row, inner) = (10 + 2 * i, 11 + 2 * i);
ops.extend(styled_view(row, 2, &[]));
ops.extend(styled_view(
inner,
row,
&[("height", StyleValue::Number(20.0))],
));
}
apply(&mut c, ops);
c.commit();
c.layout.computed = 0;
apply(
&mut c,
vec![style_op(11, &[("height", StyleValue::Number(30.0))])],
);
c.commit();
assert_eq!(
c.nodes[c.key(12).unwrap() as usize].frame.origin.y,
px(30.0)
);
c.layout.computed
};
let (few, many) = (work(100), work(400));
assert!(
many <= few + 4,
"{few} layouts computed for 100 rows, {many} for 400"
);
}
#[test]
fn a_text_that_measures_as_before_lays_nothing_out_again() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("flexDirection", StyleValue::Str("row"))]),
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 5,
text: "9.07".into(),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(
6,
&[
("width", StyleValue::Number(10.0)),
("height", StyleValue::Number(10.0)),
],
),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let first = c.commit().unwrap();
let after = frame_of(&first, 6).unwrap().origin.x;
let root = c.nodes[c.root as usize].layout.unwrap();
// As wide as before (the tests' engine gives each character one width):
// nothing to lay out again, the text mounted again.
c.apply(Op::SetText {
id: 5,
text: "9.14".into(),
})
.unwrap();
c.flush_dirty();
assert!(!c.needs_layout && !c.layout.dirty(root));
let batch = c.commit().unwrap();
assert!(
matches!(&batch.items[..], [MountItem::Text { id: 4, text, .. }] if text.text == "9.14")
);
// Wider: laid out again, and its sibling moves.
c.apply(Op::SetText {
id: 5,
text: "+9.21".into(),
})
.unwrap();
c.flush_dirty();
assert!(c.needs_layout && c.layout.dirty(root));
let batch = c.commit().unwrap();
assert!(frame_of(&batch, 4).is_some());
assert!(frame_of(&batch, 6).unwrap().origin.x > after);
}
#[test]
fn a_videos_fit_is_its_object_fit_unless_rust_sets_one() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Video,
},
style_op(2, &[("objectFit", StyleValue::Str("cover"))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let fit = |batch: MountBatch| {
batch.items.iter().rev().find_map(|item| match item {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::Video(v),
} => Some(v.resize_mode),
_ => None,
})
};
assert_eq!(fit(c.commit().unwrap()), Some(ResizeMode::Cover));
apply(
&mut c,
vec![style_op(2, &[("objectFit", StyleValue::Str("none"))])],
);
assert_eq!(fit(c.commit().unwrap()), Some(ResizeMode::Center));
}
#[test]
fn audio_session_reaches_the_video() {
// A lesson's speech plays in silent mode: the prop reaches the
// platform's player.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Video,
},
Op::SetProp {
id: 2,
prop: Prop::Native(crate::NativeProp::AudioSession(
crate::AudioSession::Playback,
)),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let items = c.commit().unwrap();
let props = items
.items
.iter()
.find_map(|item| match item {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::Video(v),
} => Some(v),
_ => None,
})
.expect("the video's props");
assert_eq!(props.audio_session, crate::AudioSession::Playback);
}
#[test]
fn a_videos_poster_reaches_the_platform() {
// The image shown until the video's first frame is ready is the app's,
// not a platform extra.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Video,
},
Op::SetProp {
id: 2,
prop: Prop::Native(crate::NativeProp::Poster(Some(
"https://example.com/poster.png".into(),
))),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let items = c.commit().unwrap();
let props = items
.items
.iter()
.find_map(|item| match item {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::Video(v),
} => Some(v),
_ => None,
})
.expect("the video's props");
assert_eq!(
props.poster.as_deref(),
Some("https://example.com/poster.png")
);
}
#[test]
fn span_test_ids_reuse_fitted_and_hidden_layouts() {
for (fit, hidden) in [(true, false), (false, true)] {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
style_op(
2,
&[
("width", StyleValue::Number(30.0)),
("height", StyleValue::Number(16.0)),
("fontSize", StyleValue::Number(20.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::AdjustsFontSizeToFit(fit),
},
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 6,
text: "long enough to shrink".into(),
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
if hidden {
ops.push(style_op(2, &[("display", StyleValue::Str("none"))]));
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let (old_text, old_layout) = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text {
id: 2,
text,
layout,
..
} => Some((text.clone(), layout.clone())),
_ => None,
})
.unwrap();
let counts = (
c.text_engine.prepares.get(),
c.text_engine.layouts.get(),
c.text_engine.measures.get(),
);
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::TestId(Some("cached".into())),
}],
);
let batch = c.commit().unwrap();
let (text, layout) = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Text {
id: 2,
text,
layout,
..
} => Some((text, layout)),
_ => None,
})
.unwrap();
assert_eq!(text.test_ids[0].test_id.as_ref(), "cached");
assert_eq!(
text.spans, old_text.spans,
"keep the actual drawn font size"
);
assert!(Arc::ptr_eq(&old_layout.0, &layout.0));
assert_eq!(
(
c.text_engine.prepares.get(),
c.text_engine.layouts.get(),
c.text_engine.measures.get()
),
counts
);
}
}
#[test]
fn a_links_href_reaches_the_spans_a_fitted_text_draws() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
style_op(
2,
&[
("width", StyleValue::Number(30.0)),
("height", StyleValue::Number(16.0)),
("fontSize", StyleValue::Number(20.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::AdjustsFontSizeToFit(true),
},
// A link: a span taking presses.
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::Listen {
id: 4,
event: EventKind::Press,
enabled: true,
},
Op::CreateText {
id: 6,
text: "long enough to shrink".into(),
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let text_of = |batch: &MountBatch| {
batch.items.iter().find_map(|i| match i {
MountItem::Text {
id: 2,
text,
layout,
..
} => Some((text.clone(), layout.clone())),
_ => None,
})
};
let (old_text, old_layout) = text_of(&c.commit().unwrap()).unwrap();
assert_eq!(old_text.links.len(), 1);
assert_eq!(old_text.link_hrefs, []);
let counts = (
c.text_engine.prepares.get(),
c.text_engine.layouts.get(),
c.text_engine.measures.get(),
);
// Its `href` given: the drawn (shrunk) spans take it, as they take a
// test id, laid out as they were.
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::Href(Some("https://example.com/fitted".into())),
}],
);
let (text, layout) = text_of(&c.commit().unwrap()).unwrap();
assert_eq!(text.link_href(0), Some("https://example.com/fitted"));
assert_eq!(
text.spans, old_text.spans,
"keep the actual drawn font size"
);
assert!(Arc::ptr_eq(&old_layout.0, &layout.0));
assert_eq!(
(
c.text_engine.prepares.get(),
c.text_engine.layouts.get(),
c.text_engine.measures.get()
),
counts
);
}
/// What a node's `env()` terms came to: its padding and margin insets.
fn env_applied(c: &Core<FakeEngine>, id: NodeId) -> [EdgeInsets; 2] {
let key = c.key(id).unwrap();
c.nodes[key as usize]
.env
.as_deref()
.map(|(_, applied)| *applied)
.unwrap_or_default()
}
fn env_with_keyboard(height: f32, duration: f32) -> crate::element::Environment {
crate::element::Environment {
window: size_pt(320.0, 480.0),
keyboard_height: px(height),
keyboard_duration: duration,
..Default::default()
}
}
#[test]
fn keyboard_inset_height_pads_and_animates_with_the_keyboard() {
let mut c = core();
c.set_environment(env_with_keyboard(0.0, 250.0));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(
2,
&[
("height", StyleValue::Number(100.0)),
(
"paddingBottom",
StyleValue::Str("env(keyboard-inset-height)"),
),
],
),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("flex", StyleValue::Number(1.0))]),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).map(|f| f.size.height.0), Some(100.0));
assert!(!matches!(batch.items[0], MountItem::LayoutAnimation(_)));
// The keyboard shows: the padding follows, animated with its curve.
c.set_environment(env_with_keyboard(40.0, 250.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).map(|f| f.size.height.0), Some(60.0));
assert!(
matches!(
&batch.items[0],
MountItem::LayoutAnimation(crate::LayoutAnimation {
update: Some(t), .. }) if t.curve == crate::LayoutCurve::Keyboard && t.duration_ms == 250.0
),
"{:?}",
batch.items
);
assert_eq!(env_applied(&c, 2)[0].bottom, px(40.0));
// Without a duration it moves at once.
c.set_environment(env_with_keyboard(0.0, 0.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).map(|f| f.size.height.0), Some(100.0));
assert!(!matches!(batch.items[0], MountItem::LayoutAnimation(_)));
// A plain value replaces the term: the keyboard no longer moves it.
apply(
&mut c,
vec![style_op(
2,
&[
("height", StyleValue::Number(100.0)),
("paddingBottom", StyleValue::Number(10.0)),
],
)],
);
c.commit();
assert!(c.env_styled.is_empty());
c.set_environment(env_with_keyboard(40.0, 250.0));
assert!(c.commit().is_none());
}
#[test]
fn the_keyboard_inset_reads_zero_under_a_view_that_clears_the_keyboard() {
// A bottom sheet the keyboard lifts (`clears_keyboard`): what pads by
// `env(keyboard-inset-height)` in it, the panel itself or its content,
// is not lifted a second time; outside it the inset is the keyboard's.
let padded = |id| {
style_op(
id,
&[
("height", StyleValue::Number(100.0)),
(
"paddingBottom",
StyleValue::Str("env(keyboard-inset-height)"),
),
],
)
};
let mut c = core();
c.set_environment(env_with_keyboard(0.0, 0.0));
let mut ops = Vec::new();
for id in [2, 3, 4] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(padded(id));
}
ops.extend([
Op::SetProp {
id: 2,
prop: Prop::ClearsKeyboard(true),
},
// 3 in the panel 2, 4 beside it.
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
]);
apply(&mut c, ops);
c.commit();
c.set_environment(env_with_keyboard(40.0, 0.0));
c.commit();
assert_eq!(env_applied(&c, 2)[0].bottom, px(0.0));
assert_eq!(env_applied(&c, 3)[0].bottom, px(0.0));
assert_eq!(env_applied(&c, 4)[0].bottom, px(40.0));
// No longer clear of it: the inset is the keyboard's again.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::ClearsKeyboard(false),
}],
);
c.commit();
assert_eq!(env_applied(&c, 2)[0].bottom, px(40.0));
assert_eq!(env_applied(&c, 3)[0].bottom, px(40.0));
}
#[test]
fn styles_that_read_the_keyboard_height_move_with_the_keyboard() {
// An app that reads `keyboardFrame()` (not `env()`) restyles in the
// commit the keyboard's change starts.
let keyboard_curve = |batch: &MountBatch| {
matches!(
&batch.items[0],
MountItem::LayoutAnimation(crate::LayoutAnimation {
update: Some(t), .. }) if t.curve == crate::LayoutCurve::Keyboard && t.duration_ms == 250.0
)
};
let mut c = core();
c.set_environment(env_with_keyboard(0.0, 250.0));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(!keyboard_curve(&batch));
// The keyboard shows; the app shrinks its view by its height.
c.set_environment(env_with_keyboard(40.0, 250.0));
apply(
&mut c,
vec![style_op(2, &[("height", StyleValue::Number(60.0))])],
);
let batch = c.commit().unwrap();
assert!(keyboard_curve(&batch), "{:?}", batch.items);
// A later change of the app's own does not.
apply(
&mut c,
vec![style_op(2, &[("height", StyleValue::Number(50.0))])],
);
let batch = c.commit().unwrap();
assert!(!keyboard_curve(&batch), "{:?}", batch.items);
// An animation the app configured for the commit wins.
c.set_environment(env_with_keyboard(0.0, 250.0));
let spring = crate::LayoutAnimation {
create: None,
update: Some(crate::LayoutTransition {
curve: crate::LayoutCurve::EaseIn,
property: crate::LayoutProperty::Opacity,
duration_ms: 100.0,
delay_ms: 0.0,
}),
delete: None,
};
apply(
&mut c,
vec![
Op::Command {
id: ROOT_ID,
command: Command::LayoutAnimation(spring),
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
],
);
let batch = c.commit().unwrap();
assert!(
matches!(&batch.items[0], MountItem::LayoutAnimation(a) if *a == spring),
"{:?}",
batch.items
);
}
#[test]
fn calc_adds_a_length_to_the_keyboard_inset() {
let mut c = core();
c.set_environment(env_with_keyboard(0.0, 0.0));
view_with_classes(
&mut c,
2,
"h-[100px] mb-[calc(env(keyboard-inset-height)+8px)]",
);
view_with_classes(&mut c, 4, "h-[10px]");
let batch = c.commit().unwrap();
// Hidden: only the length, between it and the view below.
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.y.0), Some(108.0));
c.set_environment(env_with_keyboard(300.0, 0.0));
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.y.0), Some(408.0));
}
#[test]
fn safe_area_insets_are_those_of_the_root_view_a_node_renders_in() {
let mut c = core();
c.set_environment(crate::element::Environment {
window: size_pt(320.0, 480.0),
safe_area: EdgeInsets {
top: px(20.0),
bottom: px(34.0),
..Default::default()
},
..Default::default()
});
let padded = [
(
"paddingTop",
StyleValue::Str("calc(env(safe-area-inset-top) + 8px)"),
),
(
"paddingBottom",
StyleValue::Str("env(safe-area-inset-bottom)"),
),
];
apply(
&mut c,
vec![
// On the surface.
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &padded),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
// On a page, whose header covers the top.
Op::Create {
id: 4,
tag: Tag::Stack,
},
Op::Create {
id: 6,
tag: Tag::Screen,
},
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(8, &padded),
Op::Insert {
parent: 6,
child: 8,
before: None,
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 4,
before: None,
},
],
);
c.commit();
assert_eq!(
env_applied(&c, 2)[0],
EdgeInsets {
top: px(20.0),
bottom: px(34.0),
..Default::default()
}
);
assert_eq!(
env_applied(&c, 8)[0],
EdgeInsets {
bottom: px(34.0),
..Default::default()
}
);
// The page reports its insets: its node follows, the surface's does
// not.
c.component_event(
6,
EventKind::Insets,
&EventPayload::Map(vec![
("top", PayloadValue::Number(64.0)),
("bottom", PayloadValue::Number(0.0)),
]),
);
c.commit();
assert_eq!(
env_applied(&c, 8)[0],
EdgeInsets {
top: px(64.0),
..Default::default()
}
);
assert_eq!(env_applied(&c, 2)[0].top, px(20.0));
}
/// A native element with `component` and, optionally, a bound `progress`.
fn native_with_animated_prop(c: &mut Core<FakeEngine>, node: Option<crate::animation::NodeId>) {
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Native,
},
Op::SetProp {
id: 2,
prop: Prop::Component("com.example.thing".into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
if let Some(node) = node {
ops.push(Op::SetProp {
id: 2,
prop: Prop::ComponentPropBinding("progress".into(), Some(node)),
});
}
apply(c, ops);
}
fn component_prop_op(name: &str, value: Option<crate::JsonValue>) -> Op {
Op::SetProp {
id: 2,
prop: Prop::ComponentProp(name.into(), value),
}
}
fn animated_prop_op(name: &str, node: Option<crate::animation::NodeId>) -> Op {
Op::SetProp {
id: 2,
prop: Prop::ComponentPropBinding(name.into(), node),
}
}
fn component_props_of(
batch: &crate::mount::MountBatch,
) -> Vec<(Arc<str>, Option<crate::JsonValue>)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::ComponentProps { id: 2, props } => Some(props.clone()),
_ => None,
})
.flatten()
.collect()
}
fn component_bindings_of(batch: &crate::mount::MountBatch) -> Option<Vec<Arc<str>>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ComponentPropSlots { id: 2, names } => Some(names.clone()),
_ => None,
})
}
fn animation_bindings_of(
batch: &crate::mount::MountBatch,
) -> Option<Vec<(AnimationProp, crate::animation::NodeId)>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::AnimationBindings { id: 2, bindings } => Some(bindings.clone()),
_ => None,
})
}
#[test]
fn component_prop_binds_to_animated_node() {
let mut c = core();
native_with_animated_prop(&mut c, Some(7));
let batch = c.commit().unwrap();
let names = batch
.items
.iter()
.position(|i| matches!(i, MountItem::ComponentPropSlots { id: 2, .. }))
.unwrap();
let bindings = batch
.items
.iter()
.position(|i| matches!(i, MountItem::AnimationBindings { id: 2, .. }))
.unwrap();
assert!(names < bindings);
assert_eq!(component_bindings_of(&batch), Some(vec!["progress".into()]));
assert_eq!(
animation_bindings_of(&batch),
Some(vec![(AnimationProp::ComponentSlot(0), 7)])
);
assert!(
component_props_of(&batch)
.iter()
.all(|(k, _)| &**k != "progress")
);
}
#[test]
fn static_value_hidden_while_bound() {
let mut c = core();
native_with_animated_prop(&mut c, None);
apply(
&mut c,
vec![component_prop_op("progress", Some(serde_json::json!(0.5)))],
);
c.commit().unwrap();
apply(&mut c, vec![animated_prop_op("progress", Some(7))]);
c.commit().unwrap();
// Set while bound: kept, not sent.
apply(
&mut c,
vec![component_prop_op("progress", Some(serde_json::json!(0.7)))],
);
// Nothing to send at all.
if let Some(batch) = c.commit() {
assert!(
component_props_of(&batch)
.iter()
.all(|(k, _)| &**k != "progress")
);
}
// Unbound: the kept value comes back.
apply(&mut c, vec![animated_prop_op("progress", None)]);
let batch = c.commit().unwrap();
assert_eq!(
component_props_of(&batch),
vec![("progress".into(), Some(serde_json::json!(0.7)))]
);
assert_eq!(animation_bindings_of(&batch), Some(vec![]));
}
#[test]
fn unbind_without_static_sends_none() {
let mut c = core();
native_with_animated_prop(&mut c, Some(7));
c.commit().unwrap();
apply(&mut c, vec![animated_prop_op("progress", None)]);
let batch = c.commit().unwrap();
assert_eq!(component_props_of(&batch), vec![("progress".into(), None)]);
assert_eq!(animation_bindings_of(&batch), Some(vec![]));
}
#[test]
fn rebinding_reuses_the_slot() {
let mut c = core();
native_with_animated_prop(&mut c, Some(7));
c.commit().unwrap();
apply(&mut c, vec![animated_prop_op("progress", Some(8))]);
let batch = c.commit().unwrap();
// Same table, no new names.
assert_eq!(component_bindings_of(&batch), None);
assert_eq!(
animation_bindings_of(&batch),
Some(vec![(AnimationProp::ComponentSlot(0), 8)])
);
}
#[test]
fn late_named_component_gets_bindings() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Native,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
animated_prop_op("progress", Some(7)),
],
);
c.commit().unwrap();
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Component("com.example.thing".into()),
}],
);
let batch = c.commit().unwrap();
let at = |pred: &dyn Fn(&MountItem) -> bool| batch.items.iter().position(pred).unwrap();
let component = at(&|i| matches!(i, MountItem::Component { id: 2, .. }));
let names = at(&|i| matches!(i, MountItem::ComponentPropSlots { id: 2, .. }));
let bindings = at(&|i| matches!(i, MountItem::AnimationBindings { id: 2, .. }));
assert!(component < names && names < bindings);
}
mod remount {
use super::*;
#[test]
fn resends_native_component_slots_before_their_bindings() {
let mut c = core();
native_with_animated_prop(&mut c, Some(7));
let first = c.commit().unwrap();
c.remount();
let again = c.commit().unwrap();
assert_eq!(component_bindings_of(&again), component_bindings_of(&first));
assert_eq!(animation_bindings_of(&again), animation_bindings_of(&first));
let slots = again
.items
.iter()
.position(|i| matches!(i, MountItem::ComponentPropSlots { id: 2, .. }))
.unwrap();
let bindings = again
.items
.iter()
.position(|i| matches!(i, MountItem::AnimationBindings { id: 2, .. }))
.unwrap();
assert!(slots < bindings);
assert!(
!again
.items
.iter()
.any(|i| matches!(i, MountItem::Create { .. } | MountItem::Component { .. }))
);
assert!(c.commit().is_none());
}
fn assert_sticky_replayed(c: &mut Core<FakeEngine>, first: &MountBatch, view: NodeId) {
let expected = sticky_of(first, view).expect("initial sticky ranges");
assert!(!expected.is_empty());
assert!(c.commit().is_none());
c.remount();
let batch = c.commit().unwrap();
assert_eq!(sticky_of(&batch, view), Some(expected));
assert!(
!batch.items.iter().any(|i| matches!(
i,
MountItem::Create { .. } | MountItem::Insert { .. } | MountItem::Remove { .. }
)),
"existing sticky views must not be restacked: {:?}",
batch.items
);
assert!(c.commit().is_none());
}
#[test]
fn replays_css_sticky_ranges_even_when_layout_is_unchanged() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
];
ops.extend(child_view(3, 2, 100.0, &[]));
ops.extend(child_view(
4,
2,
40.0,
&[
("position", StyleValue::Str("sticky")),
("top", StyleValue::Number(10.0)),
],
));
ops.extend(child_view(5, 2, 2000.0, &[]));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let first = c.commit().unwrap();
assert_sticky_replayed(&mut c, &first, 2);
}
#[test]
fn replays_sticky_rows_for_own_and_parent_viewports() {
for parent in [false, true] {
let mut c = core();
let list = if parent {
page(&mut c, 100.0, &[20]);
4
} else {
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(20),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
2
};
apply(
&mut c,
vec![
Op::SetProp {
id: list,
prop: Prop::StickyIndices(vec![0, 10]),
},
Op::Animation(AnimationOp::CreateValue {
node: 2,
value: 56.0,
}),
Op::SetProp {
id: list,
prop: Prop::StickyOffsetNode(Some(2)),
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
let first = c.commit().unwrap();
let offsets = sticky_offsets_of(&first, 2).unwrap();
assert_sticky_replayed(&mut c, &first, 2);
c.remount();
let again = c.commit().unwrap();
assert_eq!(sticky_offsets_of(&again, 2), Some(offsets));
if parent {
assert_eq!(sticky_of(&again, list), None);
}
}
}
#[test]
fn sends_every_view_again_without_creating_it() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::CreateText {
id: 4,
text: "hello".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
style_op(
2,
&[
("padding", StyleValue::Number(10.0)),
("borderRadius", StyleValue::Number(8.0)),
],
),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let first = c.commit().unwrap();
assert!(c.commit().is_none());
c.remount();
let again = c.commit().expect("a remount sends a batch");
assert!(
!again.items.iter().any(|i| matches!(
i,
MountItem::Create { .. } | MountItem::Insert { .. } | MountItem::Remove { .. }
)),
"the views stay: {:?}",
again.items
);
assert_eq!(frame_of(&again, 2), frame_of(&first, 2));
assert_eq!(frame_of(&again, 3), frame_of(&first, 3));
assert!(
again
.items
.iter()
.any(|i| matches!(i, MountItem::ViewStyle { id: 2, .. }))
);
assert!(
again
.items
.iter()
.any(|i| matches!(i, MountItem::Text { id: 3, .. }))
);
assert!(c.commit().is_none(), "nothing left to send");
}
/// A right to left horizontal scroll view the user scrolled stays where
/// it is: it gets its content size again, never the scroll to its right
/// end a new one gets.
#[test]
fn keeps_a_scrolled_right_to_left_scroll_view_where_it_is() {
let mut c = core();
let n = |v: f32| StyleValue::Number(v);
let mut ops = vec![
Op::SetProp {
id: ROOT_ID,
prop: Prop::LayoutDirection(true),
},
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
},
style_op(2, &[("width", n(150.0)), ("height", n(50.0))]),
];
for id in [3, 4] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(id, &[("width", n(100.0)), ("height", n(50.0))]));
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let first = c.commit().unwrap();
let scrolls = |batch: &MountBatch| {
batch
.items
.iter()
.filter(|i| {
matches!(
i,
MountItem::Command { id: 2, .. } | MountItem::ScrollBy { id: 2, .. }
)
})
.count()
};
// A new one starts at its right end.
assert_eq!(scrolls(&first), 1);
// The user scrolls it to its left end.
c.set_scroll_offset(2, point(px(0.0), px(0.0)), u32::MAX);
c.remount();
let again = c.commit().expect("a remount sends a batch");
let content: Vec<_> = again
.items
.iter()
.filter_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(*size),
_ => None,
})
.collect();
assert_eq!(content, [size_pt(200.0, 50.0)]);
assert_eq!(scrolls(&again), 0, "{:?}", again.items);
assert!(c.commit().is_none(), "nothing left to send");
}
}
mod built_in_scrollbars {
use serde_json::json;
use super::*;
use crate::{
Prop, ScrollbarSetting,
element::{
AnyElement, BuiltInScrollbar, Component, NoEvent, Props, Registry, Scope,
ScrollbarSource,
},
prelude::*,
};
/// A bar: a view with a thumb, counting its cleanups.
#[derive(Default)]
struct Bar;
#[derive(Clone, PartialEq, Props)]
struct BarProps {}
thread_local! {
static BARS_CLEANED: Cell<u32> = const { Cell::new(0) };
}
impl Component for Bar {
type Props = BarProps;
type Event = NoEvent;
fn view(_: BarProps, _: Scope<NoEvent>) -> impl IntoElement {
cleanup(|| BARS_CLEANED.with(|c| c.set(c.get() + 1)));
view().child(view().w(px(4.0)).h(px(20.0)))
}
}
/// Bars for vertical views only: horizontal ones keep the platform's.
fn bars(of: &BuiltInScrollbar) -> Option<AnyElement> {
(!of.horizontal).then(|| Bar::element(BarProps {}).into_element())
}
/// The app draws every bar with `bars`.
fn app_theme() -> (ScrollbarSource, crate::element::AnyValue) {
(bars, crate::element::AnyValue::new(()))
}
/// A core whose sets make bars: a scroll view 2 of 300 by 200 with a
/// child 4 of 1000 points, its `scrollbar` `setting`.
fn scroll_view(
builtin: bool,
setting: Option<ScrollbarSetting>,
) -> (Core<FakeEngine>, MountBatch) {
let mut c = core();
let mut registry = Registry::new();
registry.scrollbars_from(bars);
c.set_components(registry);
c.set_builtin_scrollbars(builtin.then(|| app_theme()));
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(
2,
&[
("width", StyleValue::Number(300.0)),
("height", StyleValue::Number(200.0)),
],
),
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(4, &[("height", StyleValue::Number(1000.0))]),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
if let Some(setting) = setting {
ops.push(Op::SetProp {
id: 2,
prop: Prop::Scrollbar(setting),
});
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
(c, batch)
}
/// The core's children of view 2 (odd ids) that a batch inserts.
fn bars_in(batch: &MountBatch) -> Vec<NodeId> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert {
parent: 2, child, ..
} if child % 2 == 1 => Some(*child),
_ => None,
})
.collect()
}
fn indicator(batch: &MountBatch) -> Option<bool> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollConfig {
id: 2,
scrollbar_visible,
..
} => Some(*scrollbar_visible),
_ => None,
})
}
fn replaced(batch: &MountBatch) -> Option<bool> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollConfig {
id: 2, replaced, ..
} => Some(*replaced),
_ => None,
})
}
#[test]
fn views_keep_the_platforms_indicator_until_the_app_draws_bars() {
let (_, batch) = scroll_view(false, None);
assert!(bars_in(&batch).is_empty());
assert_eq!(indicator(&batch), Some(true));
assert_eq!(replaced(&batch), Some(false));
}
#[test]
fn a_built_in_bar_covers_the_viewport_and_stays_there() {
let (_, batch) = scroll_view(true, None);
let [bar] = bars_in(&batch)[..] else {
panic!("one bar: {:?}", batch.items)
};
assert_eq!(indicator(&batch), Some(false), "the bar takes its place");
assert_eq!(replaced(&batch), Some(true), "on every axis");
assert_eq!(frame_of(&batch, bar), Some(rect(0.0, 0.0, 300.0, 200.0)));
let sticky = batch.items.iter().find_map(|i| match i {
MountItem::StickyCells { id: 2, cells } => Some(cells.clone()),
_ => None,
});
let cells = sticky.expect("the bar is pinned");
assert_eq!(cells.len(), 1);
assert_eq!((cells[0].cell, cells[0].start), (bar, Points(0.0)));
assert!(cells[0].end.0 > 1000.0, "across all of the content");
// Out of the content's layout: the content size is the child's.
let content = batch.items.iter().rev().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size, .. } => Some(*size),
_ => None,
});
assert_eq!(content, Some(size_pt(300.0, 1000.0)));
}
#[test]
fn a_built_in_bar_keeps_within_the_scrollbar_inset() {
let (mut c, batch) = scroll_view(true, None);
let [bar] = bars_in(&batch)[..] else {
panic!("one bar: {:?}", batch.items)
};
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::ScrollbarInset(EdgeInsets {
top: px(10.0),
right: px(6.0),
bottom: px(60.0),
left: px(0.0),
})),
}],
);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, bar),
Some(rect(0.0, 10.0, 294.0, 130.0)),
"{:?}",
batch.items
);
// Moving the inset without resizing the bar still moves its frame.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::ScrollbarInset(EdgeInsets {
top: px(20.0),
right: px(0.0),
bottom: px(50.0),
left: px(6.0),
})),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, bar), Some(rect(6.0, 20.0, 294.0, 130.0)));
// Back to the whole viewport.
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Scroll(ScrollProp::ScrollbarInset(EdgeInsets::default())),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, bar), Some(rect(0.0, 0.0, 300.0, 200.0)));
}
#[test]
fn a_culled_scroll_pins_its_bar_only_after_it_is_created() {
let mut c = core();
let mut registry = Registry::new();
registry.scrollbars_from(bars);
c.set_components(registry);
c.set_builtin_scrollbars(Some(app_theme()));
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
ops.extend(child_view(4, 2, 1000.0, &[]));
ops.extend([
Op::Create {
id: 6,
tag: Tag::Scroll,
},
style_op(6, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: 2,
child: 6,
before: None,
},
]);
ops.extend(child_view(8, 6, 1000.0, &[]));
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert!(!created_in(&batch).contains(&6));
assert!(
!batch
.items
.iter()
.any(|item| matches!(item, MountItem::StickyCells { id: 6, .. })),
"a scroll view that has no native view cannot pin its bar"
);
let key = c.key(6).unwrap();
let bar = c.nodes[key as usize]
.scroll
.as_ref()
.unwrap()
.bar
.as_ref()
.unwrap()
.0;
c.set_scroll_offset(2, point(Points::ZERO, Points(1000.0)), 0);
for remount in [false, true] {
if remount {
c.remount();
}
let batch = c.commit().unwrap();
let pins: Vec<_> = batch
.items
.iter()
.enumerate()
.filter_map(|(at, item)| match item {
MountItem::StickyCells { id: 6, cells } => Some((at, cells)),
_ => None,
})
.collect();
assert_eq!(pins.len(), 1, "remount={remount}");
assert_eq!(pins[0].1.len(), 1);
assert_eq!(pins[0].1[0].cell, bar);
if !remount {
for id in [6, bar] {
let made = batch
.items
.iter()
.position(|item| {
matches!(item, MountItem::Create { id: made, .. } if *made == id)
})
.expect("the scroll view and its bar are made when they come into view");
assert!(made < pins[0].0);
}
}
assert!(c.commit().is_none());
}
}
#[test]
fn what_the_app_appends_goes_below_the_bar() {
let (mut c, batch) = scroll_view(true, None);
let [bar] = bars_in(&batch)[..] else {
panic!("one bar")
};
apply(
&mut c,
vec![
Op::Create {
id: 6,
tag: Tag::View,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
],
);
let batch = c.commit().unwrap();
let before = batch.items.iter().find_map(|i| match i {
MountItem::Insert {
parent: 2,
child: 6,
before,
} => Some(*before),
_ => None,
});
assert_eq!(before, Some(Some(bar)));
let key = c.key(2).unwrap();
let ids: Vec<NodeId> = c.nodes[key as usize]
.children
.iter()
.map(|&k| c.nodes[k as usize].id)
.collect();
assert_eq!(ids, [4, 6, bar]);
}
#[test]
fn a_raised_or_sticky_child_still_goes_below_the_bar() {
let (mut c, batch) = scroll_view(true, None);
let [bar] = bars_in(&batch)[..] else {
panic!("one bar")
};
let raised = |v: f32| {
style(&[
("zIndex", StyleValue::Number(v)),
("position", StyleValue::Str("sticky")),
])
};
apply(
&mut c,
vec![
Op::Create {
id: 6,
tag: Tag::View,
},
Op::SetStyle {
id: 6,
style: raised(100.0),
patch: StylePatch::default(),
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
],
);
let batch = c.commit().unwrap();
let before = batch.items.iter().find_map(|i| match i {
MountItem::Insert {
parent: 2,
child: 6,
before,
} => Some(*before),
_ => None,
});
assert_eq!(before, Some(Some(bar)), "the bar draws above it");
}
/// The views of list 2, bottom to top, as the platforms stack them:
/// in the order inserted, then the sticky cells raised on every
/// `StickyCells` and insert. `in_order` raises them in the order the
/// item lists them (iOS, Android), otherwise in the order they are
/// among the children (the desktops), when not all of them are last.
struct Stack {
views: Vec<NodeId>,
sticky: Vec<NodeId>,
in_order: bool,
}
impl Stack {
fn apply(&mut self, batch: &MountBatch) {
for item in &batch.items {
match item {
MountItem::Insert {
parent: 2,
child,
before,
} => {
self.views.retain(|v| v != child);
let at = before
.and_then(|b| self.views.iter().position(|&v| v == b))
.unwrap_or(self.views.len());
self.views.insert(at, *child);
self.raise();
}
MountItem::Remove { id } => self.views.retain(|v| v != id),
MountItem::StickyCells { id: 2, cells } => {
self.sticky = cells.iter().map(|c| c.cell).collect();
self.raise();
}
_ => {}
}
}
}
fn raise(&mut self) {
let sticky = |v: &NodeId| self.sticky.contains(v);
let cells: Vec<NodeId> = if self.in_order {
self.sticky.clone()
} else {
let at_end = self.views.iter().rev().take_while(|v| sticky(v)).count();
let cells: Vec<NodeId> = self.views.iter().copied().filter(sticky).collect();
if at_end == cells.len() {
return;
}
cells
};
for cell in cells {
if self.views.contains(&cell) {
self.views.retain(|&v| v != cell);
self.views.push(cell);
}
}
}
}
#[test]
fn a_lists_sticky_rows_go_below_its_bar() {
for in_order in [false, true] {
let mut c = core();
let mut registry = Registry::new();
registry.scrollbars_from(bars);
c.set_components(registry);
c.set_builtin_scrollbars(Some(app_theme()));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(100),
},
Op::SetProp {
id: 2,
prop: Prop::StickyIndices(vec![0, 10]),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let mut stack = Stack {
views: Vec::new(),
sticky: Vec::new(),
in_order,
};
let batch = c.commit().unwrap();
stack.apply(&batch);
let [bar] = bars_in(&batch)[..] else {
panic!("one bar: {:?}", batch.items)
};
let (mut next_id, mut cells) = (100, Vec::new());
for offset in [0.0, 300.0, 600.0, 2000.0, 0.0] {
c.set_scroll_offset(2, point(px(0.0), px(offset)), u32::MAX);
if let Some(batch) = c.commit() {
stack.apply(&batch);
}
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
// Nothing to commit when the window already held the rows.
if let Some(batch) = c.commit() {
// Every set the list pins keeps its bar, last (on top).
for item in &batch.items {
if let MountItem::StickyCells { id: 2, cells } = item {
assert_eq!(cells.last().map(|c| c.cell), Some(bar), "{cells:?}");
}
}
stack.apply(&batch);
}
assert_eq!(
stack.views.last(),
Some(&bar),
"at {offset}, raised in order: {in_order}: {:?} (sticky {:?})",
stack.views,
stack.sticky
);
assert!(stack.sticky.len() > 1, "a row sticks: {:?}", stack.sticky);
}
}
}
/// A core drawing every bar with `bars`: in a view 2, a multiline (or
/// single-line) input 6 of 300 by 100, 50 down, and a view 8 10 high
/// after it.
fn input_view(multiline: bool) -> (Core<FakeEngine>, MountBatch) {
let mut c = core();
let mut registry = Registry::new();
registry.scrollbars_from(bars);
c.set_components(registry);
c.set_builtin_scrollbars(Some(app_theme()));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("paddingTop", StyleValue::Number(50.0))]),
Op::Create {
id: 6,
tag: Tag::Input,
},
Op::SetProp {
id: 6,
prop: Prop::Multiline(multiline),
},
style_op(
6,
&[
("width", StyleValue::Number(300.0)),
("height", StyleValue::Number(100.0)),
],
),
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(8, &[("height", StyleValue::Number(10.0))]),
Op::Insert {
parent: 2,
child: 6,
before: None,
},
Op::Insert {
parent: 2,
child: 8,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
(c, batch)
}
/// The last config batch `batch` sends input 6.
fn input_config(batch: &MountBatch) -> Option<crate::InputConfig> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Input { id: 6, config } => Some((**config).clone()),
_ => None,
})
}
/// Where a batch inserts the core's views (odd ids) into view 2.
fn bars_beside(batch: &MountBatch) -> Vec<(NodeId, Option<NodeId>)> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Insert {
parent: 2,
child,
before,
} if child % 2 == 1 => Some((*child, *before)),
_ => None,
})
.collect()
}
#[test]
fn a_multiline_input_gets_a_bar_over_it_in_its_indicators_place() {
let (c, batch) = input_view(true);
let [(bar, before)] = bars_beside(&batch)[..] else {
panic!("one bar: {:?}", batch.items)
};
assert_eq!(before, Some(8), "just above the input");
assert_eq!(frame_of(&batch, bar), frame_of(&batch, 6));
assert_eq!(frame_of(&batch, bar), Some(rect(0.0, 50.0, 300.0, 100.0)));
let config = input_config(&batch).expect("the input's config");
assert!(config.report_scroll && !config.scrollbar_visible);
// Not one of the view's children, nor pinned as a scroll view's.
let key = c.key(2).unwrap();
assert_eq!(c.nodes[key as usize].children.len(), 3);
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::StickyCells { .. }))
);
}
#[test]
fn a_single_line_input_keeps_no_bar() {
let (_, batch) = input_view(false);
assert!(bars_beside(&batch).is_empty());
let config = input_config(&batch).expect("the input's config");
assert!(!config.report_scroll && config.scrollbar_visible);
}
#[test]
fn an_input_bar_follows_the_input_and_goes_with_it() {
let (mut c, batch) = input_view(true);
let [(bar, _)] = bars_beside(&batch)[..] else {
panic!("one bar")
};
// Moved after view 8: the bar is made again just above it.
apply(
&mut c,
vec![Op::Insert {
parent: 2,
child: 6,
before: None,
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == bar))
);
let [(moved, before)] = bars_beside(&batch)[..] else {
panic!("the bar made again: {:?}", batch.items)
};
assert_eq!(before, None);
let key = c.key(2).unwrap();
let ids: Vec<NodeId> = c.nodes[key as usize]
.children
.iter()
.map(|&k| c.nodes[k as usize].id)
.collect();
assert_eq!(ids, [8, 6, moved]);
assert_eq!(frame_of(&batch, 6), Some(rect(0.0, 60.0, 300.0, 100.0)));
assert_eq!(frame_of(&batch, moved), frame_of(&batch, 6));
// Released with the input.
apply(&mut c, vec![Op::Release { id: 6 }]);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == moved))
);
assert!(c.key(moved).is_err());
}
#[test]
fn an_input_reports_its_scrolling_to_watches() {
let (mut c, _) = input_view(true);
c.set_input_scroll(
6,
point(px(0.0), px(40.0)),
size_pt(280.0, 400.0),
size_pt(280.0, 90.0),
);
let report = c.scroll_report(6).expect("a report");
assert_eq!(report.offset, point(px(0.0), px(40.0)));
assert_eq!(report.content_size, size_pt(280.0, 400.0));
assert_eq!(report.size, size_pt(280.0, 90.0));
}
thread_local! {
static INPUT_WATCHED: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
static INPUT_HEARD: Cell<Option<f32>> = const { Cell::new(None) };
}
/// A multiline input without a bar of its own, and a scroll bar of the
/// app's (a watch of the input's scrolling) while `INPUT_WATCHED` holds.
#[component]
fn WatchedInput() -> impl IntoElement {
let watching = signal(true);
INPUT_WATCHED.with(|w| w.set(Some(watching)));
let field = element_ref();
view()
.child(
input()
.element_ref(&field)
.multiline(true)
.scrollbar(false)
.w(px(300.0))
.h(px(100.0)),
)
.child(dynamic(move || {
if watching.get() {
watch_scroll(
move || field.node(),
|e: &ScrollEvent| INPUT_HEARD.with(|h| h.set(Some(e.offset.y.0))),
);
}
view()
}))
}
/// The config the last batch sent an input, if it sent one.
fn any_input_config(batch: &MountBatch) -> Option<crate::InputConfig> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Input { config, .. } => Some((**config).clone()),
_ => None,
})
}
#[test]
fn a_watched_input_reports_its_scrolling_without_a_bar_of_its_own() {
INPUT_HEARD.with(|h| h.set(None));
let mut c = core();
c.mount_root(&crate::element::Root::new::<WatchedInput>(|| ()));
let mut batch = c.commit().unwrap();
let id = batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create {
id,
kind: ViewKind::Input,
} => Some(*id),
_ => None,
})
.expect("the input");
// The watch finds its target once it is mounted, in a later round.
while let Some(next) = c.commit() {
batch.items.extend(next.items);
}
let config = any_input_config(&batch).expect("the input's config");
assert!(config.report_scroll, "watched: its scrolling is reported");
assert!(!config.scrollbar_visible, "`scrollbar(false)`");
c.set_input_scroll(
id,
point(px(0.0), px(30.0)),
size_pt(300.0, 400.0),
size_pt(300.0, 100.0),
);
let _ = c.commit();
assert_eq!(
INPUT_HEARD.with(Cell::get),
Some(30.0),
"the watch hears it"
);
// No watch left: the platform stops reporting.
let watching = INPUT_WATCHED.with(Cell::get).unwrap();
{
let _entered = c.components.runtime.enter();
watching.set(false);
}
let mut batch = c.commit().unwrap();
while let Some(next) = c.commit() {
batch.items.extend(next.items);
}
let config = any_input_config(&batch).expect("the input's config again");
assert!(!config.report_scroll);
}
#[test]
fn a_theme_of_the_views_own_shows_a_bar_and_false_none() {
let theme = ScrollbarSetting::Themed(std::sync::Arc::new(json!({ "mode": "always" })));
let (_, batch) = scroll_view(false, Some(theme));
assert_eq!(bars_in(&batch).len(), 1);
assert_eq!(indicator(&batch), Some(false));
let (_, batch) = scroll_view(true, Some(ScrollbarSetting::Hidden));
assert!(bars_in(&batch).is_empty());
assert_eq!(indicator(&batch), Some(false));
}
#[test]
fn turning_bars_off_releases_them_and_brings_the_indicator_back() {
let (mut c, batch) = scroll_view(true, None);
let [bar] = bars_in(&batch)[..] else {
panic!("one bar")
};
c.set_builtin_scrollbars(None);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == bar)),
"{:?}",
batch.items
);
assert_eq!(indicator(&batch), Some(true));
assert!(c.decorated.is_empty());
assert_eq!(BARS_CLEANED.with(Cell::get), 1, "the bar's cleanup ran");
}
#[test]
fn a_scrollbar_turned_off_releases_its_bar_in_the_runtime() {
let (mut c, batch) = scroll_view(true, Some(ScrollbarSetting::Shown));
let [bar] = bars_in(&batch)[..] else {
panic!("one bar")
};
apply(
&mut c,
vec![Op::SetProp {
id: 2,
prop: Prop::Scrollbar(ScrollbarSetting::Hidden),
}],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == bar)),
"{:?}",
batch.items
);
assert_eq!(BARS_CLEANED.with(Cell::get), 1, "the bar's cleanup ran");
}
#[test]
fn a_view_the_set_makes_no_bar_for_keeps_its_indicator() {
let mut c = core();
let mut registry = Registry::new();
registry.scrollbars_from(bars);
c.set_components(registry);
c.set_builtin_scrollbars(Some(app_theme()));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
assert!(bars_in(&batch).is_empty());
assert_eq!(indicator(&batch), Some(true));
}
#[test]
fn releasing_the_view_releases_its_bar() {
let (mut c, batch) = scroll_view(true, None);
let [bar] = bars_in(&batch)[..] else {
panic!("one bar")
};
apply(&mut c, vec![Op::Release { id: 4 }, Op::Release { id: 2 }]);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::Delete { id } if *id == bar))
);
assert!(c.key(bar).is_err());
assert!(c.decorated.is_empty());
}
}
#[test]
fn frames_of_a_subtree_moved_by_whole_points_are_not_walked_again() {
let mut c = core();
let at = |top: f32, left: f32, width: f32, height: f32| {
vec![
("position", StyleValue::Str("absolute")),
("top", StyleValue::Number(top)),
("left", StyleValue::Number(left)),
("width", StyleValue::Number(width)),
("height", StyleValue::Number(height)),
]
};
let mut ops = Vec::new();
for (id, parent, style) in [
(2, ROOT_ID, at(0.0, 0.0, 200.0, 200.0)),
(4, 2, at(5.0, 10.0, 50.0, 20.0)),
(6, 4, at(2.0, 3.0, 10.0, 10.0)),
] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(id, &style));
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
apply(&mut c, ops);
let first = c.commit().unwrap();
assert_eq!(frame_of(&first, 6), Some(rect(3.0, 2.0, 10.0, 10.0)));
// The rows' origin of a table, scrolled: it moves, what is in it does
// not, relative to it.
apply(&mut c, vec![style_op(2, &at(-37.0, 0.0, 200.0, 200.0))]);
let moved = c.commit().unwrap();
assert_eq!(frame_of(&moved, 2), Some(rect(0.0, -37.0, 200.0, 200.0)));
assert_eq!(frame_of(&moved, 4), None);
assert_eq!(frame_of(&moved, 6), None);
// A change deep inside is still sent, and so is a view added there.
apply(
&mut c,
vec![
style_op(6, &at(2.0, 3.0, 12.0, 10.0)),
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(8, &at(1.0, 1.0, 4.0, 4.0)),
Op::Insert {
parent: 4,
child: 8,
before: None,
},
],
);
let changed = c.commit().unwrap();
assert_eq!(frame_of(&changed, 6), Some(rect(3.0, 2.0, 12.0, 10.0)));
assert_eq!(frame_of(&changed, 8), Some(rect(1.0, 1.0, 4.0, 4.0)));
assert_eq!(frame_of(&changed, 4), None);
// A view shown again gets its frame back though nothing in it changed.
apply(
&mut c,
vec![style_op(4, &[("display", StyleValue::Str("none"))])],
);
let hidden = c.commit().unwrap();
assert_eq!(frame_of(&hidden, 6), Some(Bounds::default()));
apply(&mut c, vec![style_op(4, &at(5.0, 10.0, 50.0, 20.0))]);
let shown = c.commit().unwrap();
assert_eq!(frame_of(&shown, 6), Some(rect(3.0, 2.0, 12.0, 10.0)));
}
/// A view that follows another one (`follow.rs`): a row (2: 10 of padding
/// at the start, 30 high) of tabs 50 (4) and 70 (6) wide, its follower (8)
/// laid out first, absolute, 2 high at the bottom; then a view (10) after
/// the row, 10 high.
fn follow_row(c: &mut Core<FakeEngine>, column: bool) {
use StyleValue::{Number, Str};
let list: &[(&str, StyleValue<'_>)] = if column {
&[("flexDirection", Str("column")), ("width", Number(100.0))]
} else {
&[
("flexDirection", Str("row")),
("paddingLeft", Number(10.0)),
("height", Number(30.0)),
]
};
let follower: &[(&str, StyleValue<'_>)] = if column {
&[
("position", Str("absolute")),
("left", Number(0.0)),
("width", Number(3.0)),
("marginTop", Number(2.0)),
("marginBottom", Number(2.0)),
]
} else {
&[
("position", Str("absolute")),
("bottom", Number(0.0)),
("height", Number(2.0)),
]
};
let tab = |n: f32| -> Vec<(&str, StyleValue<'_>)> {
if column {
vec![("height", Number(n))]
} else {
vec![("width", Number(n)), ("height", Number(30.0))]
}
};
let (first, second) = if column { (30.0, 40.0) } else { (50.0, 70.0) };
let mut ops = Vec::new();
for (id, parent, style) in [
(2, 1, list.to_vec()),
(8, 2, follower.to_vec()),
(4, 2, tab(first)),
(6, 2, tab(second)),
(10, 1, vec![("height", Number(10.0))]),
] {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(id, &style));
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
ops.push(Op::SetProp {
id: 8,
prop: Prop::Follow(Some(crate::element::FollowTarget::of_node(6))),
});
apply(c, ops);
}
/// The frames of `batch`, each with the layout animation it runs with.
fn animated_frames(batch: &MountBatch) -> Vec<(NodeId, Option<crate::LayoutTransition>)> {
let mut current = None;
let mut frames = Vec::new();
for item in &batch.items {
match item {
MountItem::LayoutAnimation(a) => current = a.update,
MountItem::Frame { id, .. } => frames.push((*id, current)),
_ => {}
}
}
frames
}
#[test]
fn a_follower_spans_its_target_along_its_parents_row() {
let mut c = core();
follow_row(&mut c, false);
let batch = c.commit().unwrap();
// Across the row, its style: at the bottom, 2 high. Along it, 6: after
// the padding and 4.
assert_eq!(frame_of(&batch, 8), Some(rect(60.0, 28.0, 70.0, 2.0)));
let placed = animated_frames(&batch).iter().filter(|f| f.0 == 8).count();
assert_eq!(placed, 1, "one frame, the followed one: {:?}", batch.items);
}
#[test]
fn a_follower_made_after_layout_is_placed_on_its_target() {
// A turn that makes more than `PACE_AFTER` views makes the rest after
// the layout that gave them their frames (`pace.rs`). A follower made so
// has no frame of its own for `place_follower` until a layout walks it,
// and its target is not made when the followers are first placed.
use StyleValue::{Number, Str};
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", Number(400.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// Views enough to spend the turn's budget before the row.
for i in 0..80 {
ops.extend(child_view(100 + 2 * i, 2, 1.0, &[]));
}
type ViewSpec<'a> = (crate::NodeId, crate::NodeId, Vec<(&'a str, StyleValue<'a>)>);
let views: [ViewSpec<'_>; 5] = [
(20, 2, vec![]),
(
22,
20,
vec![
("flexDirection", Str("row")),
("paddingLeft", Number(10.0)),
("height", Number(30.0)),
],
),
(
28,
22,
vec![
("position", Str("absolute")),
("bottom", Number(0.0)),
("height", Number(2.0)),
],
),
(
24,
22,
vec![("width", Number(50.0)), ("height", Number(30.0))],
),
(
26,
22,
vec![("width", Number(70.0)), ("height", Number(30.0))],
),
];
for (id, parent, style) in views {
ops.push(Op::Create { id, tag: Tag::View });
ops.push(style_op(id, &style));
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
ops.push(Op::SetProp {
id: 28,
prop: Prop::Follow(Some(crate::element::FollowTarget::of_node(26))),
});
apply(&mut c, ops);
let mut batch = c.commit().unwrap();
// The views that wait show, and are made in the commits that follow.
for _ in 0..4 {
if created_in(&batch).contains(&28) && created_in(&batch).contains(&26) {
break;
}
batch = c.commit().unwrap();
}
// After the padding (10) and the first tab (50), as long as the second.
assert_eq!(frame_of(&batch, 28), Some(rect(60.0, 28.0, 70.0, 2.0)));
}
#[test]
fn following_another_view_moves_its_frame_alone_with_its_transition() {
let mut c = core();
follow_row(&mut c, false);
c.commit().unwrap();
let spring = crate::LayoutTransition::new(
crate::LayoutCurve::FittedSpring {
damping_ratio: 0.85,
},
362.0,
);
apply(
&mut c,
vec![
Op::SetProp {
id: 8,
prop: Prop::FollowTransition(Some(spring)),
},
Op::SetProp {
id: 8,
prop: Prop::Follow(Some(crate::element::FollowTarget::of_node(4))),
},
// The content after the row changes in the same commit.
style_op(10, &[("height", StyleValue::Number(20.0))]),
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(10.0, 28.0, 50.0, 2.0)));
let frames = animated_frames(&batch);
assert!(frames.contains(&(8, Some(spring))), "{frames:?}");
assert!(
frames.contains(&(10, None)),
"what changes around it changes at once: {frames:?}"
);
assert_eq!(frames.len(), 2, "no tab moves: {frames:?}");
}
#[test]
fn a_follower_moves_at_once_with_the_layout_that_moves_its_target() {
let mut c = core();
follow_row(&mut c, false);
apply(
&mut c,
vec![Op::SetProp {
id: 8,
prop: Prop::FollowTransition(Some(crate::LayoutTransition::new(
crate::LayoutCurve::EaseOut,
160.0,
))),
}],
);
c.commit().unwrap();
// The first tab grows: the second moves, and its follower with it, in
// the same batch and without the transition.
apply(
&mut c,
vec![style_op(
4,
&[
("width", StyleValue::Number(60.0)),
("height", StyleValue::Number(30.0)),
],
)],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 6), Some(rect(70.0, 0.0, 70.0, 30.0)));
assert_eq!(frame_of(&batch, 8), Some(rect(70.0, 28.0, 70.0, 2.0)));
assert!(
animated_frames(&batch).iter().all(|f| f.1.is_none()),
"{:?}",
batch.items
);
}
#[test]
fn a_follower_in_a_column_follows_vertically_inside_its_margins() {
let mut c = core();
follow_row(&mut c, true);
let batch = c.commit().unwrap();
// Under 4 (30), inside margins of 2; at the left, 3 wide.
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 32.0, 3.0, 36.0)));
}
#[test]
fn a_follower_follows_a_target_inside_other_views() {
let mut c = core();
follow_row(&mut c, false);
// 12, inside 6 after a padding of 5, 20 wide.
apply(
&mut c,
vec![
style_op(
6,
&[
("width", StyleValue::Number(70.0)),
("height", StyleValue::Number(30.0)),
("paddingLeft", StyleValue::Number(5.0)),
],
),
Op::Create {
id: 12,
tag: Tag::View,
},
style_op(
12,
&[
("width", StyleValue::Number(20.0)),
("height", StyleValue::Number(10.0)),
],
),
Op::Insert {
parent: 6,
child: 12,
before: None,
},
Op::SetProp {
id: 8,
prop: Prop::Follow(Some(crate::element::FollowTarget::of_node(12))),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(65.0, 28.0, 20.0, 2.0)));
}
#[test]
fn a_follower_following_nothing_takes_its_own_layout() {
let mut c = core();
follow_row(&mut c, false);
c.commit().unwrap();
apply(
&mut c,
vec![Op::SetProp {
id: 8,
prop: Prop::Follow(None),
}],
);
let batch = c.commit().unwrap();
// Where its style puts it: at the start of the row's content, as wide
// as its content (none).
assert_eq!(frame_of(&batch, 8), Some(rect(10.0, 28.0, 0.0, 2.0)));
}
#[test]
fn nothing_follows_while_no_view_follows_an_element() {
// The pass a follower takes (`Core::place_followers`) returns at once
// on an empty list, and `set_frame` notes nothing: no work, whatever
// the layout does.
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(2, &[("height", StyleValue::Number(30.0))]),
Op::Insert {
parent: 1,
child: 2,
before: None,
},
// Following nothing makes no follower.
Op::SetProp {
id: 2,
prop: Prop::Follow(None),
},
Op::SetProp {
id: 2,
prop: Prop::FollowTransition(None),
},
],
);
c.commit().unwrap();
c.set_viewport(size_pt(200.0, 300.0));
c.commit().unwrap();
assert!(c.followers.is_empty());
assert!(!c.follow_changed);
// A follower released is forgotten, and so is the work.
let mut c = core();
follow_row(&mut c, false);
c.commit().unwrap();
assert_eq!(c.followers.len(), 1);
apply(
&mut c,
vec![
Op::Remove {
parent: 2,
child: 8,
},
Op::Release { id: 8 },
],
);
c.commit().unwrap();
assert!(c.followers.is_empty());
c.set_viewport(size_pt(320.0, 480.0));
c.commit();
assert!(!c.follow_changed);
}
/// A column (2) of a follower (8: absolute, at the left, 3 wide), a
/// header (3, 40 high) and a list (20, 400 high, 30 rows of 50); `nested`
/// puts the list in a scroll view (30, 300 high) after a view 100 high,
/// with a second follower (9) in the scroll view's content. Both follow
/// 50, a view 20 high 10 down row 3's cell: the cell at 150 in the list's
/// content, so the view at 160 there.
fn follow_list(c: &mut Core<FakeEngine>, nested: bool) -> Vec<u32> {
use StyleValue::{Number, Str};
let follower = vec![
("position", Str("absolute")),
("left", Number(0.0)),
("width", Number(3.0)),
];
type ViewSpec<'a> = (NodeId, Tag, NodeId, Vec<(&'a str, StyleValue<'a>)>);
let mut views: Vec<ViewSpec<'_>> = vec![
(
2,
Tag::View,
ROOT_ID,
vec![("flexDirection", Str("column"))],
),
(8, Tag::View, 2, follower.clone()),
(3, Tag::View, 2, vec![("height", Number(40.0))]),
];
let list_parent = if nested {
views.extend([
(30, Tag::Scroll, 2, vec![("height", Number(300.0))]),
(9, Tag::View, 30, follower),
(31, Tag::View, 30, vec![("height", Number(100.0))]),
]);
30
} else {
2
};
views.push((20, Tag::List, list_parent, vec![("height", Number(400.0))]));
let mut ops = Vec::new();
for (id, tag, parent, style) in views {
ops.push(Op::Create { id, tag });
ops.push(style_op(id, &style));
if tag == Tag::List {
ops.push(Op::SetProp {
id,
prop: Prop::EstimatedItemSize(px(50.0)),
});
ops.push(Op::SetProp {
id,
prop: Prop::Count(30),
});
}
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
apply(c, ops);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(c, &mut next_id, &mut cells, 50.0);
c.commit();
let mut ops = vec![
Op::Create {
id: 50,
tag: Tag::View,
},
style_op(50, &[("height", Number(20.0)), ("marginTop", Number(10.0))]),
Op::Insert {
parent: cells[3],
child: 50,
before: None,
},
];
for id in if nested { vec![8, 9] } else { vec![8] } {
ops.push(Op::SetProp {
id,
prop: Prop::Follow(Some(crate::element::FollowTarget::of_node(50))),
});
}
apply(c, ops);
cells
}
#[test]
fn a_follower_follows_a_row_of_a_list_where_the_list_scrolled_it() {
let mut c = core();
follow_list(&mut c, false);
let batch = c.commit().unwrap();
// Under the header (40), the row's view (160 in the list's content).
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 200.0, 3.0, 20.0)));
// The platform reports the list scrolled: the follower goes with the
// row, in the commit that follows the report.
c.set_scroll_offset(20, point(px(0.0), px(100.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 100.0, 3.0, 20.0)));
// Half of the view scrolled out of the list's viewport: the follower
// spans the half the list shows.
c.set_scroll_offset(20, point(px(0.0), px(170.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 40.0, 3.0, 10.0)));
// Wholly out of it: the list shows no part of it, and the follower
// follows nothing (its style alone places it).
c.set_scroll_offset(20, point(px(0.0), px(600.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 0.0, 3.0, 0.0)));
// Back: it follows the row again.
c.set_scroll_offset(20, point(px(0.0), px(0.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 200.0, 3.0, 20.0)));
}
/// A follower outside a list reads the same committed coordinates as
/// measurement and overlays when a resize anchors the list with an instant
/// scroll in the same batch.
#[test]
fn a_follower_follows_a_row_through_the_lists_resize_anchor() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[
("flexGrow", StyleValue::Number(1.0)),
("flexDirection", StyleValue::Str("column")),
],
),
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(
8,
&[
("position", StyleValue::Str("absolute")),
("left", StyleValue::Number(0.0)),
("width", StyleValue::Number(3.0)),
],
),
Op::Insert {
parent: 3,
child: 8,
before: None,
},
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("flexGrow", StyleValue::Number(1.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::FollowEnd(Some(px(80.0)), false),
},
Op::SetProp {
id: 2,
prop: Prop::Count(100),
},
Op::Insert {
parent: 3,
child: 2,
before: None,
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
let mut at = scrolled(&c.commit().unwrap(), 0.0);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
c.set_scroll_offset(2, point(px(0.0), px(at)), u32::MAX);
c.commit();
assert_eq!(at, 100.0 * 50.0 - 480.0, "at the end");
let last = *cells
.iter()
.max_by(|&&a, &&b| {
let y = |id| c.nodes[c.key(id).unwrap() as usize].frame.origin.y.0;
y(a).total_cmp(&y(b))
})
.unwrap();
apply(
&mut c,
vec![Op::SetProp {
id: 8,
prop: Prop::Follow(Some(crate::element::FollowTarget::of_node(last))),
}],
);
let batch = c.commit().expect("the follower");
let before = frame_of(&batch, 8).unwrap();
assert_eq!(before, rect(0.0, 430.0, 3.0, 50.0));
c.set_viewport(size_pt(320.0, 300.0));
let batch = c.commit().expect("the resize");
let scroll_by: f32 = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::ScrollBy { id: 2, dy, .. } => Some(dy.0),
_ => None,
})
.sum();
assert_eq!(scroll_by, 180.0);
assert_eq!(
frame_of(&batch, 8).unwrap().origin.y.0,
before.origin.y.0 - scroll_by,
"the follower moves with the row in the resize batch"
);
}
#[test]
fn a_follower_lets_go_of_a_row_whose_cell_the_list_gave_up() {
let mut c = core();
follow_list(&mut c, false);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 200.0, 3.0, 20.0)));
// Row 3 goes: its cell is spare, hidden where it was, and shows no row
// to follow.
apply(
&mut c,
vec![Op::SetProp {
id: 20,
prop: Prop::Count(2),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 0.0, 3.0, 0.0)));
}
#[test]
fn a_follower_lets_go_of_a_row_left_behind_once_the_items_change() {
// A list in its parent's viewport (4) in a scroll view (2), with a
// follower (8) in the scroll view's content: no viewport on the way
// cuts what it follows.
use StyleValue::{Number, Str};
let mut c = core();
let mut ops = Vec::new();
for (id, tag, parent, style) in [
(2, Tag::Scroll, ROOT_ID, vec![("height", Number(400.0))]),
(
8,
Tag::View,
2,
vec![
("position", Str("absolute")),
("left", Number(0.0)),
("width", Number(3.0)),
],
),
(4, Tag::List, 2, vec![]),
] {
ops.push(Op::Create { id, tag });
ops.push(style_op(id, &style));
ops.push(Op::Insert {
parent,
child: id,
before: None,
});
}
ops.extend([
Op::SetProp {
id: 4,
prop: Prop::ListViewport(crate::ListViewport::Parent),
},
Op::SetProp {
id: 4,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 4,
prop: Prop::Count(100),
},
]);
apply(&mut c, ops);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
apply(
&mut c,
vec![
Op::Create {
id: 50,
tag: Tag::View,
},
style_op(50, &[("height", Number(20.0)), ("marginTop", Number(10.0))]),
Op::Insert {
parent: cells[3],
child: 50,
before: None,
},
Op::SetProp {
id: 8,
prop: Prop::Follow(Some(crate::element::FollowTarget::of_node(50))),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 160.0, 3.0, 20.0)));
// Scrolled far down: row 3's cell is left behind, where it showed the
// row, and the follower stays on it (the scroll view moves both).
c.set_scroll_offset(2, point(px(0.0), px(2000.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), None);
// Rows change far from it: the cell is spare, though it stays where it
// was, and shows no row to follow.
apply(
&mut c,
vec![Op::SetProp {
id: 4,
prop: Prop::Splice(90, 1, 1),
}],
);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, cells[3]), None, "the cell stays");
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 0.0, 3.0, 0.0)));
}
#[test]
fn a_follower_follows_a_row_through_the_scroll_views_outside_it() {
let mut c = core();
follow_list(&mut c, true);
let batch = c.commit().unwrap();
// 8, outside the scroll view: under the header (40), the view (100)
// and the row's view (160). 9, in the scroll view's content: the
// view and the row's.
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 300.0, 3.0, 20.0)));
assert_eq!(frame_of(&batch, 9), Some(rect(0.0, 260.0, 3.0, 20.0)));
// The list scrolls: both go with the row.
c.set_scroll_offset(20, point(px(0.0), px(100.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 200.0, 3.0, 20.0)));
assert_eq!(frame_of(&batch, 9), Some(rect(0.0, 160.0, 3.0, 20.0)));
// The scroll view scrolls: 8 goes with it; 9 is in what it scrolls,
// which the platform moves, and stays.
c.set_scroll_offset(30, point(px(0.0), px(50.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 150.0, 3.0, 20.0)));
assert_eq!(frame_of(&batch, 9), None);
// Out of the scroll view's viewport, though in the list's: 8 follows
// nothing.
c.set_scroll_offset(30, point(px(0.0), px(250.0)), u32::MAX);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8), Some(rect(0.0, 0.0, 3.0, 0.0)));
assert_eq!(frame_of(&batch, 9), None);
}
#[test]
fn an_effect_takes_its_picture_again_when_a_child_leaves() {
let mut c = core();
let source = "fn shade(uv: vec2f) -> vec4f { return sample_content(uv); }";
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::ShaderEffect,
},
style_op(
2,
&[
("width", StyleValue::Number(100.0)),
("height", StyleValue::Number(50.0)),
],
),
Op::SetProp {
id: 2,
prop: Prop::ShaderSource(Some(source.into())),
},
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[
("position", StyleValue::Str("absolute")),
("width", StyleValue::Number(10.0)),
("height", StyleValue::Number(10.0)),
],
),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
// An absolute child of a fixed-size effect: only its Remove and Delete
// go out, neither of which leads to the effect any more.
apply(
&mut c,
vec![
Op::Remove {
parent: 2,
child: 3,
},
Op::Release { id: 3 },
],
);
let batch = c.commit().unwrap();
assert!(
batch
.items
.iter()
.any(|i| matches!(i, MountItem::ShaderInput { id: 2 })),
"{:?}",
batch.items
);
}
#[test]
fn a_layout_animation_alone_takes_no_screen_picture() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::ScreenEffect,
},
Op::SetProp {
id: 2,
prop: Prop::ShaderSource(Some(
"fn shade(uv: vec2f) -> vec4f { return sample_content(uv); }".into(),
)),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
// A layout animation with nothing to animate: the batch is dropped, not
// kept alive by the screen effect's picture.
apply(
&mut c,
vec![Op::Command {
id: 1,
command: Command::LayoutAnimation(crate::LayoutAnimation::EASE_IN_EASE_OUT),
}],
);
assert!(c.commit().is_none());
}
/// Layout in a terminal (`core::terminal_layout`): ratatui's splits in a
/// terminal's 8×16 point Cells.
mod terminal_layout {
use super::*;
use crate::{
StyleValue as V,
geometry::{Edges, size_pt},
};
fn terminal(c: &mut Core<FakeEngine>, on: bool) {
c.set_environment(crate::element::Environment {
cell: on.then(|| size_pt(8.0, 16.0)),
..Default::default()
});
}
fn node(id: NodeId, tag: Tag, parent: NodeId, props: &[(&str, V<'_>)]) -> Vec<Op> {
vec![
Op::Create { id, tag },
style_op(id, props),
Op::Insert {
parent,
child: id,
before: None,
},
]
}
fn view(id: NodeId, parent: NodeId, props: &[(&str, V<'_>)]) -> Vec<Op> {
node(id, Tag::View, parent, props)
}
/// A text `id` (its raw text `id + 1`) in `parent`.
fn text(id: NodeId, parent: NodeId, content: &str) -> Vec<Op> {
vec![
Op::Create { id, tag: Tag::Text },
Op::CreateText {
id: id + 1,
text: content.into(),
},
Op::Insert {
parent: id,
child: id + 1,
before: None,
},
Op::Insert {
parent,
child: id,
before: None,
},
]
}
fn laid_out(ops: Vec<Op>) -> MountBatch {
let mut c = core();
terminal(&mut c, true);
apply(&mut c, ops);
c.commit().unwrap()
}
/// No frame, or one of no size.
fn left_out(batch: &MountBatch, id: NodeId) -> bool {
frame_of(batch, id)
.is_none_or(|f| f.size.width == Points::ZERO && f.size.height == Points::ZERO)
}
/// A pressable box 40pt high with a 1pt border, 6pt / 12pt padding and
/// a label.
fn button() -> Vec<Op> {
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("height", V::Number(40.0)),
("borderWidth", V::Number(1.0)),
("paddingVertical", V::Number(6.0)),
("paddingHorizontal", V::Number(12.0)),
],
);
ops.push(Op::Listen {
id: 2,
event: EventKind::Press,
enabled: true,
});
ops.extend(text(4, 2, "OK"));
ops
}
#[test]
fn a_button_is_one_row() {
let batch = laid_out(button());
// No border nor vertical padding, its height its label's; a
// column of padding each side.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 32.0, 16.0)));
assert_eq!(frame_of(&batch, 4), Some(rect(8.0, 0.0, 16.0, 16.0)));
}
#[test]
fn a_label_on_a_point_keeps_its_row() {
// A plot's label: a point of no size (absolute, 0 × 0) at a bar's
// end, a row whose text keeps its size. Its row is
// its own, not the point's none: above the point for an upright
// bar (`align-items: flex-end`), below it for a tag (`flex-start`),
// centered along the point as CSS's unsafe alignment.
let label = |align: &'static str| {
let mut ops = view(
2,
ROOT_ID,
&[("width", V::Number(320.0)), ("height", V::Number(160.0))],
);
ops.extend(view(
3,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(80.0)),
("top", V::Number(96.0)),
("width", V::Number(0.0)),
("height", V::Number(0.0)),
("flexDirection", V::Str("row")),
("justifyContent", V::Str("center")),
("alignItems", V::Str(align)),
],
));
ops.extend(text(4, 3, "42"));
laid_out(ops)
};
let above = label("flex-end");
assert_eq!(frame_of(&above, 3), Some(rect(80.0, 96.0, 0.0, 0.0)));
assert_eq!(frame_of(&above, 4), Some(rect(-8.0, -16.0, 16.0, 16.0)));
let below = label("flex-start");
assert_eq!(frame_of(&below, 4), Some(rect(-8.0, 0.0, 16.0, 16.0)));
}
#[test]
fn a_box_of_absolute_children_keeps_its_explicit_height() {
// A table's header: 32pt high, its one cell absolute in it.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("stretch")),
("height", V::Number(32.0)),
],
);
ops.extend(view(
3,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("top", V::Number(0.0)),
("bottom", V::Number(0.0)),
("width", V::Number(80.0)),
],
));
ops.extend(text(4, 3, "Symbol"));
let batch = laid_out(ops);
// Two rows, as its content has none to give it.
assert_eq!(frame_of(&batch, 2).map(|f| f.size.height), Some(px(32.0)));
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 80.0, 32.0)));
}
#[test]
fn an_absolute_box_on_its_bottom_inset_is_as_tall_as_its_content() {
// A toast stack as tall as its toasts measured, none at first: the
// toast's slot pinned to its bottom, the toast two texts in
// padding.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(160.0)),
("height", V::Number(0.0)),
],
);
ops.extend(view(
3,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("bottom", V::Number(0.0)),
],
));
ops.extend(view(
5,
3,
&[
("paddingVertical", V::Number(12.0)),
("backgroundColor", V::Str("#333333")),
],
));
ops.extend(text(6, 5, "Saved"));
ops.extend(text(8, 5, "Q3"));
let batch = laid_out(ops);
let frame = frame_of(&batch, 3).expect("the slot is laid out");
assert!(
frame.size.height >= px(32.0),
"its two rows at least, not the stack's height: {frame:?}"
);
assert_eq!(
frame.origin.y + frame.size.height,
Points::ZERO,
"its bottom on the stack's: {frame:?}"
);
assert_eq!(
frame_of(&batch, 8).map(|f| f.size.height),
Some(px(16.0)),
"its second text shows"
);
}
#[test]
fn a_grids_one_row_stretches_over_its_known_height() {
// A dock's panel: a slot 96pt high, the panel a grid of one cell
// over all of it (inset 0), the cell a box whose content is all
// absolute (an editor's layers).
let mut ops = view(
10,
ROOT_ID,
&[
("alignSelf", V::Str("stretch")),
("height", V::Number(96.0)),
],
);
ops.extend(view(
2,
10,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("top", V::Number(0.0)),
("bottom", V::Number(0.0)),
("display", V::Str("grid")),
("gridTemplateColumns", V::Str("1fr")),
("gridTemplateRows", V::Str("1fr")),
],
));
ops.extend(view(3, 2, &[]));
ops.extend(view(
4,
3,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("top", V::Number(0.0)),
],
));
ops.extend(text(20, 4, "let total"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 3).map(|f| f.size.height), Some(px(96.0)));
}
#[test]
fn a_grids_items_span_their_columns_and_rows() {
let s = |v: &'static str| V::Str(v);
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", s("flex-start")),
("width", V::Number(240.0)),
("display", s("grid")),
("gridTemplateColumns", s("1fr 1fr 1fr")),
],
);
// `col-span-2`, then one track; `row-span-2` under the span, then
// two tracks beside it.
// (A text takes two ids, its own and its raw text's.)
ops.extend(view(3, 2, &[("gridColumn", s("span 2"))]));
ops.extend(text(4, 3, "wide"));
ops.extend(text(6, 2, "a"));
ops.extend(view(8, 2, &[("gridRow", s("span 2"))]));
ops.extend(text(10, 8, "tall"));
ops.extend(text(12, 2, "b"));
ops.extend(text(14, 2, "c"));
ops.extend(text(16, 2, "d"));
let batch = laid_out(ops);
let at = |id| {
frame_of(&batch, id)
.map(|f| (f.origin.x.0, f.origin.y.0, f.size.width.0, f.size.height.0))
};
assert_eq!(at(3), Some((0.0, 0.0, 160.0, 16.0)));
assert_eq!(at(6), Some((160.0, 0.0, 80.0, 16.0)));
assert_eq!(at(8), Some((0.0, 16.0, 80.0, 32.0)));
assert_eq!(at(12), Some((80.0, 16.0, 80.0, 16.0)));
assert_eq!(at(14), Some((160.0, 16.0, 80.0, 16.0)));
// The next row's first free track is beside the tall item.
assert_eq!(at(16), Some((80.0, 32.0, 80.0, 16.0)));
}
#[test]
fn a_charts_margins_are_gutters_of_their_size() {
// A chart (a box of layers) keeping 58pt at its right and 21pt
// below for its axes' labels, in a bordered card as wide as the
// 320pt viewport (a box never lays a child out past its own
// border, so a wider card would be held to it): seven Cells and a
// row; a box of content keeps two Cells of spacing.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(320.0)),
("borderWidth", V::Number(1.0)),
],
);
ops.extend(view(
3,
2,
&[
("marginRight", V::Number(58.0)),
("marginBottom", V::Number(21.0)),
("height", V::Number(32.0)),
],
));
ops.extend(view(
4,
3,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("top", V::Number(0.0)),
],
));
ops.extend(text(5, 4, "41.83"));
ops.extend(view(10, 2, &[("marginRight", V::Number(58.0))]));
ops.extend(text(11, 10, "Below"));
let batch = laid_out(ops);
let chart = frame_of(&batch, 3).unwrap();
let below = frame_of(&batch, 10).unwrap();
assert_eq!(chart.size.width, px(320.0 - 16.0 - 56.0), "{chart:?}");
assert_eq!(below.size.width, px(320.0 - 16.0 - 16.0), "{below:?}");
assert_eq!(
below.origin.y,
chart.origin.y + chart.size.height + px(16.0)
);
}
#[test]
fn an_anchor_of_no_width_keeps_its_height_to_center_its_label_in() {
// An axis's tick label: an absolute line of no width 64pt high
// (four rows), its label centered in it by automatic margins.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("stretch")),
("height", V::Number(96.0)),
],
);
ops.extend(view(
3,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(80.0)),
("top", V::Number(0.0)),
("width", V::Number(0.0)),
("height", V::Number(64.0)),
("flexDirection", V::Str("row")),
],
));
ops.extend(view(4, 3, &[]));
ops.extend(view(5, 4, &[("marginVertical", V::Str("auto"))]));
ops.extend(text(6, 5, "41.83"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 3).map(|f| f.size.height), Some(px(64.0)));
let label = frame_of(&batch, 5).unwrap();
// Rows 1 or 2 of the four: centered, not at the anchor's top.
assert!(
label.origin.y == px(16.0) || label.origin.y == px(32.0),
"{label:?}"
);
assert_eq!(label.size.width, px(40.0), "{label:?}");
}
#[test]
fn a_label_at_an_axis_end_ends_there_whole() {
// The last tick's label along an x axis: an anchor of no width at
// the plot's right end, its window aligning the label to its end.
// The label keeps its width and ends at the tick, inside the plot,
// rather than being shrunk to `…` past it.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("stretch")),
("height", V::Number(32.0)),
],
);
ops.extend(view(
3,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(160.0)),
("top", V::Number(0.0)),
("width", V::Number(0.0)),
("flexDirection", V::Str("row")),
],
));
ops.extend(view(
4,
3,
&[
("flexGrow", V::Number(1.0)),
("minWidth", V::Number(0.0)),
("flexDirection", V::Str("row")),
("justifyContent", V::Str("flex-end")),
],
));
ops.extend(view(
5,
4,
&[
("flexShrink", V::Number(0.0)),
("marginHorizontal", V::Str("auto")),
],
));
ops.extend(text(6, 5, "100.42"));
let batch = laid_out(ops);
let label = frame_of(&batch, 5).unwrap();
assert_eq!(label.size.width, px(48.0), "{label:?}");
assert_eq!(label.origin.x, px(-48.0), "ends at the tick: {label:?}");
}
#[test]
fn a_card_has_its_border_and_a_padding_row_from_12_points() {
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("borderWidth", V::Number(1.0)),
("padding", V::Number(16.0)),
],
);
ops.extend(text(3, 2, "Title"));
ops.extend(view(5, 2, &[]));
ops.extend(text(6, 5, "One"));
ops.extend(view(8, 2, &[]));
ops.extend(text(9, 8, "Two"));
let batch = laid_out(ops);
// A border Cell each side, a column and a row of padding:
// 1 + 1 + 3 + 1 + 1 rows, 1 + 1 + 5 + 1 + 1 columns.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 72.0, 112.0)));
assert_eq!(frame_of(&batch, 3), Some(rect(16.0, 32.0, 40.0, 16.0)));
assert_eq!(frame_of(&batch, 5), Some(rect(16.0, 48.0, 40.0, 16.0)));
assert_eq!(frame_of(&batch, 8), Some(rect(16.0, 64.0, 40.0, 16.0)));
}
#[test]
fn a_sidebar_keeps_its_columns_and_the_content_fills() {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(3, 2, &[("width", V::Number(240.0))]));
ops.extend(text(4, 3, "Nav"));
ops.extend(view(6, 2, &[("flexGrow", V::Number(1.0))]));
ops.extend(text(7, 6, "Body"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 240.0, 16.0)));
assert_eq!(frame_of(&batch, 6), Some(rect(240.0, 0.0, 80.0, 16.0)));
}
#[test]
fn column_gaps_cost_a_row_from_16_points() {
for (gap, second) in [(12.0, 16.0), (16.0, 32.0), (32.0, 32.0)] {
let mut ops = view(2, ROOT_ID, &[("rowGap", V::Number(gap))]);
ops.extend(text(3, 2, "One"));
ops.extend(text(5, 2, "Two"));
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 5).map(|f| f.origin.y),
Some(Points(second)),
"a gap of {gap}"
);
}
}
#[test]
fn sections_and_card_rows_keep_one_blank_row() {
let mut ops = view(2, ROOT_ID, &[("rowGap", V::Number(24.0))]);
// A card: a border, its rows 16pt apart inside.
ops.extend(view(
3,
2,
&[
("borderWidth", V::Number(1.0)),
("marginBottom", V::Number(24.0)),
],
));
ops.extend(view(4, 3, &[("rowGap", V::Number(16.0))]));
ops.extend(text(5, 4, "One"));
ops.extend(text(7, 4, "Two"));
ops.extend(view(
9,
2,
&[
("borderWidth", V::Number(1.0)),
("padding", V::Number(12.0)),
],
));
ops.extend(view(10, 9, &[]));
ops.extend(text(11, 10, "Three"));
let batch = laid_out(ops);
// Inside the card a blank row between its rows; between the cards
// one, the gap and the margin collapsed into it; the second card's
// 12pt padding a row above and below.
assert_eq!(frame_of(&batch, 7).map(|f| f.origin.y), Some(Points(32.0)));
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 320.0, 80.0)));
assert_eq!(frame_of(&batch, 9), Some(rect(0.0, 96.0, 320.0, 80.0)));
}
#[test]
fn a_badge_with_a_dot_is_one_row_of_its_text() {
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("flexDirection", V::Str("row")),
("columnGap", V::Number(6.0)),
("height", V::Number(26.0)),
("paddingHorizontal", V::Number(10.0)),
("borderWidth", V::Number(1.0)),
],
);
ops.extend(view(
3,
2,
&[("width", V::Number(8.0)), ("height", V::Number(8.0))],
));
ops.extend(text(4, 2, "2 online"));
let batch = laid_out(ops);
// The dot draws nothing and is left out; the badge is its text and
// a column each side, no border.
assert!(left_out(&batch, 3));
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 80.0, 16.0)));
assert_eq!(frame_of(&batch, 4), Some(rect(8.0, 0.0, 64.0, 16.0)));
}
#[test]
fn a_gray_key_before_its_name_keeps_its_cell() {
// A legend's key: an 8pt round dot of a gray series before its
// name. It is the series' only mark, so it keeps a Cell (a `●`)
// though its fill has no hue; between two texts, or as light as
// the page, it is a decoration.
let row = |fill: &'static str, before: bool| {
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("flexDirection", V::Str("row")),
("columnGap", V::Number(8.0)),
],
);
if before {
ops.extend(text(6, 2, "A"));
}
ops.extend(view(
3,
2,
&[
("width", V::Number(8.0)),
("height", V::Number(8.0)),
("borderRadius", V::Number(4.0)),
("backgroundColor", V::Str(fill)),
],
));
ops.extend(text(4, 2, "Memory"));
laid_out(ops)
};
let key = row("#8a8a8a", false);
assert_eq!(frame_of(&key, 3), Some(rect(0.0, 0.0, 8.0, 16.0)));
assert_eq!(frame_of(&key, 4), Some(rect(16.0, 0.0, 48.0, 16.0)));
assert!(left_out(&row("#8a8a8a", true), 3), "between two texts");
assert!(left_out(&row("#f4f4f4", false), 3), "as light as the page");
}
#[test]
fn a_list_against_a_frame_s_line_keeps_a_column_from_it() {
// A tree's box: a border with no padding of its own around a list
// padded 6pt (no Cell by itself): the rows keep a column from
// the line on each side, never start or end on it.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(160.0)),
("borderWidth", V::Number(1.0)),
],
);
ops.extend(view(4, 2, &[("padding", V::Number(6.0))]));
ops.extend(view(
6,
4,
&[
("flexDirection", V::Str("row")),
("justifyContent", V::Str("space-between")),
],
));
ops.extend(text(8, 6, "app"));
ops.extend(text(10, 6, "1.4 KB"));
ops.extend(text(12, 4, "nsh.json"));
let c = laid_out(ops);
// 20 columns: the line's, 18 for the list, a column each side of
// its rows.
assert_eq!(frame_of(&c, 4), Some(rect(8.0, 16.0, 144.0, 32.0)));
assert_eq!(frame_of(&c, 6), Some(rect(8.0, 0.0, 128.0, 16.0)));
assert_eq!(frame_of(&c, 12), Some(rect(8.0, 16.0, 128.0, 16.0)));
}
#[test]
fn a_closed_reveal_takes_no_row() {
// An accordion's panel sprung shut: a clip of no height around
// its content, which shows none of it; the next title follows.
let mut ops = view(2, ROOT_ID, &[("alignSelf", V::Str("flex-start"))]);
ops.extend(text(4, 2, "Shipping"));
ops.extend(view(
6,
2,
&[("height", V::Number(0.0)), ("overflow", V::Str("hidden"))],
));
ops.extend(text(8, 6, "Two to five days"));
ops.extend(text(10, 2, "Returns"));
let c = laid_out(ops);
assert_eq!(frame_of(&c, 6).map(|f| f.size.height), Some(Points(0.0)));
assert_eq!(frame_of(&c, 10).map(|f| f.origin.y), Some(Points(16.0)));
}
#[test]
fn a_tile_keeps_its_content_stacked() {
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Str("48%")),
("borderWidth", V::Number(1.0)),
("padding", V::Number(12.0)),
("rowGap", V::Number(2.0)),
],
);
ops.push(Op::Listen {
id: 2,
event: EventKind::Press,
enabled: true,
});
// An icon in a ringed circle: its layer holds only the icon.
ops.extend(view(
3,
2,
&[
("width", V::Number(32.0)),
("height", V::Number(32.0)),
("borderWidth", V::Number(1.0)),
("marginBottom", V::Number(8.0)),
],
));
ops.extend(view(
4,
3,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("bottom", V::Number(0.0)),
],
));
ops.extend(node(
5,
Tag::Canvas,
4,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
ops.extend(text(6, 2, "Focus"));
ops.extend(text(8, 2, "Until tomorrow"));
let batch = laid_out(ops);
// A control: no border, its title above its detail, as tall as
// both; 48% of 40 columns is 19.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 152.0, 32.0)));
assert_eq!(frame_of(&batch, 6), Some(rect(8.0, 0.0, 136.0, 16.0)));
assert_eq!(frame_of(&batch, 8), Some(rect(8.0, 16.0, 136.0, 16.0)));
assert!(left_out(&batch, 5));
assert!(left_out(&batch, 3));
}
#[test]
fn a_bordered_box_around_one_row_has_no_border() {
// A tab list: a hairline around a row of tabs, 2pt inside.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("flexDirection", V::Str("row")),
("borderWidth", V::Number(1.0)),
("padding", V::Number(2.0)),
],
);
for (id, label) in [(3, "One"), (6, "Two")] {
ops.extend(view(id, 2, &[("paddingHorizontal", V::Number(8.0))]));
ops.push(Op::Listen {
id,
event: EventKind::Press,
enabled: true,
});
ops.extend(text(id + 1, id, label));
}
let batch = laid_out(ops);
// One row, no border Cells; mounted without its border, so the
// platform draws none either.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 80.0, 16.0)));
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 40.0, 16.0)));
let widths = view_style_of(&batch, 2).unwrap().borders.widths;
assert_eq!(widths, Edges::all(Points::ZERO));
}
#[test]
fn a_card_keeps_its_border_mounted() {
let mut ops = view(2, ROOT_ID, &[("borderWidth", V::Number(1.0))]);
ops.extend(view(3, 2, &[]));
ops.extend(text(4, 3, "One"));
ops.extend(text(6, 3, "Two"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 320.0, 64.0)));
let widths = view_style_of(&batch, 2).unwrap().borders.widths;
assert_eq!(widths, Edges::all(Points(1.0)));
}
#[test]
fn a_filled_composer_keeps_its_border_around_its_field() {
let frame = |field: bool| {
let mut ops = view(
2,
ROOT_ID,
&[
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(12.0)),
("backgroundColor", V::Str("#333333")),
],
);
if field {
ops.extend(node(3, Tag::Input, 2, &[]));
} else {
ops.extend(text(3, 2, "Draft"));
}
ops.extend(view(6, 2, &[("flexDirection", V::Str("row"))]));
ops.extend(text(7, 6, "Send"));
view_style_of(&laid_out_on_surfaces(ops), 2)
.unwrap()
.borders
.widths
};
// Around a field the line stays; a plain filled card is its band.
assert_eq!(frame(true), Edges::all(Points(1.0)));
assert_eq!(frame(false), Edges::all(Points::ZERO));
}
#[test]
fn an_icon_button_shows_its_label_or_is_left_out() {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(text(3, 2, "Invoice"));
for (id, label) in [(5, Some("More")), (8, None)] {
ops.extend(view(
id,
2,
&[("width", V::Number(28.0)), ("height", V::Number(28.0))],
));
ops.push(Op::Listen {
id,
event: EventKind::Press,
enabled: true,
});
if let Some(label) = label {
ops.push(Op::SetProp {
id,
prop: Prop::Accessibility(AccessibilityProp::Label(Some(label.into()))),
});
}
ops.extend(node(
id + 1,
Tag::Canvas,
id,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
}
let batch = laid_out(ops);
// One row: the labelled one is its label, the other left out.
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.height),
Some(Points(16.0))
);
assert_eq!(frame_of(&batch, 5), Some(rect(56.0, 0.0, 32.0, 16.0)));
assert!(left_out(&batch, 8));
// The painter draws the label of the one laid out as its label.
assert!(view_style_of(&batch, 5).is_some_and(|s| s.shows_label));
}
#[test]
fn a_cover_control_over_a_card_is_not_shown_as_its_label() {
// A card's whole-card press target: a labelled control pinned over
// it (absolute, every inset 0) holding one empty view, and a
// labelled control holding nothing. Neither is an icon control
// whose content was left out: their content is nothing, so the
// layout gives them no row of their label and the painter must not
// draw it over the card's text.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("padding", V::Number(12.0)),
("borderWidth", V::Number(1.0)),
],
);
ops.extend(text(3, 2, "Card title"));
for (id, holds) in [(5, true), (7, false)] {
ops.extend(view(
id,
2,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("right", V::Number(0.0)),
("bottom", V::Number(0.0)),
("left", V::Number(0.0)),
],
));
ops.push(Op::Listen {
id,
event: EventKind::Press,
enabled: true,
});
ops.push(Op::SetProp {
id,
prop: Prop::Accessibility(AccessibilityProp::Label(Some("Open the card".into()))),
});
if holds {
ops.extend(view(id + 1, id, &[]));
}
}
let batch = laid_out(ops);
for id in [5, 7] {
// Pinned over the card's rows, not one row of its label.
let frame = frame_of(&batch, id).unwrap();
assert!(frame.size.height > px(16.0), "{id}: {frame:?}");
assert!(
view_style_of(&batch, id).is_none_or(|s| !s.shows_label),
"{id}"
);
}
}
#[test]
fn a_measured_leaf_stops_at_its_maximum_height() {
// A maximum adds no rows, so it holds for a text and a field as for
// any box: past it their content scrolls (a field) or is clipped.
// Thirty rows of 40 columns (320pt) each.
let long = "x".repeat(40 * 30);
let mut ops = view(2, ROOT_ID, &[]);
ops.extend(text(3, 2, &long));
ops.push(style_op(3, &[("maxHeight", V::Number(80.0))]));
ops.extend(node(5, Tag::Input, 2, &[("maxHeight", V::Number(80.0))]));
ops.push(Op::SetProp {
id: 5,
prop: Prop::Multiline(true),
});
let mut c = core();
terminal(&mut c, true);
apply(&mut c, ops);
let text = frame_of(&c.commit().unwrap(), 3).unwrap();
c.input_changed(5, &long, 1);
let field = frame_of(&c.commit().unwrap(), 5).unwrap();
// Five rows of 16pt, not thirty.
assert_eq!(text.size.height, px(80.0), "{text:?}");
assert_eq!(field.size.height, px(80.0), "{field:?}");
assert_eq!(field.origin.y, px(80.0), "under the text: {field:?}");
// Short content keeps its own height under the maximum.
c.input_changed(5, &"x".repeat(50), 2);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 5).map(|f| f.size.height), Some(px(32.0)));
}
#[test]
fn a_badge_in_a_section_head_is_its_text() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("columnGap", V::Number(16.0)),
],
);
ops.extend(view(3, 2, &[("flex", V::Number(1.0))]));
ops.extend(text(4, 3, "Team"));
ops.extend(view(
6,
2,
&[
("height", V::Number(16.0)),
("borderRadius", V::Number(13.0)),
("justifyContent", V::Str("center")),
("borderWidth", V::Number(1.0)),
],
));
ops.extend(text(7, 6, "2 online"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 6), Some(rect(256.0, 0.0, 64.0, 16.0)));
assert_eq!(frame_of(&batch, 7), Some(rect(0.0, 0.0, 64.0, 16.0)));
}
#[test]
fn a_badge_pinned_over_an_avatar_is_left_out() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("alignItems", V::Str("center")),
("columnGap", V::Number(16.0)),
],
);
ops.extend(view(
3,
2,
&[
("width", V::Number(64.0)),
("height", V::Number(64.0)),
("borderWidth", V::Number(2.0)),
],
));
ops.extend(view(
4,
3,
&[
("flexGrow", V::Number(1.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
("borderWidth", V::Number(1.0)),
],
));
ops.extend(text(5, 4, "M"));
ops.extend(view(
7,
3,
&[
("position", V::Str("absolute")),
("right", V::Number(0.0)),
("bottom", V::Number(0.0)),
("paddingHorizontal", V::Number(6.0)),
("height", V::Number(20.0)),
("borderWidth", V::Number(2.0)),
],
));
ops.extend(text(8, 7, "PRO"));
ops.extend(view(
10,
2,
&[("flexGrow", V::Number(1.0)), ("rowGap", V::Number(3.0))],
));
ops.extend(text(11, 10, "Margaret Hamilton"));
ops.extend(text(13, 10, "Flight software"));
let batch = laid_out(ops);
// The badge would cover the initials: left out, the initials kept.
assert!(left_out(&batch, 7));
assert_eq!(
frame_of(&batch, 5).map(|f| f.size),
Some(size_pt(8.0, 16.0))
);
// The name above the role, after the avatar and a gap.
let name = frame_of(&batch, 11).unwrap();
assert_eq!(name.size, size_pt(248.0, 16.0));
assert_eq!(
frame_of(&batch, 13).map(|f| f.origin.y),
Some(name.origin.y + Points(16.0))
);
assert_eq!(frame_of(&batch, 10).map(|f| f.origin.x), Some(Points(72.0)));
}
#[test]
fn a_presence_dot_on_an_avatar_is_one_cell_at_its_corner() {
// A 32pt avatar (round: its one row of initials, 4 Cells wide)
// with a 10pt dot of a color of its own at its bottom right: one
// Cell, the avatar's last; a neutral dot (an offline one) is left
// out, and so is one in flow.
let avatar = |dot: &str, absolute: bool| {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(32.0)),
("height", V::Number(32.0)),
("borderRadius", V::Number(16.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
ops.extend(text(4, 3, "AL"));
let mut style = vec![
("width", V::Number(10.0)),
("height", V::Number(10.0)),
("borderRadius", V::Number(5.0)),
("backgroundColor", V::Str(dot)),
];
if absolute {
style.extend([
("position", V::Str("absolute")),
("right", V::Number(-1.0)),
("bottom", V::Number(-1.0)),
]);
}
ops.extend(view(6, 3, &style));
laid_out(ops)
};
let online = avatar("#22c55e", true);
assert!(!left_out(&online, 6));
assert_eq!(frame_of(&online, 6), Some(rect(24.0, 0.0, 8.0, 16.0)));
// A square one row high (a list's avatar), beside its initials.
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(32.0)),
("height", V::Number(16.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
ops.extend(text(4, 3, "AL"));
ops.extend(view(
6,
3,
&[
("width", V::Number(10.0)),
("height", V::Number(10.0)),
("borderRadius", V::Number(5.0)),
("backgroundColor", V::Str("#22c55e")),
("position", V::Str("absolute")),
("right", V::Number(-1.0)),
("bottom", V::Number(-1.0)),
],
));
let row = laid_out(ops);
assert_eq!(frame_of(&row, 4).map(|f| f.origin.x), Some(Points(8.0)));
assert_eq!(frame_of(&row, 6), Some(rect(24.0, 0.0, 8.0, 16.0)));
assert!(left_out(&avatar("#888888", true), 6));
assert!(left_out(&avatar("#22c55e", false), 6));
// Leading a title in a row (an issue's status), one Cell, the
// row's gap after it.
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("alignItems", V::Str("center")),
("columnGap", V::Number(8.0)),
],
);
ops.extend(view(
3,
2,
&[
("width", V::Number(8.0)),
("height", V::Number(8.0)),
("borderRadius", V::Number(4.0)),
("backgroundColor", V::Str("#f59e0b")),
],
));
ops.extend(text(4, 2, "In progress"));
let status = laid_out(ops);
assert_eq!(frame_of(&status, 3), Some(rect(0.0, 0.0, 8.0, 16.0)));
assert_eq!(frame_of(&status, 4).map(|f| f.origin.x), Some(Points(16.0)));
}
#[test]
fn an_icon_is_left_out_with_its_gap_and_margin() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("columnGap", V::Number(8.0)),
],
);
ops.extend(node(
3,
Tag::Canvas,
2,
&[
("width", V::Number(20.0)),
("height", V::Number(20.0)),
("marginRight", V::Number(16.0)),
],
));
ops.extend(text(4, 2, "OK"));
let batch = laid_out(ops);
assert!(left_out(&batch, 3));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 0.0, 16.0, 16.0)));
}
#[test]
fn an_image_keeps_its_box_unless_it_is_an_icon() {
let mut ops = node(
2,
Tag::Image,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(200.0)),
("height", V::Number(100.0)),
],
);
ops.extend(node(
3,
Tag::Image,
ROOT_ID,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
ops.extend(text(4, ROOT_ID, "After"));
let batch = laid_out(ops);
// 25 columns, 6.25 rows to 6: what follows stays below it.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 200.0, 96.0)));
// An icon-sized picture (a star, a logo) would be a blot of half
// blocks: it is left out, and what follows closes up.
assert!(left_out(&batch, 3));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 96.0, 320.0, 16.0)));
}
#[test]
fn an_icon_image_before_a_label_is_left_out_with_its_gap() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("columnGap", V::Number(8.0)),
],
);
ops.extend(node(
3,
Tag::Image,
2,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
ops.extend(text(4, 2, "Inbox"));
// An avatar a little larger than a glyph keeps its picture.
ops.extend(node(
6,
Tag::Image,
ROOT_ID,
&[("width", V::Number(24.0)), ("height", V::Number(24.0))],
));
let batch = laid_out(ops);
assert!(left_out(&batch, 3));
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x), Some(Points(0.0)));
assert!(!left_out(&batch, 6));
}
#[test]
fn an_avatar_holding_only_its_picture_keeps_its_rows() {
// An avatar 40pt square: its initials gone once its picture has
// loaded, it holds only the picture over it (absolute), filling it.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(40.0)),
("height", V::Number(40.0)),
],
);
ops.extend(view(3, 2, &[("flexGrow", V::Number(1.0))]));
ops.extend(node(
4,
Tag::Image,
3,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("bottom", V::Number(0.0)),
],
));
let batch = laid_out(ops);
// Five columns, 2.5 rows to 2.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 40.0, 32.0)));
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 40.0, 32.0)));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 0.0, 40.0, 32.0)));
}
#[test]
fn a_box_holding_a_growing_scroll_view_keeps_its_explicit_height() {
// A picker 160pt tall: a search row, then its grid in a scroll view
// growing into what is left, which has no rows of its content.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("height", V::Number(160.0)),
],
);
ops.extend(text(3, 2, "Search"));
ops.extend(node(5, Tag::Scroll, 2, &[("flexGrow", V::Number(1.0))]));
ops.extend(text(6, 5, "Grid"));
let batch = laid_out(ops);
// Ten rows: one for the search, nine for the grid.
assert_eq!(frame_of(&batch, 2).map(|f| f.size.height.0), Some(160.0));
assert_eq!(frame_of(&batch, 5).map(|f| f.size.height.0), Some(144.0));
}
#[test]
fn a_chart_sized_canvas_keeps_its_size_in_cells() {
let batch = laid_out(node(
2,
Tag::Canvas,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(300.0)),
("height", V::Number(200.0)),
],
));
// 37.5 columns and 12.5 rows, halves rounding down.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 296.0, 192.0)));
}
#[test]
fn justify_space_between_puts_the_space_between() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("justifyContent", V::Str("space-between")),
],
);
ops.extend(text(3, 2, "A"));
ops.extend(text(5, 2, "B"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 8.0, 16.0)));
assert_eq!(frame_of(&batch, 5), Some(rect(312.0, 0.0, 8.0, 16.0)));
}
#[test]
fn wrapped_children_take_lines() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("flexWrap", V::Str("wrap")),
("alignSelf", V::Str("flex-start")),
("width", V::Number(80.0)),
("columnGap", V::Number(8.0)),
],
);
for id in [3, 5, 7] {
ops.extend(text(id, 2, "abcd"));
}
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 32.0, 16.0)));
assert_eq!(frame_of(&batch, 5), Some(rect(40.0, 0.0, 32.0, 16.0)));
assert_eq!(frame_of(&batch, 7), Some(rect(0.0, 16.0, 32.0, 16.0)));
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 80.0, 32.0)));
}
#[test]
fn an_absolute_child_is_placed_by_its_insets() {
let mut ops = view(2, ROOT_ID, &[("height", V::Number(100.0))]);
ops.extend(text(3, 2, "In flow"));
ops.extend(view(
5,
2,
&[
("position", V::Str("absolute")),
("top", V::Number(16.0)),
("left", V::Number(16.0)),
],
));
ops.extend(text(6, 5, "X"));
let batch = laid_out(ops);
// It takes no room: the text in flow stays at the top.
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 320.0, 16.0)));
assert_eq!(frame_of(&batch, 5), Some(rect(16.0, 16.0, 8.0, 16.0)));
}
#[test]
fn a_scroll_view_lays_its_content_out_unbounded() {
let mut ops = node(2, Tag::Scroll, ROOT_ID, &[("height", V::Number(64.0))]);
for i in 0..10u32 {
ops.extend(text(10 + 2 * i, 2, "Line"));
}
let batch = laid_out(ops);
// Four rows of it shown, all ten laid out, a column narrower than
// the view for its bar.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 320.0, 64.0)));
assert_eq!(frame_of(&batch, 28), Some(rect(0.0, 144.0, 312.0, 16.0)));
let content = batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(*size),
_ => None,
});
assert_eq!(content, Some(size_pt(320.0, 160.0)));
}
/// A padded scroll view's content holds its padding once on each
/// side, as with Taffy's layout: a horizontal one's column of padding
/// each side (from 16pt) around a text that fits is as wide as the
/// view, and around a wider one scrolls to the right column and no
/// further.
#[test]
fn a_scroll_view_holds_its_trailing_padding_once() {
let content = |width: f32| {
let mut ops = node(
2,
Tag::Scroll,
ROOT_ID,
&[("width", V::Number(160.0)), ("padding", V::Number(16.0))],
);
ops.push(Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
});
ops.extend(node(
4,
Tag::Text,
2,
&[("width", V::Number(width)), ("flexShrink", V::Number(0.0))],
));
ops.push(Op::CreateText {
id: 5,
text: "ABCDE".into(),
});
ops.push(Op::Insert {
parent: 4,
child: 5,
before: None,
});
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x.0), Some(8.0));
batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(size.width.0),
_ => None,
})
};
assert_eq!(content(144.0), Some(160.0));
assert_eq!(content(400.0), Some(416.0));
}
#[test]
fn a_horizontal_scroll_view_lays_its_content_out_unbounded_along_x() {
let mut ops = node(2, Tag::Scroll, ROOT_ID, &[("width", V::Number(24.0))]);
ops.push(Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
});
ops.extend(node(
4,
Tag::Text,
2,
&[("width", V::Number(40.0)), ("flexShrink", V::Number(0.0))],
));
ops.push(Op::CreateText {
id: 5,
text: "ABCDE".into(),
});
ops.push(Op::Insert {
parent: 4,
child: 5,
before: None,
});
let batch = laid_out(ops);
// Three columns shown, the text's five laid out.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 24.0, 16.0)));
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 0.0, 40.0, 16.0)));
let content = batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(*size),
_ => None,
});
assert_eq!(content, Some(size_pt(40.0, 16.0)));
}
#[test]
fn a_native_component_takes_its_explicit_size() {
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Native,
},
Op::SetProp {
id: 2,
prop: Prop::Component("example.label".into()),
},
];
ops.push(style_op(
2,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(80.0)),
("height", V::Number(32.0)),
],
));
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
let batch = laid_out(ops);
// Laid out where the platform draws it, or leaves it blank.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 80.0, 32.0)));
}
/// The border widths node `id` is mounted with, last.
fn widths(batch: &MountBatch, id: NodeId) -> Option<Edges<Points>> {
batch.items.iter().rev().find_map(|i| match i {
MountItem::ViewStyle { id: v, style } if *v == id => Some(style.borders.widths),
_ => None,
})
}
/// Laid out in a dark terminal (its page black).
fn laid_out_on_surfaces(ops: Vec<Op>) -> MountBatch {
let mut c = core();
c.set_environment(crate::element::Environment {
cell: Some(size_pt(8.0, 16.0)),
dark: true,
..Default::default()
});
apply(&mut c, ops);
c.commit().unwrap()
}
#[test]
fn a_circle_has_no_border_and_keeps_its_initials_on_a_row() {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(20.0)),
("height", V::Number(20.0)),
("borderRadius", V::Number(10.0)),
("borderWidth", V::Number(1.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
ops.extend(view(4, 3, &[]));
ops.extend(text(5, 4, "DK"));
let batch = laid_out(ops);
// Two columns, no border: its initials on one row.
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 16.0, 16.0)));
assert_eq!(frame_of(&batch, 5), Some(rect(0.0, 0.0, 16.0, 16.0)));
}
#[test]
fn a_text_keeps_its_longest_word_while_a_sibling_can_shrink() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("width", V::Number(120.0)),
("columnGap", V::Number(24.0)),
],
);
ops.extend(text(3, 2, "Hello world"));
ops.extend(view(5, 2, &[]));
ops.extend(text(6, 5, "Description"));
let batch = laid_out(ops);
// 11 + 2 + 11 columns in 15: the gap gives one, then both texts
// their columns down to their longest words.
let a = frame_of(&batch, 3).unwrap();
let b = frame_of(&batch, 5).unwrap();
assert!(a.size.width >= Points(40.0), "{a:?}");
assert!(b.size.width >= Points(40.0), "{b:?}");
assert!(b.origin.x - (a.origin.x + a.size.width) <= Points(8.0));
}
#[test]
fn a_track_over_a_blank_rail_is_placed() {
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(80.0)),
],
);
ops.push(Op::Listen {
id: 2,
event: EventKind::Press,
enabled: true,
});
ops.extend(text(3, 2, " "));
ops.extend(view(
5,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("top", V::Number(0.0)),
("width", V::Number(40.0)),
],
));
ops.extend(text(6, 5, "━━━━━"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 5), Some(rect(0.0, 0.0, 40.0, 16.0)));
}
#[test]
fn a_bar_pinned_over_a_scroll_view_is_placed() {
let mut ops = view(2, ROOT_ID, &[]);
ops.extend(node(3, Tag::Scroll, 2, &[("height", V::Number(64.0))]));
for i in 0..6u32 {
ops.extend(text(10 + 2 * i, 3, "Line"));
}
ops.extend(view(
30,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("bottom", V::Number(0.0)),
],
));
ops.extend(text(31, 30, "Search"));
let batch = laid_out(ops);
// Over the scroll view's last row, not left out.
let bar = frame_of(&batch, 30).unwrap();
assert_eq!(
(bar.origin.y, bar.size.height),
(Points(48.0), Points(16.0))
);
assert!(!left_out(&batch, 31));
}
#[test]
fn a_filled_box_is_a_surface_with_padding_and_no_border() {
let mut ops = view(
2,
ROOT_ID,
&[
("backgroundColor", V::Str("#333333")),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#3a3a3a")),
("padding", V::Number(16.0)),
],
);
ops.extend(text(3, 2, "Title"));
ops.extend(view(5, 2, &[]));
ops.extend(text(6, 5, "Body"));
let batch = laid_out_on_surfaces(ops);
// A row of padding above and below, two columns each side.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 320.0, 64.0)));
assert_eq!(
frame_of(&batch, 3).map(|f| f.origin),
Some(point(Points(16.0), Points(16.0)))
);
assert_eq!(widths(&batch, 2), Some(Edges::all(Points::ZERO)));
}
#[test]
fn a_filled_box_draws_no_border_however_it_stands_out() {
let mut ops = view(
2,
ROOT_ID,
&[
("backgroundColor", V::Str("#1a1a1a")),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#ffffff")),
("padding", V::Number(16.0)),
],
);
ops.extend(text(3, 2, "Title"));
ops.extend(view(5, 2, &[]));
ops.extend(text(6, 5, "Body"));
let batch = laid_out_on_surfaces(ops);
// A face is a line or a fill, never both: a surface's padding, no
// border Cell, however its line stands out.
assert_eq!(
frame_of(&batch, 3).map(|f| f.origin),
Some(point(Points(16.0), Points(16.0)))
);
assert_eq!(widths(&batch, 2), Some(Edges::all(Points::ZERO)));
// Where fills are not bands it is laid out the same: the color
// depth never moves anything.
let mut ops = view(
2,
ROOT_ID,
&[
("backgroundColor", V::Str("#1a1a1a")),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#ffffff")),
("padding", V::Number(16.0)),
],
);
ops.extend(text(3, 2, "Title"));
ops.extend(view(5, 2, &[]));
ops.extend(text(6, 5, "Body"));
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 3).map(|f| f.origin),
Some(point(Points(16.0), Points(16.0)))
);
assert_eq!(widths(&batch, 2), Some(Edges::all(Points::ZERO)));
}
#[test]
fn a_fill_of_its_parents_color_is_no_surface() {
let mut ops = view(2, ROOT_ID, &[("backgroundColor", V::Str("#000000"))]);
ops.extend(view(
3,
2,
&[
("alignSelf", V::Str("flex-start")),
("backgroundColor", V::Str("#000000")),
("paddingHorizontal", V::Number(16.0)),
],
));
ops.extend(text(4, 3, "Same"));
ops.extend(view(6, 3, &[]));
ops.extend(text(7, 6, "Box"));
let batch = laid_out_on_surfaces(ops);
// A column of padding as any box, not a surface's two.
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x), Some(Points(8.0)));
}
#[test]
fn stacked_avatars_keep_their_initials_and_a_column_apart() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("alignItems", V::Str("center")),
],
);
for (n, initials) in ["DK", "FA", "MH", "+1.3k"].iter().enumerate() {
let id = 10 + 10 * n as NodeId;
let margin = if n == 0 { 0.0 } else { -8.0 };
ops.extend(view(
id,
2,
&[
("width", V::Number(20.0)),
("height", V::Number(20.0)),
("borderRadius", V::Number(10.0)),
("borderWidth", V::Number(2.0)),
("marginLeft", V::Number(margin)),
("flexShrink", V::Number(0.0)),
],
));
ops.extend(view(id + 1, id, &[("flexGrow", V::Number(1.0))]));
ops.extend(text(id + 2, id + 1, initials));
}
let batch = laid_out(ops);
// `DK FA MH +1.3k`: no borders, the initials on a row, a column
// between the avatars the negative margins stacked.
assert_eq!(frame_of(&batch, 10), Some(rect(0.0, 0.0, 16.0, 16.0)));
assert_eq!(frame_of(&batch, 20), Some(rect(24.0, 0.0, 16.0, 16.0)));
assert_eq!(frame_of(&batch, 30), Some(rect(48.0, 0.0, 16.0, 16.0)));
assert_eq!(frame_of(&batch, 40), Some(rect(72.0, 0.0, 40.0, 16.0)));
assert_eq!(frame_of(&batch, 42), Some(rect(0.0, 0.0, 40.0, 16.0)));
}
/// A pressable view `id` in `parent`, labelled `label` when given.
fn pressable(
id: NodeId,
parent: NodeId,
props: &[(&str, V<'_>)],
label: Option<&str>,
) -> Vec<Op> {
let mut ops = view(id, parent, props);
ops.push(Op::Listen {
id,
event: EventKind::Press,
enabled: true,
});
if let Some(label) = label {
ops.push(Op::SetProp {
id,
prop: Prop::Accessibility(AccessibilityProp::Label(Some(label.into()))),
});
}
ops
}
#[test]
fn a_split_button_is_one_row_without_a_border() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("alignSelf", V::Str("flex-start")),
("borderWidth", V::Number(1.0)),
("paddingVertical", V::Number(12.0)),
],
);
ops.extend(pressable(
3,
2,
&[("paddingHorizontal", V::Number(12.0))],
None,
));
ops.extend(text(4, 3, "Squash and merge"));
ops.extend(pressable(
6,
2,
&[("width", V::Number(32.0)), ("height", V::Number(32.0))],
Some("More"),
));
ops.extend(node(
7,
Tag::Canvas,
6,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
let batch = laid_out(ops);
// A group of controls is never a card: one row, no border.
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.height),
Some(Points(16.0))
);
assert_eq!(
frame_of(&batch, 4).map(|f| f.size),
Some(size_pt(128.0, 16.0))
);
assert!(!left_out(&batch, 6));
assert_eq!(widths(&batch, 2), Some(Edges::all(Points::ZERO)));
// Its label and the menu's, `More`, two blank columns apart: the
// label's padding and one.
let (main, more) = (frame_of(&batch, 3).unwrap(), frame_of(&batch, 6).unwrap());
assert_eq!(
more.origin.x - (main.origin.x + main.size.width),
Points(8.0)
);
}
#[test]
fn a_steppers_pair_of_marks_reads_as_one_and_marks_beside_more_keep_a_column() {
// A number input's steppers: `▴` and `▾` alone in their box, and
// the same two marks with a third (a clear `×`) in another.
let marks = |id: NodeId, parent: NodeId, glyphs: &[&str]| {
let mut ops = view(
id,
parent,
&[
("flexDirection", V::Str("row")),
("alignSelf", V::Str("flex-start")),
],
);
for (i, glyph) in glyphs.iter().enumerate() {
let button = id + 2 + 4 * i as NodeId;
ops.extend(pressable(button, id, &[], None));
ops.extend(text(button + 2, button, glyph));
}
ops
};
let mut ops = marks(2, ROOT_ID, &["▴", "▾"]);
ops.extend(marks(20, ROOT_ID, &["×", "▴", "▾"]));
let batch = laid_out_on_surfaces(ops);
let x = |id: NodeId| frame_of(&batch, id).map(|f| f.origin.x);
// The pair: side by side, two columns in all.
assert_eq!((x(4), x(8)), (Some(Points::ZERO), Some(Points(8.0))));
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.width),
Some(Points(16.0))
);
// Three marks: a column between each.
assert_eq!(
(x(22), x(26), x(30)),
(Some(Points::ZERO), Some(Points(16.0)), Some(Points(32.0)))
);
}
#[test]
fn a_filled_split_button_is_one_row_where_fills_are_not_bands() {
// The gallery's: a filled, framed pill of the main action, a
// divider and the menu's trigger in the menu's view, in a terminal
// that shows no bands (16 colors, no colors).
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("alignSelf", V::Str("flex-start")),
("alignItems", V::Str("stretch")),
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(8.0)),
("backgroundColor", V::Str("#2563eb")),
],
);
ops.extend(pressable(
3,
2,
&[
("height", V::Number(40.0)),
("paddingHorizontal", V::Number(16.0)),
],
None,
));
ops.extend(text(4, 3, "Squash and merge"));
ops.extend(view(
6,
2,
&[
("width", V::Number(1.0)),
("backgroundColor", V::Str("#ffffff")),
],
));
ops.extend(view(8, 2, &[]));
ops.extend(pressable(
10,
8,
&[("width", V::Number(40.0)), ("height", V::Number(40.0))],
Some("Merge options"),
));
ops.extend(node(
12,
Tag::Canvas,
10,
&[("width", V::Number(14.0)), ("height", V::Number(14.0))],
));
let batch = laid_out(ops);
// One row, no border, its label whole.
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.height),
Some(Points(16.0))
);
assert_eq!(widths(&batch, 2), Some(Edges::all(Points::ZERO)));
assert_eq!(
frame_of(&batch, 4).map(|f| f.size),
Some(size_pt(128.0, 16.0))
);
}
#[test]
fn a_filled_card_around_an_inset_well_draws_no_line() {
// The gallery's Dock: a framed card padded 5pt around an inset well
// with a line of its own, drawn as one frame where fills are bands.
let framed_card = |ops: &mut Vec<Op>| {
ops.extend(view(
2,
ROOT_ID,
&[
("flex", V::Number(1.0)),
("padding", V::Number(5.0)),
("gap", V::Number(5.0)),
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(12.0)),
("borderColor", V::Str("#b0b0b0")),
("backgroundColor", V::Str("#262626")),
],
));
};
let mut ops = Vec::new();
framed_card(&mut ops);
ops.extend(view(
3,
2,
&[
("flex", V::Number(1.0)),
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(8.0)),
("borderColor", V::Str("#b0b0b0")),
("backgroundColor", V::Str("#0a0a0a")),
],
));
ops.extend(view(4, 3, &[("paddingLeft", V::Number(12.0))]));
ops.extend(text(5, 4, "Files"));
let batch = laid_out_on_surfaces(ops);
// A face is a line or a fill, never both: the filled card and the
// well inside it draw no line, their colors set them apart.
assert!(widths(&batch, 2).is_none_or(|w| w == Edges::all(Points::ZERO)));
assert!(widths(&batch, 3).is_none_or(|w| w == Edges::all(Points::ZERO)));
// The card's 5pt is a column each side, the well's edge.
let (card, well) = (frame_of(&batch, 2).unwrap(), frame_of(&batch, 3).unwrap());
assert_eq!(well.origin.x, Points(8.0));
assert_eq!(
card.size.width - (well.origin.x + well.size.width),
Points(8.0)
);
// A text right in the card (beside a box: a card of texts alone is
// a one-row chip) keeps that column off its band's edge.
let mut ops = Vec::new();
framed_card(&mut ops);
ops.extend(text(3, 2, "Files"));
ops.extend(view(5, 2, &[]));
ops.extend(text(6, 5, "Open"));
let batch = laid_out_on_surfaces(ops);
assert_eq!(frame_of(&batch, 3).map(|f| f.origin.x), Some(Points(8.0)));
}
#[test]
fn a_band_whose_line_a_padded_card_leaves_out_lies_against_the_cards_line() {
// The gallery's inline command palette: a card padded a Cell inside
// its line, holding (through a wrapper of no insets) a framed,
// filled palette and a caption under it.
let ops = |ops: &mut Vec<Op>| {
ops.extend(view(
2,
ROOT_ID,
&[
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#b0b0b0")),
("paddingHorizontal", V::Number(15.0)),
("paddingVertical", V::Number(15.0)),
],
));
ops.extend(view(3, 2, &[]));
ops.extend(view(
4,
3,
&[
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(12.0)),
("borderColor", V::Str("#b0b0b0")),
("backgroundColor", V::Str("#262626")),
("overflow", V::Str("hidden")),
],
));
ops.extend(view(5, 4, &[("paddingHorizontal", V::Number(8.0))]));
ops.extend(text(6, 5, "Inbox"));
ops.extend(view(8, 4, &[("paddingHorizontal", V::Number(8.0))]));
ops.extend(text(9, 8, "Archive"));
ops.extend(text(11, 3, "In Inbox"));
};
let mut all = Vec::new();
ops(&mut all);
let batch = laid_out_on_surfaces(all);
let wrapper = frame_of(&batch, 3).unwrap();
let palette = frame_of(&batch, 4).unwrap();
// The palette drops its line and reaches across the card's padding
// to its line on both sides.
assert!(widths(&batch, 4).is_none_or(|w| w == Edges::all(Points::ZERO)));
assert_eq!(wrapper.origin.x, Points(16.0));
assert_eq!(palette.origin.x, Points(-8.0));
assert_eq!(palette.size.width, wrapper.size.width + Points(16.0));
// Its rows' text starts where the caption under it does: one column
// inside the card's line, once.
let row = frame_of(&batch, 5).unwrap();
let label = frame_of(&batch, 6).unwrap();
assert_eq!(
palette.origin.x + row.origin.x + label.origin.x,
Points(0.0)
);
assert_eq!(frame_of(&batch, 11).map(|f| f.origin.x), Some(Points(0.0)));
// Laid out the same where fills are left out: the color depth
// never moves anything.
let mut all = Vec::new();
ops(&mut all);
let batch = laid_out(all);
assert!(widths(&batch, 4).is_none_or(|w| w == Edges::all(Points::ZERO)));
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x), Some(Points(-8.0)));
}
#[test]
fn a_fields_marks_and_suffix_keep_one_column_apart() {
// A combobox's row in a terminal: the field, its `×` and `▾`, and
// the app's `⌘K` a margin after them.
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("width", V::Number(400.0)),
],
);
ops.extend(node(4, Tag::Input, 2, &[("flexGrow", V::Number(1.0))]));
ops.extend(pressable(6, 2, &[], None));
ops.extend(text(8, 6, "×"));
ops.extend(pressable(10, 2, &[], None));
ops.extend(text(12, 10, "▾"));
ops.extend(text(14, 2, "⌘K"));
ops.push(style_op(14, &[("marginLeft", V::Number(8.0))]));
let batch = laid_out(ops);
let (clear, toggle, keys) = (
frame_of(&batch, 6).unwrap(),
frame_of(&batch, 10).unwrap(),
frame_of(&batch, 14).unwrap(),
);
assert_eq!(clear.size.width, Points(8.0));
assert_eq!(
toggle.origin.x - (clear.origin.x + clear.size.width),
Points(8.0)
);
assert_eq!(
keys.origin.x - (toggle.origin.x + toggle.size.width),
Points(8.0)
);
}
#[test]
fn a_prefix_showing_nothing_spaces_nothing_before_the_field() {
// A field's prefix holding only its focus ring (its icon left out
// in a terminal), with the column the field keeps after a prefix.
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("width", V::Number(400.0)),
],
);
ops.extend(view(4, 2, &[("marginRight", V::Number(8.0))]));
ops.extend(view(
6,
4,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("bottom", V::Number(0.0)),
("borderWidth", V::Number(1.0)),
],
));
ops.extend(node(8, Tag::Input, 2, &[("flexGrow", V::Number(1.0))]));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 8).map(|f| f.origin.x), Some(Points(0.0)));
}
#[test]
fn a_filled_split_buttons_halves_keep_a_column_apart() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("alignSelf", V::Str("flex-start")),
("backgroundColor", V::Str("#2563eb")),
],
);
ops.extend(pressable(
3,
2,
&[("paddingHorizontal", V::Number(12.0))],
None,
));
ops.extend(text(4, 3, "Merge"));
ops.extend(pressable(
6,
2,
&[("width", V::Number(32.0)), ("height", V::Number(32.0))],
Some("More"),
));
ops.extend(node(
7,
Tag::Canvas,
6,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
let batch = laid_out_on_surfaces(ops);
// One band: a column of the page between its halves, so they read
// as two.
let (main, more) = (frame_of(&batch, 3).unwrap(), frame_of(&batch, 6).unwrap());
assert_eq!(
more.origin.x - (main.origin.x + main.size.width),
Points(8.0)
);
}
#[test]
fn icon_buttons_give_their_labels_before_a_text_wraps() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("width", V::Number(240.0)),
],
);
ops.extend(view(3, 2, &[("flex", V::Number(1.0))]));
ops.extend(text(4, 3, "Harbor at dawn.jpg"));
for (id, label) in [(10, "Add to favorites"), (20, "Share"), (30, "Delete")] {
ops.extend(pressable(
id,
2,
&[("width", V::Number(28.0)), ("height", V::Number(28.0))],
Some(label),
));
ops.extend(node(
id + 1,
Tag::Canvas,
id,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
}
let batch = laid_out(ops);
// 30 columns: the name keeps its 18 on one row, the labels share
// what is left, cut short or left out.
assert_eq!(
frame_of(&batch, 4).map(|f| f.size),
Some(size_pt(144.0, 16.0))
);
let labels: i32 = [10, 20, 30]
.iter()
.map(|&id| frame_of(&batch, id).map_or(0, |f| (f.size.width.0 / 8.0) as i32))
.sum();
assert!(labels <= 12, "{labels}");
}
#[test]
fn a_nested_group_of_icon_buttons_gives_its_labels_before_a_text_wraps() {
// The gallery's card: the name and its details in a column that
// fills the row, the icon buttons in a row of their own.
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("alignItems", V::Str("center")),
("gap", V::Number(12.0)),
("width", V::Number(320.0)),
],
);
ops.extend(view(
3,
2,
&[("flex", V::Number(1.0)), ("gap", V::Number(2.0))],
));
ops.extend(text(4, 3, "Harbor at dawn.jpg"));
ops.extend(text(6, 3, "4032 × 3024 · 3.2 MB"));
ops.extend(view(
8,
2,
&[
("flexDirection", V::Str("row")),
("alignItems", V::Str("center")),
("gap", V::Number(4.0)),
],
));
let labels = [
(10, "Add to favorites"),
(20, "Share…"),
(30, "Download"),
(40, "Move to the trash"),
];
for (id, label) in labels {
ops.extend(pressable(
id,
8,
&[("width", V::Number(40.0)), ("height", V::Number(40.0))],
Some(label),
));
ops.extend(view(id + 1, id, &[]));
ops.extend(node(
id + 2,
Tag::Canvas,
id + 1,
&[("width", V::Number(18.0)), ("height", V::Number(18.0))],
));
}
let batch = laid_out(ops);
// 40 columns: both texts keep one row each, the group gives.
assert_eq!(
frame_of(&batch, 4).map(|f| f.size.height),
Some(Points(16.0))
);
assert_eq!(
frame_of(&batch, 6).map(|f| f.size.height),
Some(Points(16.0))
);
let group = frame_of(&batch, 8).unwrap();
assert!(group.size.width.0 / 8.0 <= 19.0, "{group:?}");
}
#[test]
fn a_badge_of_an_explicit_height_is_not_stretched_down_a_row() {
// A section's head: its title and subtitle, the badge beside them.
let mut ops = view(
2,
ROOT_ID,
&[("flexDirection", V::Str("row")), ("gap", V::Number(16.0))],
);
ops.extend(view(3, 2, &[("flex", V::Number(1.0))]));
ops.extend(text(4, 3, "Split button"));
ops.extend(text(6, 3, "The main action"));
ops.extend(view(
8,
2,
&[
("height", V::Number(16.0)),
("justifyContent", V::Str("center")),
("backgroundColor", V::Str("#333333")),
],
));
ops.extend(text(9, 8, "Open"));
let batch = laid_out_on_surfaces(ops);
assert_eq!(
frame_of(&batch, 8).map(|f| (f.origin.y, f.size.height)),
Some((Points(0.0), Points(16.0)))
);
}
#[test]
fn a_trigger_whose_chevron_grows_shows_its_label() {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(pressable(
10,
2,
&[("width", V::Number(40.0)), ("height", V::Number(40.0))],
Some("Merge options"),
));
// A layer that grows to center the chevron, as a menu trigger's.
ops.extend(view(11, 10, &[("flexGrow", V::Number(1.0))]));
ops.extend(node(
12,
Tag::Canvas,
11,
&[("width", V::Number(14.0)), ("height", V::Number(14.0))],
));
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 10).map(|f| f.size),
Some(size_pt(104.0, 16.0))
);
}
/// A terminal mark, `[ ]` or `( )` and its space, as `nsh-base`'s
/// `mark_view`: texts `id`, `id + 2`, `id + 4`, `id + 6` in view `id - 1`.
fn mark(id: NodeId, parent: NodeId, ends: (&str, &str, &str)) -> Vec<Op> {
let mut ops = view(id - 1, parent, &[("flexDirection", V::Str("row"))]);
ops.extend(text(id, id - 1, ends.0));
ops.extend(text(id + 2, id - 1, ends.1));
ops.extend(text(id + 4, id - 1, ends.2));
ops.extend(text(id + 6, id - 1, " "));
ops
}
#[test]
fn radios_in_a_group_line_up_whether_their_ring_holds_a_dot() {
let mut ops = view(2, ROOT_ID, &[]);
for (row, on) in [(10, false), (30, true), (50, false)] {
ops.extend(pressable(
row,
2,
&[
("flexDirection", V::Str("row")),
("alignItems", V::Str("center")),
("gap", V::Number(12.0)),
("marginHorizontal", V::Number(-8.0)),
("paddingStart", V::Number(8.0)),
("paddingEnd", V::Number(8.0)),
],
None,
));
ops.extend(mark(row + 2, row, ("(", if on { "●" } else { " " }, ")")));
// The app's own ring, a circle the terminal draws none of.
ops.extend(view(
row + 10,
row,
&[
("width", V::Number(32.0)),
("height", V::Number(32.0)),
("borderRadius", V::Number(16.0)),
("borderWidth", V::Number(1.0)),
],
));
if on {
ops.extend(view(
row + 11,
row + 10,
&[
("width", V::Number(10.0)),
("height", V::Number(10.0)),
("borderRadius", V::Number(5.0)),
],
));
}
ops.extend(text(row + 12, row, "Choice"));
}
let batch = laid_out(ops);
// `( ) Choice` on every row: the mark's space is the gap's column.
for row in [10, 30, 50] {
assert!(left_out(&batch, row + 10), "the ring of row {row}");
assert_eq!(
frame_of(&batch, row + 12).map(|f| f.origin.x),
Some(Points(40.0)),
"the label of row {row}"
);
}
}
#[test]
fn checkboxes_side_by_side_keep_two_columns_and_their_marks_one() {
let mut ops = view(
2,
ROOT_ID,
&[("flexDirection", V::Str("row")), ("gap", V::Number(12.0))],
);
for (id, label) in [(10, "Small"), (30, "Regular")] {
ops.extend(pressable(
id,
2,
&[("flexDirection", V::Str("row")), ("gap", V::Number(8.0))],
None,
));
ops.extend(mark(id + 2, id, ("[", " ", "]")));
ops.extend(text(id + 12, id, label));
}
let batch = laid_out(ops);
// `[ ] Small [ ] Regular`.
assert_eq!(frame_of(&batch, 22).map(|f| f.origin.x), Some(Points(32.0)));
let (a, b) = (frame_of(&batch, 10).unwrap(), frame_of(&batch, 30).unwrap());
assert_eq!(a.size.width, Points(72.0));
assert_eq!(b.origin.x - (a.origin.x + a.size.width), Points(16.0));
}
#[test]
fn a_control_of_an_explicit_width_keeps_its_label_whole() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("flexWrap", V::Str("wrap")),
("gap", V::Number(6.0)),
("width", V::Number(320.0)),
],
);
for (id, slot) in [(10, "09:00"), (30, "09:30"), (50, "10:00"), (70, "10:30")] {
ops.extend(pressable(
id,
2,
&[
("flexDirection", V::Str("row")),
("width", V::Number(62.0)),
("height", V::Number(30.0)),
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(8.0)),
],
None,
));
ops.extend(mark(id + 2, id, ("(", " ", ")")));
ops.extend(text(id + 12, id, slot));
}
let batch = laid_out(ops);
// `( ) 09:00` on one row: the slots wrap, their labels do not.
for id in [10, 30, 50, 70] {
let slot = frame_of(&batch, id).unwrap();
assert!(slot.size.width >= Points(72.0), "slot {id}: {slot:?}");
assert_eq!(
frame_of(&batch, id + 12).map(|f| f.size.height),
Some(Points(16.0)),
"slot {id}"
);
}
}
#[test]
fn tiles_and_their_labels_share_a_center_in_equal_columns() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("justifyContent", V::Str("space-between")),
("width", V::Number(320.0)),
],
);
let cases = [
(10, "KJ", "Loads"),
(30, "AT", "Fails"),
(50, "DK", "No picture"),
(70, "", "No name"),
];
for (id, initials, title) in cases {
ops.extend(view(
id,
2,
&[
("flex", V::Number(1.0)),
("alignItems", V::Str("center")),
("gap", V::Number(6.0)),
],
));
ops.extend(view(
id + 2,
id,
&[
("width", V::Number(52.0)),
("height", V::Number(52.0)),
("flexShrink", V::Number(0.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
if !initials.is_empty() {
ops.extend(text(id + 4, id + 2, initials));
}
ops.extend(text(id + 6, id, title));
ops.extend(text(id + 8, id, "idle"));
}
let batch = laid_out(ops);
let center = |id| {
let f = frame_of(&batch, id).unwrap();
f.origin.x.0 + f.size.width.0 / 2.0
};
for (id, ..) in cases {
let column = frame_of(&batch, id).unwrap();
assert_eq!(column.size.width, Points(80.0), "column {id}");
assert!(
(center(id + 2) - center(id + 6)).abs() <= 8.0,
"column {id}: tile {:?}, label {:?}",
frame_of(&batch, id + 2),
frame_of(&batch, id + 6)
);
}
}
#[test]
fn auto_margins_take_the_space_left() {
let mut ops = view(
2,
ROOT_ID,
&[("width", V::Number(320.0)), ("height", V::Number(320.0))],
);
ops.extend(view(
3,
2,
&[
("width", V::Number(160.0)),
("marginHorizontal", V::Str("auto")),
],
));
ops.extend(text(4, 3, "Command"));
ops.extend(view(6, 2, &[("flexDirection", V::Str("row"))]));
ops.extend(text(7, 6, "Title"));
ops.extend(view(9, 6, &[("marginLeft", V::Str("auto"))]));
ops.extend(text(10, 9, "Close"));
let batch = laid_out(ops);
// Centered across a column, as CSS's `margin: 0 auto`.
assert_eq!(frame_of(&batch, 3), Some(rect(80.0, 0.0, 160.0, 16.0)));
// Pushed to a row's end.
assert_eq!(frame_of(&batch, 9).map(|f| f.origin.x), Some(Points(280.0)));
}
#[test]
fn a_list_takes_its_explicit_height_before_its_cells_are_laid_out() {
// Its cells are laid out apart, in the size it is given: content
// of no rows would leave it none to lay them out in.
for horizontal in [false, true] {
let mut ops = view(2, ROOT_ID, &[]);
ops.extend(node(3, Tag::List, 2, &[("height", V::Number(128.0))]));
ops.push(Op::SetProp {
id: 3,
prop: Prop::EstimatedItemSize(px(232.0)),
});
ops.push(Op::SetProp {
id: 3,
prop: Prop::Count(20),
});
ops.push(Op::SetProp {
id: 3,
prop: Prop::Horizontal(horizontal),
});
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 3).map(|f| f.size.height),
Some(Points(128.0)),
"horizontal {horizontal}"
);
}
}
#[test]
fn a_horizontal_scroll_view_s_slides_of_its_full_width_are_one_viewport_each() {
let mut ops = node(2, Tag::Scroll, ROOT_ID, &[("width", V::Number(160.0))]);
ops.push(Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
});
for (id, label) in [(4, "Welcome"), (8, "Import")] {
ops.extend(view(id, 2, &[("width", V::Str("100%"))]));
ops.extend(text(id + 1, id, label));
}
let batch = laid_out(ops);
// A percentage is of the viewport, as CSS's: one slide per view.
assert_eq!(frame_of(&batch, 4), Some(rect(0.0, 0.0, 160.0, 16.0)));
assert_eq!(frame_of(&batch, 8), Some(rect(160.0, 0.0, 160.0, 16.0)));
let content = batch.items.iter().find_map(|i| match i {
MountItem::ScrollContent { id: 2, size } => Some(*size),
_ => None,
});
assert_eq!(content, Some(size_pt(320.0, 16.0)));
}
#[test]
fn a_stretched_scroll_view_s_slides_of_its_full_width_are_one_viewport_each() {
// A carousel's content: no width of its own (stretched by its
// card), its slides `width: 100%` and `flexShrink: 0`, each a
// paragraph that would wrap into a narrower slide.
let mut ops = view(2, ROOT_ID, &[("width", V::Number(240.0))]);
ops.extend(node(4, Tag::Scroll, 2, &[("height", V::Number(96.0))]));
ops.push(Op::SetProp {
id: 4,
prop: Prop::Horizontal(true),
});
for id in [6, 10, 14] {
ops.extend(view(
id,
4,
&[
("width", V::Str("100%")),
("flexShrink", V::Number(0.0)),
("alignItems", V::Str("center")),
("paddingHorizontal", V::Number(24.0)),
],
));
ops.extend(text(
id + 2,
id,
"Capture ideas the moment they arrive, from any device.",
));
}
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 4).map(|f| f.size.width),
Some(Points(240.0))
);
for (i, id) in [6, 10, 14].into_iter().enumerate() {
let f = frame_of(&batch, id).unwrap();
assert_eq!(
(f.origin.x, f.size.width),
(Points(240.0 * i as f32), Points(240.0)),
"slide {id}"
);
}
}
#[test]
fn a_vertical_scroll_view_s_slides_of_its_full_height_are_one_viewport_each() {
let mut ops = view(2, ROOT_ID, &[("width", V::Number(240.0))]);
ops.extend(node(4, Tag::Scroll, 2, &[("height", V::Number(32.0))]));
for id in [6, 10, 14] {
ops.extend(view(
id,
4,
&[
("height", V::Str("100%")),
("justifyContent", V::Str("center")),
],
));
ops.extend(text(id + 2, id, "A line"));
}
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 4).map(|f| f.size.height),
Some(Points(32.0))
);
for (i, id) in [6, 10, 14].into_iter().enumerate() {
let f = frame_of(&batch, id).unwrap();
assert_eq!(
(f.origin.y, f.size.height),
(Points(32.0 * i as f32), Points(32.0)),
"slide {id}"
);
}
}
/// A Rust component whose root is a horizontal scroll view holding
/// its JSX children (a carousel's content).
#[derive(Clone, Copy, PartialEq, crate::element::Props)]
struct StripProps {
children: crate::element::Children,
}
#[crate::prelude::component]
fn Strip(props: StripProps) -> impl crate::prelude::IntoElement {
use crate::prelude::*;
crate::element::scroll().horizontal().child(props.children)
}
#[test]
fn a_component_s_scroll_view_root_lays_its_slides_out_as_a_scroll_view() {
// The host becomes the scroll view when it expands: its slides of
// its full width are one viewport each, as a scroll view's.
let mut c = core();
terminal(&mut c, true);
let mut registry = crate::element::Registry::new();
registry.register::<Strip>();
c.set_components(registry);
let mut ops = view(2, ROOT_ID, &[("width", V::Number(240.0))]);
ops.extend([
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::Component(std::any::type_name::<Strip>().into()),
},
style_op(4, &[("height", V::Number(96.0))]),
Op::Insert {
parent: 2,
child: 4,
before: None,
},
]);
for id in [6, 10, 14] {
ops.extend(view(
id,
4,
&[("width", V::Str("100%")), ("flexShrink", V::Number(0.0))],
));
ops.extend(text(
id + 2,
id,
"Capture ideas the moment they arrive, from any device.",
));
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 4).map(|f| f.size.width),
Some(Points(240.0))
);
for (i, id) in [6, 10, 14].into_iter().enumerate() {
let f = frame_of(&batch, id).unwrap();
assert_eq!(
(f.origin.x, f.size.width),
(Points(240.0 * i as f32), Points(240.0)),
"slide {id}"
);
}
}
#[test]
fn a_text_breaks_its_lines_within_its_maximum_width() {
// A centered paragraph of 54 characters, at most 320pt (40
// columns) wide in a 400pt column: two rows, and its column as
// tall.
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(400.0)),
("alignItems", V::Str("center")),
],
);
ops.extend(text(
6,
2,
"Capture ideas the moment they arrive, from any device.",
));
ops.push(style_op(6, &[("maxWidth", V::Number(320.0))]));
let batch = laid_out(ops);
let f = frame_of(&batch, 6).unwrap();
assert_eq!((f.size.width, f.size.height), (Points(320.0), Points(32.0)));
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.height),
Some(Points(32.0))
);
}
#[test]
fn a_wrapping_row_breaks_its_lines_at_its_fills_bases() {
// Six tiles `flexGrow: 1` at `flexBasis: 28%` in a 320pt (40
// columns) row that wraps: three on a line, as CSS's, each a
// third of it, not six squeezed into one.
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(320.0)),
("flexDirection", V::Str("row")),
("flexWrap", V::Str("wrap")),
("gap", V::Number(8.0)),
],
);
let tiles = [4, 8, 12, 16, 20, 24];
for id in tiles {
ops.extend(view(
id,
2,
&[("flexGrow", V::Number(1.0)), ("flexBasis", V::Str("28%"))],
));
ops.extend(text(id + 2, id, "Interview"));
}
let batch = laid_out(ops);
let frames: Vec<_> = tiles
.iter()
.map(|&id| frame_of(&batch, id).unwrap())
.collect();
let (first, second) = (frames[0].origin.y, frames[3].origin.y);
assert!(second > first, "{frames:?}");
for (i, f) in frames.iter().enumerate() {
assert_eq!(
f.origin.y,
if i < 3 { first } else { second },
"tile {i}: {frames:?}"
);
// A third of the line less its gaps: 12 or 13 columns.
assert!(f.size.width >= Points(96.0), "tile {i}: {frames:?}");
}
}
#[test]
fn a_splitter_pinned_on_a_box_s_edge_takes_its_cell_out_of_the_content() {
// A column header: its title right-aligned, its resize handle (a
// `col-resize` band, absolute at `right: 0`) one Cell over its
// end: the title ends before it, whole.
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(96.0)),
("flexDirection", V::Str("row")),
("justifyContent", V::Str("flex-end")),
],
);
ops.extend(text(4, 2, "Price"));
ops.extend(view(
6,
2,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("bottom", V::Number(0.0)),
("right", V::Number(0.0)),
("width", V::Number(8.0)),
("cursor", V::Str("col-resize")),
],
));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 4), Some(rect(48.0, 0.0, 40.0, 16.0)));
assert_eq!(frame_of(&batch, 6).map(|f| f.origin.x), Some(Points(88.0)));
}
#[test]
fn a_text_cut_short_gives_its_columns_before_the_gaps_of_its_row() {
// A name column (8 columns, no shrinking), two columns, then a
// one-line description too long for the 20 columns left: the
// description is cut short, the gap stays, so the descriptions of
// rows like it line up.
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(160.0)),
("flexDirection", V::Str("row")),
("gap", V::Number(24.0)),
],
);
ops.extend(text(4, 2, "Analytic"));
ops.push(style_op(
4,
&[
("minWidth", V::Number(64.0)),
("flexShrink", V::Number(0.0)),
],
));
ops.extend(text(
6,
2,
"Which pages are visited, counted without who visited them",
));
ops.push(style_op(
6,
&[
("numberOfLines", V::Number(1.0)),
("flexShrink", V::Number(1.0)),
],
));
let batch = laid_out(ops);
// The columns only: the test's text engine ignores `numberOfLines`
// (the platforms' engines keep the text on its one line).
let detail = frame_of(&batch, 6).unwrap();
assert_eq!(
(detail.origin.x, detail.size.width),
(Points(80.0), Points(80.0))
);
}
#[test]
fn a_card_around_an_image_that_fills_it_keeps_its_height() {
// A photo's card: 200 x 150pt, framed and filled, its image
// `flex: 1` (no size of its own, so none it gives the card).
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(200.0)),
("height", V::Number(150.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#888888")),
("backgroundColor", V::Str("#333333")),
],
);
ops.extend(node(3, Tag::Image, 2, &[("flex", V::Number(1.0))]));
let batch = laid_out_on_surfaces(ops);
// Nine rows, the image in what its frame leaves.
assert_eq!(
frame_of(&batch, 2).map(|f| f.size),
Some(size_pt(200.0, 144.0))
);
let image = frame_of(&batch, 3).unwrap();
assert!(image.size.height >= Points(112.0), "{image:?}");
}
#[test]
fn a_bar_of_its_own_color_thinner_than_a_row_keeps_one() {
// A media player's track over its time: 4pt high, filled.
let mut ops = view(2, ROOT_ID, &[("gap", V::Number(4.0))]);
ops.extend(view(
3,
2,
&[
("height", V::Number(4.0)),
("backgroundColor", V::Str("#555555")),
],
));
ops.extend(text(4, 2, "0:00"));
// A hairline (a divider) takes none.
ops.extend(view(
6,
2,
&[
("height", V::Number(1.0)),
("backgroundColor", V::Str("#555555")),
],
));
ops.extend(text(7, 2, "End"));
let batch = laid_out_on_surfaces(ops);
assert_eq!(
frame_of(&batch, 3).map(|f| f.size.height),
Some(Points(16.0))
);
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.y), Some(Points(16.0)));
assert_eq!(frame_of(&batch, 7).map(|f| f.origin.y), Some(Points(32.0)));
}
#[test]
fn a_bar_pinned_under_a_row_of_text_before_it_is_placed() {
// A stepper: its bar absolute before the row of its dots' marks,
// which is drawn over it; a badge after a text is still left out.
let mut ops = view(2, ROOT_ID, &[("height", V::Number(40.0))]);
ops.extend(view(
3,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(8.0)),
("right", V::Number(8.0)),
("top", V::Number(0.0)),
],
));
ops.extend(view(
4,
3,
&[
("height", V::Number(4.0)),
("backgroundColor", V::Str("#555555")),
],
));
ops.extend(view(
5,
2,
&[
("flexDirection", V::Str("row")),
("justifyContent", V::Str("space-between")),
],
));
ops.extend(text(6, 5, "1"));
ops.extend(text(8, 5, "2"));
ops.extend(view(
10,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("top", V::Number(0.0)),
],
));
ops.extend(text(11, 10, "9"));
let batch = laid_out_on_surfaces(ops);
assert_eq!(
frame_of(&batch, 3).map(|f| f.size.height),
Some(Points(16.0))
);
assert!(!left_out(&batch, 4));
assert!(left_out(&batch, 10));
}
#[test]
fn a_ball_the_user_drags_stays_when_its_dot_is_left_out() {
// A 60pt ball of an opaque fill around an 18pt dot, with touch
// handlers (a PanResponder's): the dot is a decoration, the ball
// keeps its box. The same tile without handlers (an onboarding
// slide's icon tile) goes with its icon, and so does a 32pt one.
let ball = |size: f32, handled: bool| {
let mut ops = view(2, ROOT_ID, &[("alignItems", V::Str("flex-start"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(size)),
("height", V::Number(size)),
("borderRadius", V::Number(16.0)),
("backgroundColor", V::Str("#3b82f6")),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
if handled {
ops.push(Op::Listen {
id: 3,
event: EventKind::Touch,
enabled: true,
});
}
ops.extend(view(
4,
3,
&[
("width", V::Number(18.0)),
("height", V::Number(18.0)),
("borderRadius", V::Number(9.0)),
("backgroundColor", V::Str("#ffffff")),
],
));
laid_out_on_surfaces(ops)
};
let batch = ball(60.0, true);
assert!(!left_out(&batch, 3));
assert!(frame_of(&batch, 3).is_some_and(|f| f.size.height.0 >= 48.0));
assert!(left_out(&batch, 4));
assert!(left_out(&ball(60.0, false), 3));
assert!(left_out(&ball(32.0, true), 3));
}
#[test]
fn an_icons_lit_backing_goes_with_its_icon() {
// A quick settings tile's 32pt circle: a lit layer over it (absolute,
// nothing in it, filled) and its 16pt icon centered on it. Without
// the icon the layer would be a solid block beside the switch.
let tile = |size: f32| {
let mut ops = view(2, ROOT_ID, &[("alignItems", V::Str("flex-start"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(size)),
("height", V::Number(size)),
("borderRadius", V::Number(size / 2.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#3a3a3a")),
],
));
ops.extend(view(
4,
3,
&[
("position", V::Str("absolute")),
("top", V::Number(-1.0)),
("left", V::Number(-1.0)),
("right", V::Number(-1.0)),
("bottom", V::Number(-1.0)),
("backgroundColor", V::Str("#3b82f6")),
],
));
ops.extend(node(
5,
Tag::Canvas,
3,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
laid_out_on_surfaces(ops)
};
let batch = tile(32.0);
assert!(left_out(&batch, 3));
assert!(left_out(&batch, 4));
// Larger than an icon, its fill is the box's own: it stays.
assert!(!left_out(&tile(80.0), 3));
}
/// A 188pt stage `stage_h` high holding an absolute ring `size` points
/// across at 34pt, framed by a 1pt line, with a 10pt dot in it when
/// `dot` (an orbit).
fn ring_in_a_stage(size: f32, stage_h: f32, dot: bool) -> MountBatch {
let mut ops = view(
2,
ROOT_ID,
&[("width", V::Number(188.0)), ("height", V::Number(stage_h))],
);
ops.extend(view(
3,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(34.0)),
("top", V::Number(34.0)),
("width", V::Number(size)),
("height", V::Number(size)),
("borderRadius", V::Number(size / 2.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#888888")),
],
));
if dot {
ops.extend(view(
4,
3,
&[
("width", V::Number(10.0)),
("height", V::Number(10.0)),
("borderRadius", V::Number(5.0)),
("backgroundColor", V::Str("#3b82f6")),
],
));
}
laid_out(ops)
}
#[test]
fn an_absolute_ring_larger_than_an_icon_is_its_outline() {
// A pulse's ring: nothing in it, round, its own line; and an orbit
// around the dot on it, which is left out.
for dot in [false, true] {
let batch = ring_in_a_stage(120.0, 188.0, dot);
assert!(!left_out(&batch, 3), "dot: {dot}");
assert_eq!(
widths(&batch, 3),
Some(Edges::all(Points(1.0))),
"dot: {dot}"
);
}
assert!(left_out(&ring_in_a_stage(120.0, 188.0, true), 4));
// An icon's ring is left out as before.
assert!(left_out(&ring_in_a_stage(40.0, 188.0, false), 3));
}
#[test]
fn a_texts_explicit_width_rounds_up_to_hold_its_line() {
// A column of curve names, each 84pt (10.5 Cells) wide, then its
// track: rounded to the nearest, "cubic inOut" would be cut.
for (width, cols) in [(84.0, 11.0), (80.0, 10.0)] {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("width", V::Number(400.0)),
],
);
ops.extend(text(4, 2, "cubic inOut"));
ops.push(style_op(
4,
&[
("width", V::Number(width)),
("numberOfLines", V::Number(1.0)),
],
));
ops.extend(view(
6,
2,
&[("flexGrow", V::Number(1.0)), ("height", V::Number(16.0))],
));
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 4).map(|f| f.size.width),
Some(Points(cols * 8.0)),
"width: {width}"
);
assert_eq!(
frame_of(&batch, 6).map(|f| f.origin.x),
Some(Points(cols * 8.0)),
"width: {width}"
);
}
}
/// A box 86pt (11 Cells) wide holding a label stretched across it
/// (absolute, `left` and `right` 0) of `content`.
fn a_label_across_a_box(content: &str) -> MountBatch {
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("width", V::Number(86.0)),
("height", V::Number(64.0)),
],
);
ops.extend(view(
4,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("top", V::Number(0.0)),
("alignItems", V::Str("flex-end")),
],
));
ops.extend(text(6, 4, content));
laid_out(ops)
}
#[test]
fn a_box_holds_a_label_stretched_across_it() {
// A funnel's stage name in its column: 12 Cells in a box of 11.
let batch = a_label_across_a_box("KYC verified");
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.width),
Some(Points(96.0))
);
assert_eq!(
frame_of(&batch, 6).map(|f| f.size.width),
Some(Points(96.0))
);
// A paragraph laid over it still wraps in it.
let batch = a_label_across_a_box("A paragraph far wider than the box it is laid over");
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.width),
Some(Points(88.0))
);
}
#[test]
fn an_absolute_ring_its_parent_would_cut_is_left_out() {
// The stage is shorter than the ring: its outline would be open.
let batch = ring_in_a_stage(120.0, 64.0, false);
assert!(left_out(&batch, 3));
}
/// A vertical scroll view 160pt (20 Cells) wide and 64pt high in a
/// view of `parent` styles, holding a row whose text is at its right and
/// a view `tall` points high; `scrollbar` set when given.
fn scroll_with_a_right_text(
parent: &[(&str, V<'_>)],
tall: f32,
scrollbar: Option<crate::ScrollbarSetting>,
) -> MountBatch {
let mut ops = view(2, ROOT_ID, parent);
ops.extend(node(
3,
Tag::Scroll,
2,
&[("width", V::Number(160.0)), ("height", V::Number(64.0))],
));
if let Some(setting) = scrollbar {
ops.push(Op::SetProp {
id: 3,
prop: Prop::Scrollbar(setting),
});
}
ops.extend(view(
4,
3,
&[
("flexDirection", V::Str("row")),
("justifyContent", V::Str("flex-end")),
],
));
ops.extend(text(5, 4, "end"));
ops.extend(view(7, 3, &[("height", V::Number(tall))]));
laid_out(ops)
}
fn right_of(batch: &MountBatch, id: NodeId) -> Option<f32> {
frame_of(batch, id).map(|f| (f.origin.x + f.size.width).0)
}
#[test]
fn an_overflowing_scroll_view_keeps_a_column_for_its_bar() {
// Its content is a Cell narrower: the text's last Cell is the one
// before the bar's.
let batch = scroll_with_a_right_text(&[], 200.0, None);
assert_eq!(right_of(&batch, 4), Some(152.0));
assert_eq!(right_of(&batch, 5), Some(152.0));
}
#[test]
fn a_scroll_view_keeps_no_column_when_it_fits_or_hides_its_bar() {
let fits = scroll_with_a_right_text(&[], 16.0, None);
assert_eq!(right_of(&fits, 4), Some(160.0));
let hidden = scroll_with_a_right_text(&[], 200.0, Some(crate::ScrollbarSetting::Hidden));
assert_eq!(right_of(&hidden, 4), Some(160.0));
}
#[test]
fn a_scroll_view_on_its_parents_right_line_keeps_no_column() {
// Framed with no padding: the painter draws the bar on that line.
let batch = scroll_with_a_right_text(
&[
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#888888")),
("alignSelf", V::Str("flex-start")),
],
200.0,
None,
);
assert_eq!(right_of(&batch, 4), Some(160.0));
}
#[test]
fn a_framed_box_stated_three_rows_tall_keeps_its_border_around_a_text() {
// A specimen on a pressable stage: a 76pt box framed on every side
// around one label (and a circle cut by it). It is a box, not a
// badge: its border and the label inside it, three rows.
let mut ops = pressable(
2,
ROOT_ID,
&[
("height", V::Number(104.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
("borderWidth", V::Number(1.0)),
],
None,
);
ops.extend(view(
3,
2,
&[
("width", V::Number(112.0)),
("height", V::Number(76.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
("borderWidth", V::Number(1.5)),
("borderRadius", V::Number(22.0)),
],
));
ops.extend(view(
4,
3,
&[
("position", V::Str("absolute")),
("left", V::Number(-26.0)),
("top", V::Number(-26.0)),
("width", V::Number(72.0)),
("height", V::Number(72.0)),
("borderRadius", V::Number(36.0)),
],
));
ops.extend(text(6, 3, "Click"));
let batch = laid_out(ops);
let specimen = frame_of(&batch, 3).unwrap();
assert_eq!(specimen.size, size_pt(112.0, 48.0));
assert_eq!(frame_of(&batch, 6).map(|f| f.origin.y), Some(Points(16.0)));
// A badge around its text stays one row, without its border.
let mut ops = view(
2,
ROOT_ID,
&[
("alignSelf", V::Str("flex-start")),
("borderWidth", V::Number(1.0)),
("height", V::Number(24.0)),
],
);
ops.extend(text(4, 2, "New"));
let batch = laid_out(ops);
assert_eq!(
frame_of(&batch, 2).map(|f| f.size.height),
Some(Points(16.0))
);
}
#[test]
fn a_code_cell_keeps_its_size_with_its_digit() {
// A one-time code's cells, 36 × 44pt and framed: the one that holds
// a digit is the same box as the empty one, three rows with its
// border, its digit on the middle row.
let cell = |digit: Option<&str>| {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(36.0)),
("height", V::Number(44.0)),
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(8.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
if let Some(digit) = digit {
ops.extend(text(4, 3, digit));
}
laid_out(ops)
};
let (empty, filled) = (cell(None), cell(Some("2")));
assert_eq!(
frame_of(&empty, 3).map(|f| f.size),
Some(size_pt(32.0, 48.0))
);
assert_eq!(
frame_of(&filled, 3).map(|f| f.size),
Some(size_pt(32.0, 48.0))
);
assert_eq!(widths(&filled, 3), Some(Edges::all(Points(1.0))));
assert_eq!(frame_of(&filled, 4).map(|f| f.origin.y), Some(Points(16.0)));
// On a band of its own (a filled cell's fill, unlike the empty
// ones') it is the same box, its band in place of its line: a face
// is a line or a fill, never both.
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(36.0)),
("height", V::Number(44.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#3a3a3a")),
("backgroundColor", V::Str("#2a2a2a")),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
ops.extend(text(4, 3, "2"));
let banded = laid_out_on_surfaces(ops);
assert_eq!(
frame_of(&banded, 3).map(|f| f.size),
Some(size_pt(32.0, 48.0))
);
assert!(widths(&banded, 3).is_none_or(|w| w == Edges::all(Points::ZERO)));
// In a card, too.
let mut ops = view(
2,
ROOT_ID,
&[
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#505050")),
("padding", V::Number(16.0)),
("alignItems", V::Str("center")),
],
);
ops.extend(view(8, 2, &[("flexDirection", V::Str("row"))]));
ops.extend(view(
3,
8,
&[
("width", V::Number(36.0)),
("height", V::Number(44.0)),
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(8.0)),
("borderColor", V::Str("#b0b0b0")),
("backgroundColor", V::Str("#2a2a2a")),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
ops.extend(text(4, 3, "2"));
ops.extend(text(6, 2, "The code is 246810"));
let carded = laid_out_on_surfaces(ops);
assert_eq!(widths(&carded, 2), Some(Edges::all(Points(1.0))));
assert_eq!(
frame_of(&carded, 3).map(|f| f.size),
Some(size_pt(32.0, 48.0))
);
assert!(widths(&carded, 3).is_none_or(|w| w == Edges::all(Points::ZERO)));
// A round one on its band (an avatar's ring around its initials) is
// the band alone, its initials on its first row with its badge
// under them.
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(64.0)),
("height", V::Number(64.0)),
("borderRadius", V::Number(32.0)),
("borderWidth", V::Number(2.0)),
("borderColor", V::Str("#3a3a3a")),
("backgroundColor", V::Str("#2a2a2a")),
],
));
ops.extend(text(4, 3, "MH"));
let ring = laid_out_on_surfaces(ops);
assert!(widths(&ring, 3).is_none_or(|w| w == Edges::all(Points::ZERO)));
assert_eq!(frame_of(&ring, 4).map(|f| f.origin.y), Some(Points(0.0)));
// A circle that low (a group's overflow count) is a badge, one row.
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("width", V::Number(40.0)),
("height", V::Number(40.0)),
("borderRadius", V::Number(20.0)),
("borderWidth", V::Number(2.0)),
("alignItems", V::Str("center")),
("justifyContent", V::Str("center")),
],
));
ops.extend(text(4, 3, "+5"));
assert_eq!(
frame_of(&laid_out(ops), 3).map(|f| f.size.height),
Some(Points(16.0))
);
// Without a width a frame that low is a badge's, one row.
let mut ops = view(2, ROOT_ID, &[("alignSelf", V::Str("flex-start"))]);
ops.extend(view(
3,
2,
&[("height", V::Number(44.0)), ("borderWidth", V::Number(1.0))],
));
ops.extend(text(4, 3, "Tag"));
assert_eq!(
frame_of(&laid_out(ops), 3).map(|f| f.size.height),
Some(Points(16.0))
);
}
#[test]
fn a_box_holds_its_absolute_children_placed_from_its_top() {
// A step's dot (left out) with its label 24pt under it, then the
// buttons: the label keeps a row of its own above them.
let mut ops = view(2, ROOT_ID, &[]);
ops.extend(view(3, 2, &[("width", V::Number(18.0))]));
ops.extend(view(
4,
3,
&[
("width", V::Number(18.0)),
("height", V::Number(18.0)),
("borderRadius", V::Number(9.0)),
("borderWidth", V::Number(1.0)),
],
));
ops.extend(view(
6,
3,
&[
("position", V::Str("absolute")),
("top", V::Number(24.0)),
("left", V::Number(-23.0)),
("width", V::Number(64.0)),
],
));
ops.extend(text(7, 6, "Account"));
ops.extend(text(10, 2, "Next step"));
let batch = laid_out(ops);
let label = frame_of(&batch, 6).unwrap();
let next = frame_of(&batch, 10).unwrap();
assert!(
label.origin.y + label.size.height <= next.origin.y,
"label {label:?}, next {next:?}"
);
}
#[test]
fn a_disclosure_keeps_two_columns_for_its_mark() {
let state = |id, has_popup| Op::SetProp {
id,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
expanded: Some(false),
has_popup,
..Default::default()
})),
};
let mut ops = view(2, ROOT_ID, &[]);
// A collapsible's trigger: `▸ ` before its title.
ops.extend(pressable(3, 2, &[("flexDirection", V::Str("row"))], None));
ops.push(state(3, false));
ops.extend(text(4, 3, "Storage"));
// One that draws its own mark keeps none for the painter's.
ops.extend(pressable(6, 2, &[("flexDirection", V::Str("row"))], None));
ops.push(state(6, false));
ops.extend(text(7, 6, "▸ Privacy"));
// A popup's trigger is no disclosure.
ops.extend(pressable(9, 2, &[("flexDirection", V::Str("row"))], None));
ops.push(state(9, true));
ops.extend(text(10, 9, "Sort by"));
// One whose leading spacer already keeps the two columns.
ops.extend(pressable(12, 2, &[("flexDirection", V::Str("row"))], None));
ops.push(state(12, false));
ops.extend(view(14, 12, &[("width", V::Number(16.0))]));
ops.extend(text(15, 12, "Options"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.x), Some(Points(16.0)));
assert_eq!(frame_of(&batch, 7).map(|f| f.origin.x), Some(Points(0.0)));
assert_eq!(frame_of(&batch, 10).map(|f| f.origin.x), Some(Points(0.0)));
assert_eq!(frame_of(&batch, 15).map(|f| f.origin.x), Some(Points(16.0)));
}
/// An icon-only popup trigger padded each side (`Merge options`), with
/// `beside` after it in its row, `gap` apart.
fn icon_popup_trigger(beside: Option<&str>, gap: f32) -> MountBatch {
let mut ops = view(
2,
ROOT_ID,
&[("flexDirection", V::Str("row")), ("gap", V::Number(gap))],
);
ops.extend(pressable(
3,
2,
&[("paddingHorizontal", V::Number(8.0))],
Some("Merge options"),
));
ops.push(Op::SetProp {
id: 3,
prop: Prop::Accessibility(AccessibilityProp::State(crate::AccessibilityState {
expanded: Some(false),
has_popup: true,
..Default::default()
})),
});
ops.extend(node(
4,
Tag::Canvas,
3,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
if let Some(beside) = beside {
ops.extend(text(5, 2, beside));
}
laid_out(ops)
}
#[test]
fn a_popup_trigger_flush_against_words_is_one_column_of_its_arrow() {
// A split button's other half: the words beside it say what it
// opens, so it shows `▾` in place of its label, with its padding's
// column each side.
let batch = icon_popup_trigger(Some("Merge"), 0.0);
assert_eq!(
frame_of(&batch, 3).map(|f| f.size.width),
Some(Points(24.0))
);
let style = view_style_of(&batch, 3).unwrap();
assert!(style.shows_label && style.label_arrow_only);
}
#[test]
fn a_popup_trigger_with_no_words_beside_it_shows_its_name_and_arrow() {
// Alone, or apart from the words in its row (a toolbar's), only
// its name says what it opens: `Merge options ▾`, 15 columns, and
// its padding's column each side.
for batch in [
icon_popup_trigger(None, 0.0),
icon_popup_trigger(Some("Merge"), 8.0),
] {
assert_eq!(
frame_of(&batch, 3).map(|f| f.size.width),
Some(Points(17.0 * 8.0))
);
let style = view_style_of(&batch, 3).unwrap();
assert!(style.shows_label && !style.label_arrow_only);
}
}
#[test]
fn a_band_inside_a_card_draws_no_second_line() {
let mut ops = view(
2,
ROOT_ID,
&[
("backgroundColor", V::Str("#262626")),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#777777")),
("padding", V::Number(5.0)),
],
);
ops.extend(view(
3,
2,
&[
("backgroundColor", V::Str("#333333")),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#999999")),
],
));
ops.extend(view(5, 3, &[]));
ops.extend(text(6, 5, "Files"));
ops.extend(text(8, 3, "Preview"));
let batch = laid_out_on_surfaces(ops);
// A face is a line or a fill, never both: the filled card is its
// band, and the well in it is its own band, with no line between.
assert_eq!(widths(&batch, 2), Some(Edges::all(Points::ZERO)));
assert_eq!(widths(&batch, 3), Some(Edges::all(Points::ZERO)));
}
#[test]
fn icon_buttons_shown_as_labels_keep_two_columns_apart() {
let mut ops = view(
2,
ROOT_ID,
&[("flexDirection", V::Str("row")), ("gap", V::Number(8.0))],
);
for (id, label) in [(3, "Search"), (6, "Hide the sidebar")] {
ops.extend(pressable(id, 2, &[], Some(label)));
ops.extend(node(
id + 1,
Tag::Canvas,
id,
&[("width", V::Number(16.0)), ("height", V::Number(16.0))],
));
}
let batch = laid_out(ops);
// Labels read as words: a column between them would make one
// phrase of the two.
let (a, b) = (frame_of(&batch, 3).unwrap(), frame_of(&batch, 6).unwrap());
assert_eq!(b.origin.x - (a.origin.x + a.size.width), Points(16.0));
}
#[test]
fn a_bare_overlay_keeps_its_border_as_its_outline() {
let ops = node(
2,
Tag::Overlay,
ROOT_ID,
&[
("left", V::Number(80.0)),
("top", V::Number(32.0)),
("width", V::Number(160.0)),
("height", V::Number(96.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#3b82f6")),
("borderRadius", V::Number(4.0)),
],
);
let batch = laid_out(ops);
// A drop preview: its size the app's, its border sent for the
// painter to draw over its outer Cells.
assert_eq!(frame_of(&batch, 2), Some(rect(80.0, 32.0, 160.0, 96.0)));
assert_eq!(widths(&batch, 2), Some(Edges::all(Points(1.0))));
assert!(!left_out(&batch, 2));
}
#[test]
fn a_popups_panel_is_its_band_or_its_line_close_around_its_content() {
// A hover card's panel in its overlay: filled, framed, padded 16pt,
// a name over a box of figures.
let popup = || {
let mut ops = node(
2,
Tag::Overlay,
ROOT_ID,
&[("left", V::Number(80.0)), ("top", V::Number(32.0))],
);
ops.extend(view(
3,
2,
&[
("width", V::Number(240.0)),
("padding", V::Number(16.0)),
("borderWidth", V::Number(1.0)),
("borderRadius", V::Number(12.0)),
("borderColor", V::Str("#b0b0b0")),
("backgroundColor", V::Str("#262626")),
],
));
ops.extend(text(4, 3, "Mira Chen"));
ops.extend(view(6, 3, &[]));
ops.extend(text(7, 6, "Design lead"));
ops
};
// Its band alone, a column each side, no rows: its first text on
// its first row; laid out the same where fills are not bands, as
// the color depth never moves anything.
for batch in [laid_out_on_surfaces(popup()), laid_out(popup())] {
assert!(widths(&batch, 3).is_none_or(|w| w == Edges::all(Points::ZERO)));
assert_eq!(
frame_of(&batch, 4).map(|f| f.origin),
Some(point(Points(8.0), Points::ZERO))
);
let panel = frame_of(&batch, 3).unwrap();
assert_eq!(panel.size.height, Points(32.0));
}
}
#[test]
fn a_menu_whose_panel_the_app_filled_is_framed_a_cell_out_and_padded_a_column() {
// A trigger, and a menu under it: its list holds the app's filled
// and bordered panel, and an item in that.
let menu = || {
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(80.0)),
("height", V::Number(16.0)),
("alignSelf", V::Str("flex-start")),
],
);
ops.extend(node(4, Tag::Overlay, ROOT_ID, &[]));
ops.extend(view(6, 4, &[]));
ops.push(Op::SetProp {
id: 6,
prop: Prop::Accessibility(AccessibilityProp::Role(crate::AccessibilityRole::Menu)),
});
ops.extend(view(
8,
6,
&[
("width", V::Number(160.0)),
("padding", V::Number(4.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#36383c")),
("backgroundColor", V::Str("#25262a")),
],
));
ops.extend(text(10, 8, "New document"));
ops.extend([
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
overlay_prop(
4,
crate::OverlayProp::Placement(crate::overlay::Placement::Bottom),
),
overlay_prop(4, crate::OverlayProp::Align(crate::overlay::Align::Start)),
]);
ops
};
// Its panel's fill is the popup itself, its line a Cell outside it
// at every depth of color: a Cell clear of the trigger's row, its
// panel's own border no Cells, its item a column in on its first
// row.
for batch in [laid_out_on_surfaces(menu()), laid_out(menu())] {
assert_eq!(frame_of(&batch, 4).map(|f| f.origin.y), Some(Points(32.0)));
}
let batch = laid_out_on_surfaces(menu());
assert!(widths(&batch, 8).is_none_or(|w| w == Edges::all(Points::ZERO)));
assert_eq!(
frame_of(&batch, 10).map(|f| f.origin),
Some(point(Points(8.0), Points::ZERO))
);
}
#[test]
fn a_popups_line_starts_on_the_row_under_its_trigger_whatever_its_offset() {
// A menu 4pt below its trigger (the app's gap in a GUI): rounded
// up to a Cell it would leave a blank row between the trigger and
// the line, over the page's text there.
let menu = |offset: f32| {
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(80.0)),
("height", V::Number(16.0)),
("alignSelf", V::Str("flex-start")),
],
);
ops.extend(node(4, Tag::Overlay, ROOT_ID, &[]));
ops.extend(view(
8,
4,
&[
("width", V::Number(160.0)),
("padding", V::Number(4.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#36383c")),
],
));
ops.extend(text(10, 8, "New document"));
ops.extend([
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
overlay_prop(
4,
crate::OverlayProp::Placement(crate::overlay::Placement::Bottom),
),
overlay_prop(4, crate::OverlayProp::Offset(Points(offset))),
]);
ops
};
// The trigger is row 0, the line row 1, the item row 2, whether
// the line is the panel's own border or a ring outside its box.
for offset in [0.0, 4.0, 12.0] {
for batch in [laid_out_on_surfaces(menu(offset)), laid_out(menu(offset))] {
let y = |id| frame_of(&batch, id).map_or(Points::ZERO, |f| f.origin.y);
assert_eq!(y(4) + y(8) + y(10), Points(32.0), "offset {offset}");
}
}
}
#[test]
fn a_menus_rows_reach_its_line_and_keep_their_text_a_column_in() {
// A menu's panel (padded 4pt, bordered, filled by the app or not)
// holds a group's title, an item the pointer is on (filled) and
// one it is not.
let menu = |filled: bool| {
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(80.0)),
("height", V::Number(16.0)),
("alignSelf", V::Str("flex-start")),
],
);
ops.extend(node(4, Tag::Overlay, ROOT_ID, &[]));
ops.extend(view(6, 4, &[]));
ops.push(Op::SetProp {
id: 6,
prop: Prop::Accessibility(AccessibilityProp::Role(crate::AccessibilityRole::Menu)),
});
ops.extend(view(
8,
6,
&[
("width", V::Number(160.0)),
("padding", V::Number(4.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#36383c")),
(
"backgroundColor",
V::Str(if filled { "#25262a" } else { "transparent" }),
),
],
));
ops.extend(text(10, 8, "Sort by"));
ops.extend(view(12, 8, &[("backgroundColor", V::Str("#36383c"))]));
ops.extend(text(14, 12, "Name"));
ops.extend(view(16, 8, &[]));
ops.extend(text(18, 16, "Date"));
ops.extend([
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
overlay_prop(
4,
crate::OverlayProp::Placement(crate::overlay::Placement::Bottom),
),
overlay_prop(4, crate::OverlayProp::Align(crate::overlay::Align::Start)),
]);
ops
};
// Each row's band runs from the first column inside the line to
// the last (filled or not: its fill follows the pointer), and its
// text, as the title's, starts a column in. A filled panel is the
// popup (its line a Cell outside it); an unfilled one keeps its own
// line, a Cell inside its box.
for filled in [true, false] {
let batch = laid_out_on_surfaces(menu(filled));
let line = if filled { 0.0 } else { 8.0 };
for row in [12, 16] {
let f = frame_of(&batch, row).unwrap();
assert_eq!(
(f.origin.x, f.size.width),
(Points(line), Points(160.0 - 2.0 * line)),
"row {row}, filled {filled}"
);
}
assert_eq!(
frame_of(&batch, 10).map(|f| f.origin.x),
Some(Points(line + 8.0))
);
for label in [14, 18] {
assert_eq!(
frame_of(&batch, label).map(|f| f.origin.x),
Some(Points(8.0)),
"label {label}, filled {filled}"
);
}
}
}
#[test]
fn a_lists_rows_in_a_popup_styled_on_its_overlay_reach_its_line() {
// A select's list: its popup's own box filled, framed and padded
// 6pt (the app's popup style on the overlay), a scroll view in it
// holding the list of options.
let mut c = core();
c.set_environment(crate::element::Environment {
cell: Some(size_pt(8.0, 16.0)),
dark: true,
..Default::default()
});
let mut ops = node(
2,
Tag::Overlay,
ROOT_ID,
&[
("left", V::Number(80.0)),
("top", V::Number(32.0)),
("width", V::Number(160.0)),
("padding", V::Number(6.0)),
("borderWidth", V::Number(1.0)),
("borderColor", V::Str("#36383c")),
("backgroundColor", V::Str("#25262a")),
],
);
ops.extend(node(4, Tag::Scroll, 2, &[("height", V::Number(32.0))]));
ops.extend([
Op::Create {
id: 6,
tag: Tag::List,
},
Op::SetProp {
id: 6,
prop: Prop::ListViewport(crate::ListViewport::Parent),
},
Op::SetProp {
id: 6,
prop: Prop::EstimatedItemSize(px(16.0)),
},
Op::SetProp {
id: 6,
prop: Prop::Count(2),
},
Op::Insert {
parent: 4,
child: 6,
before: None,
},
]);
apply(&mut c, ops);
let first = c.commit().unwrap();
let (mut next, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next, &mut cells, 16.0);
assert!(!cells.is_empty());
// Each cell holds the option's row, its text in it.
let row = |i: usize| 300 + 4 * i as NodeId;
for (i, &cell) in cells.iter().enumerate() {
let mut ops = view(row(i), cell, &[]);
ops.extend(text(row(i) + 2, row(i), "Name"));
apply(&mut c, ops);
}
let batch = c.commit().unwrap();
// The scroll view lies against the line across the panel's
// padding, so each row's band runs line to line (its fill follows
// the highlight); its text keeps the padding, a column in.
assert_eq!(
frame_of(&first, 4).map(|f| (f.origin.x, f.size.width)),
Some((Points::ZERO, Points(160.0)))
);
for (i, &cell) in cells.iter().enumerate() {
let span = |id| frame_of(&batch, id).map(|f| (f.origin.x, f.size.width));
assert_eq!(
span(cell),
Some((Points::ZERO, Points(160.0))),
"cell {cell}"
);
assert_eq!(
span(row(i)),
Some((Points::ZERO, Points(160.0))),
"cell {cell}"
);
assert_eq!(
frame_of(&batch, row(i) + 2).map(|f| f.origin.x),
Some(Points(8.0)),
"cell {cell}"
);
}
}
#[test]
fn a_frame_around_one_frame_draws_one_line() {
let framed = |pad: f32| {
let mut ops = view(
2,
ROOT_ID,
&[("borderWidth", V::Number(1.0)), ("padding", V::Number(pad))],
);
ops.extend(view(3, 2, &[]));
ops.extend(view(
4,
3,
&[
("borderWidth", V::Number(1.0)),
("padding", V::Number(16.0)),
],
));
ops.extend(text(5, 4, "Dock"));
ops.extend(view(8, 4, &[]));
ops.extend(text(9, 8, "Panel"));
laid_out(ops)
};
let batch = framed(0.0);
assert_eq!(widths(&batch, 2), Some(Edges::all(Points::ZERO)));
assert_eq!(widths(&batch, 4), Some(Edges::all(Points(1.0))));
assert_eq!(
frame_of(&batch, 4).map(|f| f.origin),
Some(point(Points::ZERO, Points::ZERO))
);
// Padding of its own: two frames, the app's.
let batch = framed(16.0);
assert_eq!(widths(&batch, 2), Some(Edges::all(Points(1.0))));
assert_eq!(widths(&batch, 4), Some(Edges::all(Points(1.0))));
}
#[test]
fn a_dividers_gap_keeps_its_row_in_a_card() {
let mut ops = view(
2,
ROOT_ID,
&[
("borderWidth", V::Number(1.0)),
("padding", V::Number(16.0)),
("gap", V::Number(24.0)),
],
);
ops.extend(view(3, 2, &[]));
ops.extend(text(4, 3, "Editor"));
ops.extend(view(6, 2, &[]));
ops.extend(text(7, 6, "Console"));
ops.extend(view(
9,
2,
&[
("position", V::Str("absolute")),
("left", V::Number(0.0)),
("right", V::Number(0.0)),
("top", V::Number(32.0)),
("cursor", V::Str("row-resize")),
],
));
ops.extend(text(10, 9, "─"));
let batch = laid_out(ops);
let editor = frame_of(&batch, 3).unwrap();
let console = frame_of(&batch, 6).unwrap();
assert_eq!(
console.origin.y - (editor.origin.y + editor.size.height),
Points(16.0)
);
}
#[test]
fn a_resize_handle_is_one_column_between_its_panels() {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(3, 2, &[("flex", V::Number(1.0))]));
ops.extend(text(4, 3, "Left"));
ops.extend(view(
6,
2,
&[("width", V::Number(4.0)), ("cursor", V::Str("col-resize"))],
));
// Its grip: a small bare view, a decoration elsewhere.
ops.extend(view(
7,
6,
&[("width", V::Number(2.0)), ("height", V::Number(12.0))],
));
ops.extend(view(8, 2, &[("flex", V::Number(1.0))]));
ops.extend(text(9, 8, "Right"));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 6), Some(rect(160.0, 0.0, 8.0, 16.0)));
assert_eq!(frame_of(&batch, 8).map(|f| f.origin.x), Some(Points(168.0)));
}
#[test]
fn a_labelled_resize_handle_is_a_divider_not_its_label() {
// A panel's resize handle pinned on its edge: an adjustable control
// with an accessibility label, holding only its grip (a small bar in
// an absolute strip). Its content is all left out, as an icon
// button's is, but it is a divider: one column, and the painter
// draws no label over it (one column would cut it to `…`).
let mut ops = view(
2,
ROOT_ID,
&[
("width", V::Number(160.0)),
("flexDirection", V::Str("row")),
],
);
ops.extend(text(3, 2, "Sidebar"));
ops.extend(view(
5,
2,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("bottom", V::Number(0.0)),
("right", V::Number(-2.5)),
("width", V::Number(6.0)),
("cursor", V::Str("col-resize")),
],
));
ops.push(Op::SetProp {
id: 5,
prop: Prop::Accessibility(AccessibilityProp::Role(
crate::AccessibilityRole::Adjustable,
)),
});
ops.push(Op::SetProp {
id: 5,
prop: Prop::Accessibility(AccessibilityProp::Label(Some("Resize the sidebar".into()))),
});
ops.extend(view(
6,
5,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("bottom", V::Number(0.0)),
("left", V::Number(1.5)),
("width", V::Number(3.0)),
("justifyContent", V::Str("center")),
],
));
ops.extend(view(
7,
6,
&[("width", V::Number(3.0)), ("height", V::Number(0.0))],
));
let batch = laid_out(ops);
assert_eq!(frame_of(&batch, 5).map(|f| f.size.width), Some(Points(8.0)));
assert!(
view_style_of(&batch, 5).is_none_or(|s| !s.shows_label),
"{:?}",
view_style_of(&batch, 5)
);
}
#[test]
fn a_flex_basis_is_a_panels_length_both_ways() {
let mut ops = view(2, ROOT_ID, &[("flexDirection", V::Str("row"))]);
ops.extend(view(
3,
2,
&[
("flexBasis", V::Number(220.0)),
("flexGrow", V::Number(0.0)),
],
));
ops.extend(text(4, 3, "Sidebar"));
ops.extend(view(
6,
2,
&[("flexBasis", V::Number(0.0)), ("flexGrow", V::Number(1.0))],
));
ops.extend(view(7, 6, &[]));
ops.extend(view(
8,
7,
&[("flexBasis", V::Number(0.0)), ("flexGrow", V::Number(1.0))],
));
ops.extend(text(9, 8, "Editor"));
ops.extend(view(
11,
7,
&[
("flexBasis", V::Number(140.0)),
("flexGrow", V::Number(0.0)),
("minHeight", V::Number(64.0)),
],
));
ops.extend(text(12, 11, "Console"));
let batch = laid_out(ops);
// 220pt is 27 columns (27.5, a half down), the rest the editor's;
// 140pt is 9 rows, whatever the console holds.
assert_eq!(frame_of(&batch, 3), Some(rect(0.0, 0.0, 216.0, 160.0)));
assert_eq!(
frame_of(&batch, 6).map(|f| (f.origin.x, f.size.width)),
Some((Points(216.0), Points(104.0)))
);
assert_eq!(
frame_of(&batch, 11).map(|f| f.size.height),
Some(Points(144.0))
);
}
#[test]
fn an_absolute_box_stretches_between_two_insets() {
let mut ops = view(2, ROOT_ID, &[]);
for i in 0..3u32 {
ops.extend(text(10 + 2 * i, 2, "Line"));
}
ops.extend(view(
20,
2,
&[
("position", V::Str("absolute")),
("top", V::Number(0.0)),
("bottom", V::Number(0.0)),
("left", V::Number(80.0)),
("width", V::Number(8.0)),
],
));
ops.push(Op::SetProp {
id: 20,
prop: Prop::Accessibility(AccessibilityProp::Role(
crate::AccessibilityRole::Adjustable,
)),
});
ops.extend(text(21, 20, "│"));
let batch = laid_out(ops);
// Down the whole column: a divider's band.
assert_eq!(frame_of(&batch, 20), Some(rect(80.0, 0.0, 8.0, 48.0)));
}
#[test]
fn every_frame_is_whole_cells() {
let mut ops = view(
2,
ROOT_ID,
&[
("flexDirection", V::Str("row")),
("marginLeft", V::Number(5.0)),
("paddingVertical", V::Number(17.0)),
("columnGap", V::Number(3.0)),
],
);
ops.extend(view(
3,
2,
&[("width", V::Number(37.0)), ("height", V::Number(23.0))],
));
ops.extend(text(4, 2, "abc"));
ops.extend(view(6, 2, &[("flex", V::Number(1.0))]));
let batch = laid_out(ops);
let frames: Vec<_> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Frame { id, frame } => Some((*id, *frame)),
_ => None,
})
.collect();
assert!(frames.len() >= 3);
for (id, f) in frames {
let whole = |v: Points, cell: f32| (v.0 / cell).fract() == 0.0;
assert!(
whole(f.origin.x, 8.0)
&& whole(f.size.width, 8.0)
&& whole(f.origin.y, 16.0)
&& whole(f.size.height, 16.0),
"{id}: {f:?}"
);
}
}
#[test]
fn leaving_the_terminal_lays_out_in_points_again() {
let mut c = core();
terminal(&mut c, true);
apply(&mut c, button());
c.commit().unwrap();
terminal(&mut c, false);
let batch = c.commit().unwrap();
// The style as given: 1 + 12 + 16 + 12 + 1 wide, 40 high.
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 42.0, 40.0)));
terminal(&mut c, true);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2), Some(rect(0.0, 0.0, 32.0, 16.0)));
}
}
#[test]
fn a_page_shader_and_a_shader_share_one_compiled_source() {
use crate::shader::{NavShaderSpec, Shader, TransitionShader};
let mut c = core();
let source = "struct Uniforms { amount: f32 }\nfn shade(uv: vec2f) -> vec4f { return mix(sample_from(uv), sample_to(uv), nsh.progress * uniforms.amount); }";
let rust = TransitionShader::new(Shader::compile(source).expect("compiles"))
.uniform("amount", 0.5)
.duration(std::time::Duration::from_millis(500));
let spec = || NavShaderSpec {
source: source.into(),
uniforms: Default::default(),
duration: None,
};
apply(
&mut c,
vec![
// Not a page or a dialog: nothing compiles.
Op::Create {
id: 4,
tag: Tag::View,
},
Op::SetProp {
id: 4,
prop: Prop::TransitionShader(Some(spec())),
},
],
);
c.commit();
assert!(c.shaders.is_empty());
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Modal,
},
Op::SetProp {
id: 2,
prop: Prop::TransitionShader(Some(rust.into())),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Create {
id: 6,
tag: Tag::Screen,
},
Op::SetProp {
id: 6,
prop: Prop::TransitionShader(Some(spec())),
},
Op::Create {
id: 8,
tag: Tag::Shader,
},
Op::SetProp {
id: 8,
prop: Prop::ShaderSource(Some(source.into())),
},
],
);
let batch = c.commit().unwrap();
let shader = batch
.items
.iter()
.find_map(|i| match i {
MountItem::NavShader {
id: 2,
shader: Some(s),
} => Some(s.clone()),
_ => None,
})
.expect("the dialog's shader");
assert_eq!(shader.duration, std::time::Duration::from_millis(500));
assert_eq!(shader.layer.uniforms[0], 0.5f32.to_bits());
assert_eq!(
c.shaders.len(),
1,
"one compile for the dialog, the page and the view"
);
}
#[test]
fn a_bad_page_shader_keeps_its_error() {
let mut c = core();
let spec = || crate::shader::NavShaderSpec {
source: "fn shade() {}".into(),
uniforms: Default::default(),
duration: None,
};
for id in [2, 4] {
apply(
&mut c,
vec![
Op::Create {
id,
tag: Tag::Screen,
},
Op::SetProp {
id,
prop: Prop::TransitionShader(Some(spec())),
},
],
);
}
c.commit();
assert!(
matches!(c.shaders.values().next(), Some(Err(_))),
"its error kept"
);
assert_eq!(c.shaders.len(), 1);
}
mod audio {
use std::{
sync::{Arc, Mutex},
time::Duration,
};
use super::*;
use crate::{
audio::{AudioBackend, AudioCommand, AudioEvent, AudioSink, MAX_DECODED_BYTES},
prelude::*,
};
/// What the fake decodes a sound as.
struct Decodes {
duration: Duration,
bytes: u64,
truncated: bool,
}
/// Plays in place of the platform: records what it is asked.
struct FakeAudio {
log: Mutex<Vec<String>>,
/// The names the loads went by.
hints: Mutex<Vec<String>>,
decodes: Mutex<Decodes>,
}
impl FakeAudio {
fn new() -> Arc<Self> {
Arc::new(Self {
log: Mutex::default(),
hints: Mutex::default(),
decodes: Mutex::new(Decodes {
duration: Duration::from_millis(400),
bytes: 70_000,
truncated: false,
}),
})
}
fn log(&self) -> Vec<String> {
self.log.lock().unwrap().clone()
}
}
impl AudioBackend for FakeAudio {
fn command(&self, command: AudioCommand, events: &AudioSink) {
let line = match &command {
AudioCommand::Load {
max_duration, hint, ..
} => {
assert_eq!(*max_duration, crate::audio::MAX_SOUND_DURATION);
self.hints.lock().unwrap().push(hint.clone());
let d = self.decodes.lock().unwrap();
events.send(AudioEvent::Loaded {
duration: d.duration,
bytes: d.bytes,
truncated: d.truncated,
});
"load".to_owned()
}
AudioCommand::LoadUrl { url, .. } => format!("load {url}"),
AudioCommand::Play { volume, rate, .. } => format!("play {volume} {rate}"),
AudioCommand::Stop { .. } => "stop".into(),
AudioCommand::Unload { .. } => "unload".into(),
AudioCommand::Open { src, settings, .. } => {
format!("open {src} {}", settings.looped)
}
AudioCommand::Resume { .. } => {
events.send(AudioEvent::Load {
duration: Some(Duration::from_secs(10)),
});
events.send(AudioEvent::Playing);
"resume".into()
}
AudioCommand::Pause { .. } => {
events.send(AudioEvent::Paused);
"pause".into()
}
AudioCommand::Seek { position, .. } => {
events.send(AudioEvent::Progress {
position: *position,
duration: None,
});
format!("seek {}", position.as_secs_f32())
}
AudioCommand::Set { settings, .. } => format!("set {}", settings.volume),
AudioCommand::Preload { .. } => "preload".into(),
AudioCommand::Close { .. } => "close".into(),
};
self.log.lock().unwrap().push(line);
}
}
fn click_uri() -> String {
crate::platform::clipboard::data_uri("audio/wav", b"RIFF a click")
}
fn failed(result: Result<Sound, AudioFailure>) -> String {
match result {
Ok(sound) => format!("loaded {}", sound.duration().as_millis()),
Err(failure) => failure.error.as_str().to_owned(),
}
}
/// Loads [`click_uri`] twice and plays both, then lets them go.
#[component]
fn Clicks() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
let a = load_sound(&click_uri()).await.unwrap();
a.play(0.5, 1.0);
let b = load_sound(&click_uri()).await.unwrap();
b.play(1.0, 2.0);
// Clamped, never refused: a Rust caller's values.
b.play(3.0, 0.1);
drop(a);
b.stop();
drop(b);
shown.set(format!("done {}", 1));
});
text(move || shown.get())
}
/// Loads [`click_uri`] once and shows how it went.
#[component]
fn Click() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
shown.set(failed(load_sound(&click_uri()).await));
});
text(move || shown.get())
}
/// Loads a sound from bytes the app holds: the same bytes twice (one
/// static, one a copy) and other bytes once, and plays each.
#[component]
fn ByteSounds() -> impl IntoElement {
const TICK: &[u8; 16] = b"RIFF\0\0\0\0WAVEtick";
let shown = signal(String::new());
spawn(async move {
let a = load_sound(TICK).await.unwrap();
let b = load_sound(TICK.to_vec()).await.unwrap();
let c = load_sound(b"ID3 another".as_slice()).await.unwrap();
a.play(0.5, 1.0);
b.play(0.5, 1.0);
c.play(1.0, 1.0);
shown.set("done".into());
});
text(move || shown.get())
}
/// Loads a sound from bytes once and shows why it was refused, naming
/// the capability.
#[component]
fn ByteClick() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
shown.set(match load_sound(b"RIFF a click".as_slice()).await {
Ok(_) => "loaded".into(),
Err(failure) => format!("{} {:?}", failure.error.as_str(), failure.permission),
});
});
text(move || shown.get())
}
/// Plays a remote player, seeks it, and closes it.
#[component]
fn Voice() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
let mut player = audio_player(
"https://example.com/voice.m4a",
crate::audio::PlayerSettings::default(),
);
player.play();
let mut seen = Vec::new();
while let Some(event) = player.next().await {
let playing = event == AudioEvent::Playing;
seen.push(format!("{event:?}"));
if playing {
break;
}
}
player.seek(Duration::from_secs(3));
seen.push(format!("{:?}", player.next().await));
drop(player);
shown.set(seen.join("|"));
});
text(move || shown.get())
}
/// Opens a player of a source written with a dot segment and an
/// upper-case host, and plays it.
#[component]
fn LooseVoice() -> impl IntoElement {
let shown = signal(String::new());
spawn(async move {
let mut player = audio_player(
"https://EXAMPLE.com/a/../voice.m4a",
crate::audio::PlayerSettings::default(),
);
player.play();
let event = player.next().await;
shown.set(format!("{event:?}"));
});
text(move || shown.get())
}
fn shown_after<C: crate::element::Component>(c: &mut Core<FakeEngine>) -> String
where
C::Props: Default,
{
c.mount_root(&crate::element::Root::new::<C>(C::Props::default));
let end = std::time::Instant::now() + Duration::from_secs(5);
while std::time::Instant::now() < end {
c.run_component_tasks();
if let Some(batch) = c.commit() {
let texts: Vec<String> = batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Text { text, .. } if !text.text.is_empty() => {
Some(text.text.clone())
}
_ => None,
})
.collect();
if let Some(last) = texts.last() {
return last.clone();
}
}
std::thread::sleep(Duration::from_millis(2));
}
panic!("nothing shown");
}
/// Commits until no command is left, for the ones sent last.
fn settle(c: &mut Core<FakeEngine>) {
for _ in 0..5 {
c.run_component_tasks();
let _ = c.commit();
}
}
#[test]
fn a_source_loads_once_and_plays_overlapping() {
let audio = FakeAudio::new();
let mut c = core();
c.set_audio(Some(audio.clone()));
assert_eq!(shown_after::<Clicks>(&mut c), "done 1");
settle(&mut c);
assert_eq!(
audio.log(),
[
"load",
"play 0.5 1",
"play 1 2",
"play 1 0.5",
"stop",
"unload"
]
);
}
#[test]
fn bytes_load_once_named_by_their_format() {
let audio = FakeAudio::new();
let mut c = core();
c.set_audio(Some(audio.clone()));
assert_eq!(shown_after::<ByteSounds>(&mut c), "done");
settle(&mut c);
assert_eq!(
audio.log(),
[
"load",
"load",
"play 0.5 1",
"play 0.5 1",
"play 1 1",
"unload",
"unload"
]
);
let hints = audio.hints.lock().unwrap().clone();
assert_eq!(hints.len(), 2);
assert!(hints[0].starts_with("data:audio/wav;nsh-key="), "{hints:?}");
assert!(
hints[1].starts_with("data:audio/mpeg;nsh-key="),
"{hints:?}"
);
}
#[test]
fn a_sound_longer_than_the_limit_is_refused() {
let audio = FakeAudio::new();
audio.decodes.lock().unwrap().truncated = true;
let mut c = core();
c.set_audio(Some(audio.clone()));
assert_eq!(shown_after::<Click>(&mut c), "quota-exceeded");
settle(&mut c);
assert_eq!(audio.log(), ["load", "unload"]);
}
#[test]
fn decoded_audio_has_a_budget() {
let audio = FakeAudio::new();
audio.decodes.lock().unwrap().bytes = MAX_DECODED_BYTES + 1;
let mut c = core();
c.set_audio(Some(audio.clone()));
assert_eq!(shown_after::<Click>(&mut c), "quota-exceeded");
settle(&mut c);
assert_eq!(audio.log(), ["load", "unload"]);
}
#[test]
fn sound_needs_the_capability() {
let audio = FakeAudio::new();
let mut c = core();
c.set_audio(Some(audio.clone()));
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({})).unwrap(),
granted: None,
}));
assert_eq!(shown_after::<Click>(&mut c), "not-allowed");
// Bytes the app holds need the capability as much as a source: the
// core refuses them (without the engine's loader context) ...
assert_eq!(shown_after::<ByteClick>(&mut c), "not-allowed None");
// ... and so does the load, before it reads them, naming it.
c.set_image_context(crate::image::loader::Context {
access: Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({})).unwrap(),
granted: None,
}),
..Default::default()
});
assert_eq!(
shown_after::<ByteClick>(&mut c),
"not-allowed Some(\"audio\")"
);
c.set_image_context(crate::image::loader::Context::default());
assert_eq!(audio.log(), Vec::<String>::new());
}
#[test]
fn nothing_plays_where_the_platform_has_no_sound() {
let mut c = core();
assert_eq!(shown_after::<Click>(&mut c), "unavailable");
}
#[test]
fn the_platform_decodes_and_reports_on_the_root() {
let mut c = core();
c.set_environment(crate::element::Environment {
audio: true,
..Default::default()
});
c.mount_root(&crate::element::Root::new::<Click>(|| ()));
let end = std::time::Instant::now() + Duration::from_secs(5);
let id = loop {
assert!(std::time::Instant::now() < end, "no load");
c.run_component_tasks();
let load = c.commit().and_then(|b| {
b.items.into_iter().find_map(|i| match i {
MountItem::Command {
id: ROOT_ID,
command:
Command::Audio(AudioCommand::Load {
id, bytes, hint, ..
}),
} => {
assert_eq!(&*bytes, b"RIFF a click");
assert!(hint.starts_with("data:audio/wav"));
Some(id)
}
_ => None,
})
});
if let Some(id) = load {
break id;
}
std::thread::sleep(Duration::from_millis(2));
};
// Another object's event is dropped.
assert!(c.component_event(
ROOT_ID,
EventKind::Audio,
&EventPayload::Audio {
id: id + 1000,
event: AudioEvent::Ended,
}
));
assert!(c.component_event(
ROOT_ID,
EventKind::Audio,
&EventPayload::Audio {
id,
event: AudioEvent::Loaded {
duration: Duration::from_millis(250),
bytes: 44_100,
truncated: false,
},
}
));
let mut shown = None;
for _ in 0..50 {
c.run_component_tasks();
if let Some(batch) = c.commit() {
shown = batch.items.iter().find_map(|i| match i {
MountItem::Text { text, .. } if !text.text.is_empty() => {
Some(text.text.clone())
}
_ => None,
});
if shown.is_some() {
break;
}
}
}
assert_eq!(shown.as_deref(), Some("loaded 250"));
}
#[test]
fn a_player_streams_and_closes() {
let audio = FakeAudio::new();
let mut c = core();
c.set_audio(Some(audio.clone()));
assert_eq!(
shown_after::<Voice>(&mut c),
"Load { duration: Some(10s) }|Playing|Some(Progress { position: 3s, duration: None })"
);
settle(&mut c);
assert_eq!(
audio.log(),
[
"open https://example.com/voice.m4a false",
"resume",
"seek 3",
"close"
]
);
}
#[test]
fn a_player_of_a_source_not_granted_fails_at_once() {
let audio = FakeAudio::new();
let mut c = core();
c.set_audio(Some(audio.clone()));
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(&serde_json::json!({ "audio": true }))
.unwrap(),
granted: None,
}));
assert_eq!(
shown_after::<Voice>(&mut c),
// Nothing after the failure: the core closed it.
"Failed { error: NotAllowed, message: \"the source is not granted by capabilities.network\" }|None"
);
assert_eq!(audio.log(), Vec::<String>::new());
}
/// A player opens the URL the check granted (`Access::media_url`), as
/// WHATWG's parser reads the source.
#[test]
fn a_player_opens_the_url_the_check_granted() {
let audio = FakeAudio::new();
let mut c = core();
c.set_audio(Some(audio.clone()));
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "audio": true, "network": { "hosts": ["example.com"] } }),
)
.unwrap(),
granted: None,
}));
shown_after::<LooseVoice>(&mut c);
settle(&mut c);
assert_eq!(
audio.log().first().map(String::as_str),
Some("open https://example.com/voice.m4a false")
);
}
}
/// Words of eight points a character that wrap at spaces, each line taking
/// all that fits.
#[derive(Default)]
struct WordsEngine {
greedy: bool,
measures: Cell<u32>,
}
impl TextEngine for WordsEngine {
type Prepared = String;
fn prepare(&self, text: &AttributedText) -> String {
text.text.clone()
}
fn measure(&self, text: &String, max_width: Option<Points>) -> Size<Points> {
self.measures.set(self.measures.get() + 1);
let max = max_width.map_or(f32::INFINITY, |m| m.0);
let (mut line, mut widest, mut lines) = (0.0f32, 0.0f32, 1.0);
for word in text.split(' ') {
let width = word.chars().count() as f32 * 8.0;
let wider = if line > 0.0 {
line + 8.0 + width
} else {
width
};
if line > 0.0 && wider > max {
widest = widest.max(line);
line = width;
lines += 1.0;
} else {
line = wider;
}
}
size_pt(widest.max(line), lines * 16.0)
}
fn breaks_lines_greedily(&self) -> bool {
self.greedy
}
fn layout(&self, _: &String, _: Size<Points>) -> TextLayout {
TextLayout(Arc::new(()))
}
}
fn words_context(text: &str, max_lines: u32) -> TextContext<String> {
TextContext::new(Arc::new(AttributedText {
text: text.into(),
max_lines,
..AttributedText::default()
}))
}
/// Narrowed or widened by any steps, a text measures what it measures on
/// its own at each width, with or without typesetting.
#[test]
fn widths_with_the_same_line_breaks_measure_the_same() {
let text =
"the quick brown fox jumps over the lazy dog and keeps running through the long grass";
let engine = WordsEngine {
greedy: true,
..WordsEngine::default()
};
let mut cache = MeasureCache::default();
let mut cx = words_context(text, 0);
let widths = (40..400)
.rev()
.step_by(3)
.chain((40..400).step_by(7))
.chain((40..400).rev().step_by(11));
for width in widths {
let width = width as f32;
let fresh = WordsEngine::default().measure(&text.to_owned(), Some(Points(width)));
let size = measure_text(&engine, &mut cache, &mut cx, Some(width));
assert_eq!(size, fresh, "at {width}");
}
}
/// A narrower width that still holds the widest line needs no typesetting,
/// and neither does a wider one measured ahead of a growing width.
#[test]
fn a_text_is_typeset_only_when_its_line_breaks_may_change() {
let engine = WordsEngine {
greedy: true,
..WordsEngine::default()
};
let mut cache = MeasureCache::default();
// Two lines at 100: "aaaaaaaaaa" (80) and "bbbbbbbbbb" (80).
let mut cx = words_context("aaaaaaaaaa bbbbbbbbbb", 0);
measure_text(&engine, &mut cache, &mut cx, Some(100.0));
assert_eq!(engine.measures.get(), 1);
measure_text(&engine, &mut cache, &mut cx, Some(90.0));
measure_text(&engine, &mut cache, &mut cx, Some(80.0));
assert_eq!(engine.measures.get(), 1, "the widest line still fits");
measure_text(&engine, &mut cache, &mut cx, Some(79.0));
assert_eq!(engine.measures.get(), 2, "the widest line does not fit");
// Growing: one measurement covers the next widths.
let mut cache = MeasureCache::default();
let mut cx = words_context("aaaaaaaaaa bbbbbbbbbb", 0);
measure_text(&engine, &mut cache, &mut cx, Some(100.0));
let before = engine.measures.get();
measure_text(&engine, &mut cache, &mut cx, Some(102.0));
assert_eq!(engine.measures.get(), before + 1);
measure_text(&engine, &mut cache, &mut cx, Some(104.0));
measure_text(&engine, &mut cache, &mut cx, Some(108.0));
assert_eq!(engine.measures.get(), before + 1, "measured ahead");
}
/// Another width of the same left-aligned lines keeps the layout; anything
/// that moves or breaks a line does not.
#[test]
fn only_the_same_lines_at_the_left_keep_their_layout() {
let engine = WordsEngine {
greedy: true,
..WordsEngine::default()
};
let check = |text: AttributedText, to: f32, height: f32| {
let mut cache = MeasureCache::default();
let mut cx = TextContext::<String>::new(Arc::new(text));
// Two lines of 80 at 100.
measure_text(&engine, &mut cache, &mut cx, Some(100.0));
let laid = LaidText {
content: rect(0.0, 0.0, 100.0, 32.0),
layout: TextLayout(Arc::new(())),
text: cx.text.clone(),
};
keeps_lines(&cx, &laid, size_pt(to, height))
};
let text = |align, writing_direction, text: &str| AttributedText {
text: text.into(),
align,
writing_direction,
..AttributedText::default()
};
let plain = "aaaaaaaaaa bbbbbbbbbb";
assert!(check(text(TextAlign::Auto, None, plain), 80.0, 32.0));
assert!(check(text(TextAlign::Left, None, plain), 90.0, 32.0));
assert!(
!check(text(TextAlign::Auto, None, plain), 79.0, 32.0),
"breaks"
);
assert!(
!check(text(TextAlign::Auto, None, plain), 90.0, 40.0),
"taller"
);
assert!(!check(text(TextAlign::Center, None, plain), 90.0, 32.0));
assert!(!check(text(TextAlign::Right, None, plain), 90.0, 32.0));
assert!(!check(text(TextAlign::Justify, None, plain), 90.0, 32.0));
assert!(!check(text(TextAlign::Auto, Some(true), plain), 90.0, 32.0));
let arabic = "aaaaaaaa\u{0627} bbbbbbbbb";
assert!(!check(text(TextAlign::Auto, None, arabic), 90.0, 32.0));
}
/// During a burst of resizes, text far below the screen keeps its height and
/// catches up when the burst ends; text near the screen follows every width.
#[test]
fn far_text_catches_up_when_a_resize_ends() {
let mut c = Core::new(
WordsEngine {
greedy: true,
..WordsEngine::default()
},
size_pt(200.0, 100.0),
);
// Different words: the same ones would be measured once for both.
let text = |id, content, words: &str| {
vec![
Op::Create { id, tag: Tag::Text },
Op::CreateText {
id: content,
text: words.into(),
},
Op::Insert {
parent: id,
child: content,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::Insert {
parent: 1,
child: 2,
before: None,
},
];
ops.extend(text(3, 4, "aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd"));
ops.extend([
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(5, &[("height", StyleValue::Number(2000.0))]),
Op::Insert {
parent: 2,
child: 5,
before: None,
},
]);
ops.extend(text(6, 7, "eeeeeeeeee ffffffffff gggggggggg hhhhhhhhhh"));
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 3).unwrap().size.height, Points(32.0));
assert_eq!(frame_of(&batch, 6).unwrap().size.height, Points(32.0));
c.set_resizing(true);
c.set_viewport(size_pt(90.0, 100.0));
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 3).unwrap().size.height,
Points(64.0),
"follows the width"
);
assert_eq!(
frame_of(&batch, 6).unwrap().size.height,
Points(32.0),
"waits"
);
c.set_resizing(false);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 6).unwrap().size.height,
Points(64.0),
"caught up"
);
}
/// Text above the viewport wrapping onto more lines moves what shows: the
/// scroll view keeps it in place through the drag and the commit after it.
#[test]
fn a_scroll_view_keeps_what_it_shows_through_a_resize() {
let mut c = Core::new(
WordsEngine {
greedy: true,
..WordsEngine::default()
},
size_pt(200.0, 100.0),
);
// Every text measured, near the viewport or not, as a resize finds
// them (culled content is estimated: `cull.rs`).
c.set_content_culling(false);
let text = |id, content, value: &str| {
vec![
Op::Create { id, tag: Tag::Text },
Op::CreateText {
id: content,
text: value.into(),
},
Op::Insert {
parent: id,
child: content,
before: None,
},
Op::Insert {
parent: 2,
child: id,
before: None,
},
]
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: 1,
child: 2,
before: None,
},
];
// Far above the viewport, near it and shown.
ops.extend(text(3, 4, "aaaaaaaaaa bbbbbbbbbb cccccccccc dddddddddd"));
ops.extend([
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(5, &[("height", StyleValue::Number(2000.0))]),
Op::Insert {
parent: 2,
child: 5,
before: None,
},
]);
ops.extend(text(6, 7, "eeeeeeeeee ffffffffff gggggggggg hhhhhhhhhh"));
ops.extend([
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(8, &[("height", StyleValue::Number(3000.0))]),
Op::Insert {
parent: 2,
child: 8,
before: None,
},
]);
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 8).unwrap().origin.y, Points(2064.0));
c.set_scroll_offset(2, point(Points::ZERO, Points(2100.0)), 0);
let scrolled = |batch: &MountBatch| -> f32 {
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::ScrollBy { id: 2, dy, .. } => Some(dy.0),
_ => None,
})
.sum()
};
// The text just above wraps now, the far one waits.
c.set_resizing(true);
c.set_viewport(size_pt(90.0, 100.0));
let batch = c.commit().unwrap();
let moved = frame_of(&batch, 8).unwrap().origin.y.0 - 2064.0;
assert_eq!(moved, 32.0);
assert_eq!(scrolled(&batch), moved, "follows what it shows");
// The far text catches up all at once.
c.set_resizing(false);
let batch = c.commit().unwrap();
assert_eq!(scrolled(&batch), 32.0, "no jump at the end");
// One resize, outside any burst: wider, the texts take fewer lines.
c.set_viewport(size_pt(200.0, 100.0));
let batch = c.commit().unwrap();
assert_eq!(scrolled(&batch), -64.0, "a single resize too");
// At the start of the content nothing scrolls.
c.set_scroll_offset(2, point(Points::ZERO, Points::ZERO), 3);
c.set_viewport(size_pt(90.0, 100.0));
let batch = c.commit().unwrap();
assert_eq!(scrolled(&batch), 0.0);
}
/// A text whose lines change just ahead of its width stops being measured
/// ahead: it would be typeset twice per width.
#[test]
fn a_failed_measurement_ahead_is_not_repeated() {
let engine = WordsEngine {
greedy: true,
..WordsEngine::default()
};
let mut cache = MeasureCache::default();
// A word joins the first line at 168: 8 past 160.
let mut cx = words_context("aaaaaaaaaa bbbbbbbbbb", 0);
measure_text(&engine, &mut cache, &mut cx, Some(100.0));
let before = engine.measures.get();
let size = measure_text(&engine, &mut cache, &mut cx, Some(165.0));
assert_eq!(size, size_pt(80.0, 32.0));
assert_eq!(
engine.measures.get(),
before + 2,
"ahead, then at the width"
);
let before = engine.measures.get();
let size = measure_text(&engine, &mut cache, &mut cx, Some(167.0));
assert_eq!(size, size_pt(80.0, 32.0));
assert_eq!(engine.measures.get(), before + 1, "at the width only");
}
/// Engines that do not say they break lines greedily, and limits on lines,
/// are measured at every width.
#[test]
fn only_greedy_lines_without_a_limit_share_measurements() {
let plain = WordsEngine::default();
let mut cache = MeasureCache::default();
let mut cx = words_context("aaaaaaaaaa bbbbbbbbbb", 0);
measure_text(&plain, &mut cache, &mut cx, Some(100.0));
measure_text(&plain, &mut cache, &mut cx, Some(90.0));
assert_eq!(plain.measures.get(), 2);
let greedy = WordsEngine {
greedy: true,
..WordsEngine::default()
};
let mut cache = MeasureCache::default();
let mut cx = words_context("aaaaaaaaaa bbbbbbbbbb", 1);
measure_text(&greedy, &mut cache, &mut cx, Some(100.0));
measure_text(&greedy, &mut cache, &mut cx, Some(90.0));
assert_eq!(greedy.measures.get(), 2);
}
#[test]
fn overlays_with_a_cover_follow_its_size_changing() {
use StyleValue::Number;
let mut c = Core::new(FakeEngine::default(), size_pt(1920.0, 1080.0));
c.set_tokens(crate::element::tokens::sample());
// A slot 1904 × 464 at (8, 608), under a pane 600 tall.
add(&mut c, 2, Tag::View, ROOT_ID, &[("height", Number(600.0))]);
add(
&mut c,
4,
Tag::View,
ROOT_ID,
&[("flexGrow", Number(1.0)), ("padding", Number(8.0))],
);
add(&mut c, 6, Tag::View, 4, &[("flexGrow", Number(1.0))]);
// A view over it whose size the app sets once the slot's is known.
add(&mut c, 8, Tag::Overlay, ROOT_ID, &[]);
add(
&mut c,
10,
Tag::View,
8,
&[("width", Number(0.0)), ("height", Number(0.0))],
);
apply(
&mut c,
vec![
overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(6)),
),
overlay_prop(8, crate::OverlayProp::Cover(Some(10))),
],
);
c.commit();
let resize = |c: &mut Core<FakeEngine>, w: f32, h: f32| {
apply(
c,
vec![style_op(10, &[("width", Number(w)), ("height", Number(h))])],
);
c.commit();
c.measure(10).map(|m| Bounds {
origin: m.page,
size: m.frame.size,
})
};
// As large as the slot: on it, not where its former 0 × 0 frame put it.
assert_eq!(
resize(&mut c, 1904.0, 464.0),
Some(rect(8.0, 608.0, 1904.0, 464.0))
);
// Taller: its middle on the slot's, kept inside the window and 8
// points off its bottom edge (the snap margin).
assert_eq!(
resize(&mut c, 1888.0, 720.0),
Some(rect(8.0, 352.0, 1888.0, 720.0))
);
// Back: on the slot again, not where its former height put it.
assert_eq!(
resize(&mut c, 1904.0, 464.0),
Some(rect(8.0, 608.0, 1904.0, 464.0))
);
}
/// A backdrop reader (2, holding 6) between a view under it (5) and one
/// over it (7, holding 8), all children of the root.
fn backdrop_between() -> Core<FakeEngine> {
let mut c = core();
let source = "fn shade(uv: vec2f) -> vec4f { return sample_backdrop(uv); }";
let size = |id| {
style_op(
id,
&[
("width", StyleValue::Number(100.0)),
("height", StyleValue::Number(50.0)),
],
)
};
let mut ops = Vec::new();
for (id, tag) in [
(5, Tag::View),
(2, Tag::ShaderEffect),
(6, Tag::View),
(7, Tag::View),
(8, Tag::View),
] {
ops.push(Op::Create { id, tag });
ops.push(size(id));
}
ops.push(Op::SetProp {
id: 2,
prop: Prop::ShaderSource(Some(source.into())),
});
for (parent, child) in [(ROOT_ID, 5), (2, 6), (ROOT_ID, 2), (7, 8), (ROOT_ID, 7)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
apply(&mut c, ops);
c.commit().unwrap();
c
}
fn pictures_backdrop_again(c: &mut Core<FakeEngine>, id: NodeId, color: &'static str) -> bool {
apply(
c,
vec![style_op(id, &[("backgroundColor", StyleValue::Str(color))])],
);
let batch = c.commit().unwrap();
batch
.items
.iter()
.any(|i| matches!(i, MountItem::ShaderInput { id: 2 }))
}
#[test]
fn a_backdrop_is_pictured_again_only_when_what_is_under_it_changes() {
let mut c = backdrop_between();
// Over it, or in what draws over it: not in its backdrop.
assert!(!pictures_backdrop_again(&mut c, 8, "red"));
assert!(!pictures_backdrop_again(&mut c, 7, "red"));
// Under it, and its ancestor's own box.
assert!(pictures_backdrop_again(&mut c, 5, "red"));
assert!(pictures_backdrop_again(&mut c, ROOT_ID, "red"));
}
#[test]
fn a_backdrop_follows_the_order_views_draw_in() {
let mut c = backdrop_between();
// Later in order but drawn under it by its `zIndex`.
apply(
&mut c,
vec![style_op(7, &[("zIndex", StyleValue::Number(-1.0))])],
);
c.commit().unwrap();
assert!(pictures_backdrop_again(&mut c, 8, "blue"));
// A view leaving what draws over it does not change what is under it.
apply(
&mut c,
vec![style_op(7, &[("zIndex", StyleValue::Number(0.0))])],
);
c.commit().unwrap();
apply(
&mut c,
vec![
Op::Remove {
parent: 7,
child: 8,
},
Op::Release { id: 8 },
],
);
let batch = c.commit().unwrap();
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::ShaderInput { id: 2 })),
"{:?}",
batch.items
);
}
mod each_order {
use super::*;
use crate::{
element::{Component, Props, Root, Scope},
prelude::*,
};
#[derive(Clone, PartialEq)]
struct Item {
key: u32,
label: &'static str,
visible: bool,
}
fn item(key: u32, label: &'static str, visible: bool) -> Item {
Item {
key,
label,
visible,
}
}
fn caption(item: &Item, index: usize) -> String {
format!("{}:{}@{index}", item.key, item.label)
}
thread_local! {
static ITEMS: Cell<Option<Signal<Vec<Item>>>> = const { Cell::new(None) };
static FOOTER: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
static MADE: Cell<usize> = const { Cell::new(0) };
}
#[derive(Default)]
struct Holder;
#[derive(Clone, PartialEq, Props)]
struct HolderProps {
children: Children,
}
impl Component for Holder {
type Props = HolderProps;
type Event = NoEvent;
fn view(props: HolderProps, _: Scope<NoEvent>) -> impl IntoElement {
view().child(props.children)
}
}
#[derive(Default)]
struct RowsFixture;
#[derive(Clone, PartialEq, Props)]
struct FixtureProps {
nested: bool,
regions: bool,
}
impl Component for RowsFixture {
type Props = FixtureProps;
type Event = NoEvent;
fn view(props: FixtureProps, _: Scope<NoEvent>) -> impl IntoElement {
MADE.with(|made| made.set(0));
let items = signal(vec![
item(1, "one", true),
item(2, "two", !props.regions),
item(3, "three", true),
]);
let footer = signal(false);
ITEMS.with(|saved| saved.set(Some(items)));
FOOTER.with(|saved| saved.set(Some(footer)));
let rows = each(
items,
|item: &Item| item.key,
move |item, index| {
MADE.with(|made| made.set(made.get() + 1));
if props.regions {
dynamic(move || {
let item = item.get();
item.visible.then(|| text(caption(&item, index.get())))
})
} else {
text(move || caption(&item.get(), index.get())).into_element()
}
},
);
let children = vec![
text("prefix").into_element(),
rows,
when(footer, || text("anchor")).into_element(),
text("suffix").into_element(),
];
if props.nested {
view()
.child(
Holder::element(HolderProps {
children: Children::default(),
})
.children(children),
)
.into_element()
} else {
view().children(children).into_element()
}
}
}
fn children(c: &Core<FakeEngine>, parent: NodeId) -> Vec<NodeId> {
let key = c.key(parent).unwrap();
c.nodes[key as usize]
.children
.iter()
.map(|&child| c.nodes[child as usize].id)
.collect()
}
fn order(c: &Core<FakeEngine>, parent: NodeId) -> Vec<String> {
children(c, parent)
.into_iter()
.filter_map(|id| {
let node = &c.nodes[c.key(id).unwrap() as usize];
node.children
.first()
.map(|&raw| c.nodes[raw as usize].text.clone())
.or_else(|| c.folded_text(c.key(node.id).unwrap()).map(str::to_owned))
})
.collect()
}
fn mounted(nested: bool, regions: bool) -> (Core<FakeEngine>, NodeId) {
let mut c = core();
c.set_content_culling(false);
c.mount_root(&Root::new::<RowsFixture>(move || FixtureProps {
nested,
regions,
}));
let batch = c.commit().unwrap();
let prefix = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Text { id, text, .. } if text.text == "prefix" => Some(*id),
_ => None,
})
.expect("prefix mounted");
let parent = c.nodes[c.key(prefix).unwrap() as usize].parent;
let parent = c.nodes[parent as usize].id;
(c, parent)
}
fn update(c: &mut Core<FakeEngine>, items: Vec<Item>, footer: bool) -> MountBatch {
{
let _entered = c.components.runtime.enter();
ITEMS.with(Cell::get).unwrap().set(items);
FOOTER.with(Cell::get).unwrap().set(footer);
}
c.commit().unwrap()
}
#[test]
fn same_order_values_update_existing_nodes_and_repair_an_external_gap() {
let (mut c, parent) = mounted(false, false);
let original = children(&c, parent);
let batch = update(
&mut c,
vec![
item(1, "ONE", true),
item(2, "two", true),
item(3, "three", true),
],
false,
);
assert_eq!(
order(&c, parent),
["prefix", "1:ONE@0", "2:two@1", "3:three@2", "suffix"]
);
assert_eq!(children(&c, parent), original);
assert_eq!(MADE.with(Cell::get), 3);
assert_eq!(
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Text { text, .. } => Some(text.text.as_str()),
_ => None,
})
.collect::<Vec<_>>(),
["1:ONE@0"]
);
assert!(
!batch.items.iter().any(|item| matches!(
item,
MountItem::Create { .. }
| MountItem::Delete { .. }
| MountItem::Insert { .. }
| MountItem::Remove { .. }
)),
"same-order values must not remount or move rows"
);
// Equal keys alone do not prove physical placement: an unrelated
// sibling now splits the region. Its rows must become contiguous.
c.apply(Op::Create {
id: 4000,
tag: Tag::View,
})
.unwrap();
// Public apply routes a component host's Insert to its passed
// children. Perturb the physical tree directly for this check.
c.insert(parent, 4000, Some(original[2])).unwrap();
let split = [
original[0],
original[1],
4000,
original[2],
original[3],
original[4],
];
assert_eq!(children(&c, parent), split, "the physical gap was inserted");
c.commit();
assert_eq!(
children(&c, parent),
split,
"the gap persists until reconciliation"
);
update(
&mut c,
vec![
item(1, "one", true),
item(2, "two", true),
item(3, "three", true),
],
false,
);
assert_eq!(
children(&c, parent),
[
original[0],
4000,
original[1],
original[2],
original[3],
original[4]
]
);
}
#[test]
fn same_order_region_rows_follow_empty_and_populated_anchors() {
let (mut c, parent) = mounted(false, true);
assert_eq!(
order(&c, parent),
["prefix", "1:one@0", "3:three@2", "suffix"]
);
update(
&mut c,
vec![
item(1, "one", true),
item(2, "TWO", true),
item(3, "three", true),
],
true,
);
assert_eq!(
order(&c, parent),
[
"prefix",
"1:one@0",
"2:TWO@1",
"3:three@2",
"anchor",
"suffix"
]
);
update(
&mut c,
vec![
item(1, "ONE", true),
item(2, "two", false),
item(3, "three", true),
],
false,
);
assert_eq!(
order(&c, parent),
["prefix", "1:ONE@0", "3:three@2", "suffix"]
);
assert_eq!(MADE.with(Cell::get), 3, "the dynamic row owners stay");
}
#[test]
fn reordered_added_and_removed_rows_keep_the_retained_node_ids() {
let (mut c, parent) = mounted(false, false);
let original = children(&c, parent);
update(
&mut c,
vec![
item(3, "THREE", true),
item(1, "ONE", true),
item(4, "four", true),
],
false,
);
assert_eq!(
order(&c, parent),
["prefix", "3:THREE@0", "1:ONE@1", "4:four@2", "suffix"]
);
let reordered = children(&c, parent);
assert_eq!(&reordered[1..3], &[original[3], original[1]]);
assert!(c.key(original[2]).is_err(), "the removed row was released");
assert_eq!(MADE.with(Cell::get), 4);
update(&mut c, vec![], false);
assert_eq!(order(&c, parent), ["prefix", "suffix"]);
}
#[test]
fn nested_component_content_keeps_its_existing_placement_path() {
let (mut c, parent) = mounted(true, false);
let original = children(&c, parent);
assert!(
c.is_host(parent)
&& c.components
.regions
.values()
.any(|state| state.host != parent
&& state
.children
.iter()
.any(|element| element.id == original[1])),
"the rows belong to the outer view and are children of a nested host"
);
update(
&mut c,
vec![
item(1, "ONE", true),
item(2, "two", true),
item(3, "three", true),
],
true,
);
assert_eq!(
order(&c, parent),
[
"prefix",
"1:ONE@0",
"2:two@1",
"3:three@2",
"anchor",
"suffix"
]
);
update(
&mut c,
vec![item(3, "three", true), item(1, "one", true)],
false,
);
assert_eq!(
order(&c, parent),
["prefix", "3:three@0", "1:one@1", "suffix"]
);
let reordered = children(&c, parent);
assert_eq!(&reordered[1..3], &[original[3], original[1]]);
assert_eq!(MADE.with(Cell::get), 3);
}
}
/// What an update of an [`each`] costs and sends for the rows it keeps.
mod each_updates {
use std::{
cell::RefCell,
collections::HashMap,
time::{Duration, Instant},
};
use super::*;
use crate::{
element::{Root, cleanup, effect},
prelude::*,
};
/// What a row of [`Listed`] makes.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Shape {
/// A text.
Text,
/// A text and a view.
Pair,
/// A region showing its text while the item's value is not a
/// multiple of three.
Region,
/// By its key: nothing, a text, or a text and a view.
Mixed,
}
/// An item of [`Listed`]: its key and its value.
type Item = (u32, u32);
thread_local! {
static START: RefCell<Vec<Item>> = const { RefCell::new(Vec::new()) };
static SHAPE: Cell<Shape> = const { Cell::new(Shape::Text) };
static LISTED: Cell<Option<Signal<Vec<Item>>>> = const { Cell::new(None) };
/// Rows made, rows disposed and calls of the key function.
static MADE: Cell<usize> = const { Cell::new(0) };
static GONE: Cell<usize> = const { Cell::new(0) };
static KEYED: Cell<usize> = const { Cell::new(0) };
/// What the rows' effects saw, in the order they ran.
static SEEN: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
/// The elements a row of `shape` makes for a key (`Mixed` decides by it).
fn parts(shape: Shape, key: u32) -> usize {
match shape {
Shape::Text | Shape::Region => 1,
Shape::Pair => 2,
Shape::Mixed => (key % 3) as usize,
}
}
/// The rows of `START`, then of what `LISTED` is set to, between two
/// texts. A row shows the order it was made in, its key, value and
/// index: `2:7:0@1` is the third row made, of key 7, second in the list.
#[component]
fn Listed() -> impl IntoElement {
let items = signal(START.with(|start| start.borrow().clone()));
LISTED.with(|listed| listed.set(Some(items)));
let shape = SHAPE.with(Cell::get);
let rows = each(
items,
|item: &Item| {
KEYED.with(|keyed| keyed.set(keyed.get() + 1));
item.0
},
move |item, index| {
let made = MADE.with(|made| made.replace(made.get() + 1));
cleanup(|| GONE.with(|gone| gone.set(gone.get() + 1)));
let key = item.get_untracked().0;
effect(move || {
let seen = format!("{made} is {}", item.get().1);
SEEN.with(|all| all.borrow_mut().push(seen));
});
effect(move || {
let seen = format!("{made} at {}", index.get());
SEEN.with(|all| all.borrow_mut().push(seen));
});
let caption = move || {
let (key, value) = item.get();
format!("{made}:{key}:{value}@{}", index.get())
};
let mark = move || view().child(text(format!("/{made}"))).into_element();
match (shape, parts(shape, key)) {
(Shape::Region, _) => vec![dynamic(move || {
(item.get().1 % 3 != 0).then(|| text(caption()))
})],
(_, 0) => Vec::new(),
(_, 1) => vec![text(caption).into_element()],
_ => vec![text(caption).into_element(), mark()],
}
},
);
view()
.child(text("before"))
.child(rows)
.child(text("after"))
}
/// [`Listed`] mounted with `start`'s rows of `shape`, and the view its
/// rows are in.
fn mounted(shape: Shape, start: &[Item]) -> (Core<FakeEngine>, NodeId) {
START.with(|s| *s.borrow_mut() = start.to_vec());
SHAPE.with(|s| s.set(shape));
for count in [&MADE, &GONE, &KEYED] {
count.with(|count| count.set(0));
}
SEEN.with(|seen| seen.borrow_mut().clear());
let mut c = core();
c.set_content_culling(false);
c.mount_root(&Root::new::<Listed>(|| ()));
let parent = views::root_host(&c.commit().unwrap());
(c, parent)
}
/// Sets the items; the commit's mount items.
fn set(c: &mut Core<FakeEngine>, items: &[Item]) -> Vec<MountItem> {
write(c, items);
c.commit().map(|batch| batch.items).unwrap_or_default()
}
/// Sets the items, without a commit.
fn write(c: &mut Core<FakeEngine>, items: &[Item]) {
let _entered = c.components.runtime.enter();
LISTED.with(Cell::get).unwrap().set(items.to_vec());
}
/// The children of `parent`, in order.
fn children(c: &Core<FakeEngine>, parent: NodeId) -> Vec<NodeId> {
let key = c.key(parent).unwrap();
c.nodes[key as usize]
.children
.iter()
.map(|&child| c.nodes[child as usize].id)
.collect()
}
/// The texts under `parent`, in the tree's order.
fn shown(c: &Core<FakeEngine>, parent: NodeId) -> Vec<String> {
fn collect(c: &Core<FakeEngine>, key: u32, out: &mut Vec<String>) {
let node = &c.nodes[key as usize];
if !node.text.is_empty() {
out.push(node.text.clone());
}
if let Some(run) = c.folded_text(key) {
out.push(run.to_owned());
}
for &child in &node.children {
collect(c, child, out);
}
}
let mut out = Vec::new();
collect(c, c.key(parent).unwrap(), &mut out);
out
}
/// What the rows' effects saw since the last call.
fn seen() -> Vec<String> {
SEEN.with(|seen| std::mem::take(&mut *seen.borrow_mut()))
}
fn structural(item: &MountItem) -> bool {
matches!(
item,
MountItem::Create { .. }
| MountItem::Delete { .. }
| MountItem::Insert { .. }
| MountItem::Remove { .. }
)
}
fn texts_of(items: &[MountItem]) -> Vec<&str> {
items
.iter()
.filter_map(|item| match item {
MountItem::Text { text, .. } => Some(text.text.as_str()),
_ => None,
})
.collect()
}
#[test]
fn equal_items_send_no_mount_items() {
let (mut c, parent) = mounted(Shape::Pair, &[(1, 0), (2, 0), (3, 0)]);
let nodes = children(&c, parent);
seen();
// An equal list set again: the signal notifies no one.
assert!(set(&mut c, &[(1, 0), (2, 0), (3, 0)]).is_empty());
assert_eq!(KEYED.with(Cell::get), 3, "the rows were not looked at");
// The same list written as a change: every row is looked at, and
// each is as it was.
{
let _entered = c.components.runtime.enter();
LISTED.with(Cell::get).unwrap().update(|_| {});
}
let items = c.commit().map(|batch| batch.items).unwrap_or_default();
assert!(items.is_empty(), "{items:?}");
assert_eq!(KEYED.with(Cell::get), 6);
assert_eq!(children(&c, parent), nodes);
assert_eq!((MADE.with(Cell::get), GONE.with(Cell::get)), (3, 0));
assert!(seen().is_empty(), "no row's item or index was written");
}
#[test]
fn a_row_changed_in_the_middle_sends_its_text_alone() {
let start: Vec<Item> = (0..40).map(|key| (key, 0)).collect();
let (mut c, parent) = mounted(Shape::Text, &start);
let nodes = children(&c, parent);
seen();
let mut items = start.clone();
items[17].1 = 5;
let batch = set(&mut c, &items);
assert_eq!(texts_of(&batch), ["17:17:5@17"]);
assert!(!batch.iter().any(structural), "{batch:?}");
assert_eq!(children(&c, parent), nodes);
assert_eq!((MADE.with(Cell::get), GONE.with(Cell::get)), (40, 0));
assert_eq!(seen(), ["17 is 5"]);
// The first and the last, in one update.
items[0].1 = 1;
items[39].1 = 2;
let batch = set(&mut c, &items);
assert_eq!(texts_of(&batch), ["0:0:1@0", "39:39:2@39"]);
assert!(!batch.iter().any(structural), "{batch:?}");
assert_eq!(seen(), ["0 is 1", "39 is 2"]);
}
#[test]
fn an_appended_row_is_made_after_the_rows_that_stay() {
let start: Vec<Item> = (0..30).map(|key| (key, 0)).collect();
let (mut c, parent) = mounted(Shape::Pair, &start);
let nodes = children(&c, parent);
seen();
let mut items = start.clone();
// The last row changes as one comes after it.
items[29].1 = 4;
items.push((30, 0));
let batch = set(&mut c, &items);
// (The row made is applied as the region is; the row that stays
// follows with its binding's patch.)
assert_eq!(texts_of(&batch), ["30:30:0@30", "/30", "29:29:4@29"]);
let now = children(&c, parent);
// "before", 30 rows of two, the new row's two, "after".
assert_eq!(now.len(), nodes.len() + 2);
assert_eq!(now[..61], nodes[..61], "the rows before it stay");
assert_eq!(now[63], nodes[61], "what follows the rows stays");
let inserted: Vec<NodeId> = batch
.iter()
.filter_map(|item| match item {
MountItem::Insert {
parent: p, child, ..
} if *p == parent => Some(*child),
_ => None,
})
.collect();
assert_eq!(inserted.len(), 2, "only the new row's nodes are placed");
assert!(inserted.contains(&now[61]) && inserted.contains(&now[62]));
assert!(
!batch
.iter()
.any(|item| matches!(item, MountItem::Delete { .. } | MountItem::Remove { .. }))
);
assert_eq!((MADE.with(Cell::get), GONE.with(Cell::get)), (31, 0));
assert_eq!(seen(), ["29 is 4", "30 is 0", "30 at 30"]);
// The next update finds every row, the new one too.
items[30].1 = 1;
let batch = set(&mut c, &items);
assert_eq!(texts_of(&batch), ["30:30:1@30"]);
assert!(!batch.iter().any(structural), "{batch:?}");
assert_eq!(children(&c, parent), now);
}
#[test]
fn a_removed_row_goes_and_the_rows_after_it_follow() {
let start: Vec<Item> = (0..6).map(|key| (key, 0)).collect();
let (mut c, parent) = mounted(Shape::Text, &start);
let nodes = children(&c, parent);
seen();
let mut items = start.clone();
items.remove(2);
let batch = set(&mut c, &items);
assert_eq!(
shown(&c, parent),
[
"before", "0:0:0@0", "1:1:0@1", "3:3:0@2", "4:4:0@3", "5:5:0@4", "after"
]
);
assert_eq!(texts_of(&batch), ["3:3:0@2", "4:4:0@3", "5:5:0@4"]);
let now = children(&c, parent);
assert_eq!(now[..3], nodes[..3]);
assert_eq!(now[3..], nodes[4..], "the rows after it keep their nodes");
assert!(c.key(nodes[3]).is_err(), "its node is released");
assert!(
!batch
.iter()
.any(|item| matches!(item, MountItem::Create { .. } | MountItem::Insert { .. }))
);
assert_eq!((MADE.with(Cell::get), GONE.with(Cell::get)), (6, 1));
assert_eq!(seen(), ["3 at 2", "4 at 3", "5 at 4"]);
// The last rows go, then all of them.
items.truncate(2);
set(&mut c, &items);
assert_eq!(shown(&c, parent), ["before", "0:0:0@0", "1:1:0@1", "after"]);
assert_eq!(GONE.with(Cell::get), 4);
set(&mut c, &[]);
assert_eq!(shown(&c, parent), ["before", "after"]);
assert_eq!((MADE.with(Cell::get), GONE.with(Cell::get)), (6, 6));
}
#[test]
fn moved_rows_keep_their_nodes_and_follow_their_places() {
let start: Vec<Item> = (0..5).map(|key| (key, 0)).collect();
let (mut c, parent) = mounted(Shape::Text, &start);
let nodes = children(&c, parent);
seen();
// The last row comes first, changed on the way.
let batch = set(&mut c, &[(4, 9), (0, 0), (1, 0), (2, 0), (3, 0)]);
assert_eq!(
shown(&c, parent),
[
"before", "4:4:9@0", "0:0:0@1", "1:1:0@2", "2:2:0@3", "3:3:0@4", "after"
]
);
assert_eq!(
children(&c, parent),
[
nodes[0], nodes[5], nodes[1], nodes[2], nodes[3], nodes[4], nodes[6]
]
);
assert!(
!batch
.iter()
.any(|item| matches!(item, MountItem::Create { .. } | MountItem::Delete { .. }))
);
assert_eq!(
seen(),
["4 is 9", "4 at 0", "0 at 1", "1 at 2", "2 at 3", "3 at 4"]
);
// Two rows in the middle change places; the others are not written.
set(&mut c, &[(4, 9), (1, 0), (0, 0), (2, 0), (3, 0)]);
assert_eq!(
children(&c, parent),
[
nodes[0], nodes[5], nodes[2], nodes[1], nodes[3], nodes[4], nodes[6]
]
);
assert_eq!(seen(), ["1 at 1", "0 at 2"]);
// A row comes in the middle, among rows that stay.
set(&mut c, &[(4, 9), (1, 0), (7, 0), (0, 0), (2, 0), (3, 0)]);
assert_eq!(
shown(&c, parent),
[
"before", "4:4:9@0", "1:1:0@1", "5:7:0@2", "0:0:0@3", "2:2:0@4", "3:3:0@5", "after"
]
);
let now = children(&c, parent);
assert_eq!(
[now[1], now[2], now[4], now[5], now[6]],
[nodes[5], nodes[2], nodes[1], nodes[3], nodes[4]]
);
assert_eq!((MADE.with(Cell::get), GONE.with(Cell::get)), (6, 0));
assert_eq!(seen(), ["5 is 0", "5 at 2", "0 at 3", "2 at 4", "3 at 5"]);
}
#[test]
fn rows_set_twice_before_a_commit_show_the_last_list() {
let (mut c, parent) = mounted(Shape::Pair, &[(1, 0), (2, 0), (3, 0)]);
let nodes = children(&c, parent);
// A row comes and goes before the core places it; another stays.
write(&mut c, &[(1, 0), (8, 0), (2, 0), (3, 0)]);
write(&mut c, &[(1, 0), (2, 0), (3, 1), (9, 0)]);
let batch = c.commit().unwrap().items;
assert_eq!(
shown(&c, parent),
[
"before", "0:1:0@0", "/0", "1:2:0@1", "/1", "2:3:1@2", "/2", "4:9:0@3", "/4",
"after"
]
);
let now = children(&c, parent);
assert_eq!(now[..7], nodes[..7]);
assert_eq!(now[9], nodes[7]);
assert!(
!texts_of(&batch).iter().any(|text| text.starts_with("3:8")),
"the row that went was never shown"
);
assert_eq!((MADE.with(Cell::get), GONE.with(Cell::get)), (5, 1));
}
/// The rows an update keeps, as a map of the rows by key decides it:
/// a key that stays keeps its row, the others are made. With a key
/// twice the second is a row of its own, and the map then holds the
/// last row of that key.
#[derive(Default)]
struct Model {
/// The key and the order it was made in, of each row.
rows: Vec<(u32, usize)>,
made: usize,
/// The calls of the key function: one for each item of an update.
keyed: usize,
/// The rows disposed; `None` once a key came twice (the rows the
/// map dropped are not counted here).
gone: Option<usize>,
}
impl Model {
fn update(&mut self, items: &[Item]) {
let count = self.rows.len();
self.keyed += items.len();
let mut old: HashMap<u32, usize> = self.rows.drain(..).collect();
if old.len() != count {
self.gone = None;
}
for &(key, _) in items {
let made = old.remove(&key).unwrap_or_else(|| {
self.made += 1;
self.made - 1
});
self.rows.push((key, made));
}
if let Some(gone) = &mut self.gone {
*gone += old.len();
}
}
/// What [`Listed`] shows for `items`.
fn shown(&self, shape: Shape, items: &[Item]) -> Vec<String> {
let mut out = vec!["before".to_owned()];
for (index, (&(key, made), &(_, value))) in self.rows.iter().zip(items).enumerate() {
let caption = format!("{made}:{key}:{value}@{index}");
match (shape, parts(shape, key)) {
(Shape::Region, _) if value % 3 == 0 => {}
(_, 0) => {}
(_, 1) => out.push(caption),
_ => out.extend([caption, format!("/{made}")]),
}
}
out.push("after".to_owned());
out
}
}
/// A small generator (xorshift): the same lists on every run.
struct Random(u64);
impl Random {
fn next(&mut self, below: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % below.max(1) as u64) as usize
}
}
/// The next list after `items`: one of the changes a list goes
/// through. `twice` lets a key come a second time.
fn changed(random: &mut Random, items: &[Item], fresh: &mut u32, twice: bool) -> Vec<Item> {
let mut items = items.to_vec();
let len = items.len();
let new = |fresh: &mut u32| {
*fresh += 1;
(*fresh, 1)
};
match random.next(if twice { 14 } else { 13 }) {
// The streamed reply's: the last row changes, or one comes.
0 | 1 if len > 0 => items[len - 1].1 += 1,
2 | 3 => items.push(new(fresh)),
4 if len > 0 => {
items[len - 1].1 += 1;
items.push(new(fresh));
}
5 if len > 0 => items[random.next(len)].1 += 1,
6 => {
let at = random.next(len + 1);
items.insert(at, new(fresh));
}
7 if len > 0 => {
items.remove(random.next(len));
}
8 if len > 1 => {
let (a, b) = (random.next(len), random.next(len));
items.swap(a, b);
}
9 if len > 1 => {
let by = random.next(len);
items.rotate_left(by);
}
10 => items.reverse(),
11 => {
// Several rows go and several come, wherever.
for _ in 0..random.next(4) {
if !items.is_empty() {
items.remove(random.next(items.len()));
}
}
for _ in 0..random.next(4) {
let at = random.next(items.len() + 1);
items.insert(at, new(fresh));
}
}
12 => match random.next(8) {
0 => items.clear(),
_ => items.truncate(len.saturating_sub(random.next(3))),
},
13 if len > 0 => {
let key = items[random.next(len)].0;
let at = random.next(len + 1);
items.insert(at, (key, 2));
}
_ => items.push(new(fresh)),
}
items
}
/// Lists changed at random, checked after every commit against
/// [`Model`]: which rows stay, are made and go, what is shown and in
/// which order. `twice` lets keys come twice. With `NSH_EACH_ITEMS`
/// naming a file, every commit's mount items are added to it, to
/// compare two builds.
fn follows_the_model(twice: bool) {
let mut record = String::new();
for (seed, shape) in [Shape::Text, Shape::Pair, Shape::Region, Shape::Mixed]
.into_iter()
.cycle()
.enumerate()
.take(24)
{
let mut random = Random(0x9E37_79B9_7F4A_7C15 ^ (seed as u64 + 1) << 20 | 1);
let mut fresh = 100;
let mut items: Vec<Item> = (0..random.next(12) as u32).map(|key| (key, 1)).collect();
let (mut c, parent) = mounted(shape, &items);
let mut model = Model {
gone: Some(0),
..Model::default()
};
model.update(&items);
assert_eq!(shown(&c, parent), model.shown(shape, &items));
for step in 0..160 {
// Mostly one list a commit; sometimes two or three.
for _ in 0..[1, 1, 1, 2, 3][random.next(5)] {
let next = changed(&mut random, &items, &mut fresh, twice);
if next != items {
model.update(&next);
}
write(&mut c, &next);
items = next;
}
let batch = c.commit().map(|batch| batch.items).unwrap_or_default();
record.push_str(&format!("{shape:?} {seed} {step} {items:?}\n{batch:#?}\n"));
let context = format!("{shape:?}, seed {seed}, step {step}: {items:?}");
assert_eq!(shown(&c, parent), model.shown(shape, &items), "{context}");
assert_eq!(MADE.with(Cell::get), model.made, "{context}");
assert_eq!(KEYED.with(Cell::get), model.keyed, "{context}");
if let Some(gone) = model.gone {
assert_eq!(GONE.with(Cell::get), gone, "{context}");
}
}
}
if let Ok(path) = std::env::var("NSH_EACH_ITEMS") {
let path = format!("{path}.{}", if twice { "twice" } else { "once" });
std::fs::write(path, record).unwrap();
}
}
#[test]
fn random_lists_keep_the_rows_a_map_by_key_keeps() {
follows_the_model(false);
}
#[test]
fn random_lists_with_a_key_twice_keep_the_rows_a_map_by_key_keeps() {
follows_the_model(true);
}
/// What a press of [`BenchRows`] does.
#[derive(Clone, Copy, PartialEq)]
enum Change {
/// The last row's item changes; the keys stay.
Last,
/// A row is added after the others.
Append,
/// A text beside the rows changes, the items are not set: what a
/// commit of the same tree costs without the `each`.
Beside,
/// A view after the rows changes its height, the items are not
/// set: what laying the rows' parent out again costs, as a row
/// added to it does.
Resize,
}
thread_local! {
static ROWS: Cell<usize> = const { Cell::new(0) };
static CHANGE: Cell<Change> = const { Cell::new(Change::Last) };
/// Keys as `TextView`'s rows have them: a position and a name.
static NAMED: Cell<bool> = const { Cell::new(false) };
}
fn press(items: Signal<Vec<(usize, u32)>>, beside: Signal<u32>) {
match CHANGE.with(Cell::get) {
Change::Last => items.update(|items| {
if let Some(last) = items.last_mut() {
last.1 += 1;
}
}),
Change::Append => items.update(|items| items.push((items.len(), 0))),
Change::Beside | Change::Resize => beside.update(|n| *n += 1),
}
}
fn row(item: ReadSignal<(usize, u32)>) -> impl IntoElement {
view().p_1().child(text(move || {
let (at, n) = item.get();
format!("row {at} {n}")
}))
}
/// `ROWS` rows of an `each`, changed by a press as `CHANGE` says.
#[component]
fn BenchRows() -> impl IntoElement {
let items = signal(
(0..ROWS.with(Cell::get))
.map(|i| (i, 0u32))
.collect::<Vec<_>>(),
);
let beside = signal(0u32);
let rows = if NAMED.with(Cell::get) {
each(
items,
|item| (item.0, "paragraph".to_owned()),
|item, _| row(item),
)
} else {
each(items, |item| item.0, |item, _| row(item))
};
let resized = CHANGE.with(Cell::get) == Change::Resize;
view()
.on_press(move |_: &()| press(items, beside))
.child(text(move || {
format!("beside {}", if resized { 0 } else { beside.get() })
}))
.child(rows)
.child(view().h(move || {
px(if resized {
4.0 + (beside.get() % 2) as f32
} else {
4.0
})
}))
}
/// `cargo test --release -p nsh-core bench_each_update -- --ignored --nocapture`;
/// the numbers are in `docs/dev/performance.md`.
#[test]
#[ignore]
fn bench_each_update() {
println!("µs an update: the event (the rows' pass) + the commit | mount items");
for named in [false, true] {
for rows in [640, 1_280, 5_000] {
for (change, label) in [
(Change::Beside, "no row set"),
(Change::Resize, "parent laid out"),
(Change::Last, "last row changed"),
(Change::Append, "row appended"),
] {
ROWS.with(|r| r.set(rows));
CHANGE.with(|c| c.set(change));
NAMED.with(|n| n.set(named));
let mut c = core();
c.mount_root(&Root::new::<BenchRows>(|| ()));
let host = views::root_host(&c.commit().unwrap());
let n = 200;
let (mut event, mut commit) = (Duration::ZERO, Duration::ZERO);
let mut items = 0;
for _ in 0..n {
let start = Instant::now();
c.component_event(host, EventKind::Press, &EventPayload::None);
let mid = Instant::now();
items += c.commit().map_or(0, |b| b.items.len());
event += mid - start;
commit += mid.elapsed();
}
let us = |d: Duration| d.as_secs_f64() * 1e6 / f64::from(n);
println!(
"{} keys, {rows:>5} rows, {label:<16} | {:>8.1} + {:>8.1} = {:>8.1} | {}",
if named { "named" } else { "plain" },
us(event),
us(commit),
us(event + commit),
items / n as usize
);
}
}
}
}
#[test]
fn long_lists_reversed_and_shuffled_keep_their_rows() {
// More rows than are searched without an index (`OldKeys`).
for shape in [Shape::Text, Shape::Pair, Shape::Region, Shape::Mixed] {
let start: Vec<Item> = (0..40).map(|k| (k, 1)).collect();
let (mut c, parent) = mounted(shape, &start);
let rows = |c: &Core<FakeEngine>| children(c, parent);
let before = rows(&c);
let shown_before = shown(&c, parent);
let reversed: Vec<Item> = start.iter().rev().copied().collect();
let items = set(&mut c, &reversed);
assert!(
!items
.iter()
.any(|i| matches!(i, MountItem::Create { .. } | MountItem::Delete { .. })),
"{shape:?}: a reversed row is moved, not made again"
);
assert_eq!(MADE.with(Cell::get), 40, "{shape:?}");
// Each row's texts (index left out), grouped by key: a row's
// view (`/made`) follows its text.
let by_key = |texts: Vec<String>| {
let mut rows: Vec<(u32, Vec<String>)> = Vec::new();
for t in texts {
let t = t.split('@').next().unwrap().to_owned();
if t == "before" || t == "after" {
continue;
}
if t.starts_with('/') {
rows.last_mut().unwrap().1.push(t);
} else {
let key = t.split(':').nth(1).unwrap().parse().unwrap();
rows.push((key, vec![t]));
}
}
rows
};
let mut expected = by_key(shown_before);
expected.reverse();
let now = by_key(shown(&c, parent));
assert_eq!(now, expected, "{shape:?}");
let mut kept = rows(&c);
kept.sort_unstable();
let mut was = before.clone();
was.sort_unstable();
assert_eq!(kept, was, "{shape:?}: the same nodes");
// A shuffle with rows added and removed.
let shuffled: Vec<Item> = (0..40)
.map(|i| ((i * 17) % 40, 1))
.filter(|&(k, _)| k % 7 != 3)
.chain([(100, 1), (101, 1)])
.collect();
set(&mut c, &shuffled);
let keys: Vec<u32> = shown(&c, parent)
.into_iter()
.filter(|t| t.contains('@'))
.map(|t| t.split(':').nth(1).unwrap().parse().unwrap())
.collect();
let wanted: Vec<u32> = shuffled
.iter()
.map(|&(k, _)| k)
.filter(|&k| parts(shape, k) > 0)
.collect();
assert_eq!(keys, wanted, "{shape:?}");
assert_eq!(MADE.with(Cell::get), 42, "{shape:?}");
}
}
/// `cargo test --release -p nsh-core --lib bench_each_reverse -- --ignored --nocapture`;
/// the numbers are in `docs/dev/performance.md`.
#[test]
#[ignore]
fn bench_each_reverse() {
println!("ms a commit (median of 5) | mount items");
for rows in [1_000u32, 4_000, 8_000] {
for (label, shape) in [("text", Shape::Text), ("text + view", Shape::Pair)] {
let start: Vec<Item> = (0..rows).map(|k| (k, 0)).collect();
let reversed: Vec<Item> = start.iter().rev().copied().collect();
let rotated: Vec<Item> = (1..rows).chain([0]).map(|k| (k, 0)).collect();
for (step, to) in [("reverse", &reversed), ("first to last", &rotated)] {
let mut times = Vec::new();
let mut items = 0;
for _ in 0..5 {
let (mut c, _) = mounted(shape, &start);
let at = Instant::now();
items = set(&mut c, to).len();
times.push(at.elapsed().as_secs_f64() * 1e3);
}
times.sort_by(f64::total_cmp);
println!(
"{rows:>5} rows of {label:<11} {step:<13} | {:>8.2} | {items}",
times[2]
);
}
}
}
}
thread_local! {
/// [`MountRows`] in a scroll view, which culls the rows it does
/// not show.
static SCROLLED: Cell<bool> = const { Cell::new(false) };
/// Each row of [`MountRows`] with a hint, as a document's links
/// have their addresses: an overlay each.
static HINTED: Cell<bool> = const { Cell::new(false) };
/// Each row of [`MountRows`] with a [`Tip`], as a toolbar has its
/// tooltips: a component whose root is an overlay each.
static TIPPED: Cell<bool> = const { Cell::new(false) };
}
/// A component whose root is a hint overlay, as a tooltip is: its
/// host is made a view, then takes the overlay's kind.
#[derive(Default)]
struct Tip;
#[derive(Clone, PartialEq, Props)]
struct TipProps {}
impl Component for Tip {
type Props = TipProps;
type Event = NoEvent;
fn view(_: TipProps, _: Scope<NoEvent>) -> impl IntoElement {
overlay()
.hint(Duration::from_millis(500))
.child(text("tip"))
}
}
/// `ROWS` rows of an `each` as `TextView` has a document's blocks: a
/// view each, keyed by position and kind, with a region in it; a text
/// before them and a view after them.
#[component]
fn MountRows() -> impl IntoElement {
let items = signal(
(0..ROWS.with(Cell::get))
.map(|i| (i, 0u32))
.collect::<Vec<_>>(),
);
let hinted = HINTED.with(Cell::get);
let tipped = TIPPED.with(Cell::get);
let rows = view()
.flex_col()
.child(text("before"))
.child(each(
items,
|item| (item.0, "paragraph".to_owned()),
move |item, _| {
view()
.child(dynamic(move || {
let (at, n) = item.get();
text(format!("row {at} {n}"))
}))
.child(hinted.then(|| {
overlay()
.hint(Duration::from_millis(500))
.child(text("https://example.com"))
}))
.child(tipped.then(|| Tip::element(TipProps {})))
},
))
.child(view().h(px(4.0)));
if SCROLLED.with(Cell::get) {
scroll().size_full().child(rows).into_element()
} else {
rows.into_element()
}
}
/// [`MountRows`] mounted with `rows` rows and, in a scroll view,
/// scrolled down 20 points a frame for `frames` frames: the core and
/// its scroll view.
fn rows_mounted(rows: usize, frames: u32) -> (Core<FakeEngine>, Option<NodeId>) {
ROWS.with(|r| r.set(rows));
let mut c = core();
c.mount_root(&Root::new::<MountRows>(|| ()));
let batch = c.commit();
let scroll = batch
.iter()
.flat_map(|b| &b.items)
.find_map(|item| match item {
MountItem::Create {
id,
kind: ViewKind::Scroll,
} => Some(*id),
_ => None,
});
if let Some(id) = scroll {
for n in 1..=frames {
c.set_scroll_offset(id, point(px(0.0), px(20.0 * n as f32)), u32::MAX);
c.commit();
}
}
(c, scroll)
}
/// Rows of an `each` mounted at once, and made as they scroll into
/// sight, are placed among their siblings without a search of all of
/// them, or of all the overlays (a hint a row), for each: the siblings
/// and overlays looked at grow with the rows, not with their square.
#[test]
fn rows_mounted_at_once_are_placed_without_a_search_for_each() {
let mut grew = Vec::new();
for scrolled in [false, true] {
for hinted in [false, true] {
SCROLLED.with(|s| s.set(scrolled));
HINTED.with(|h| h.set(hinted));
let work = |rows| {
let (c, _) = rows_mounted(rows, 20);
c.components.placing_work.get()
};
let (few, many) = (work(400), work(1_600));
// Four times the rows: about four times the work (it was
// about sixteen times, with a search for each row).
if many > 5 * few {
grew.push(format!(
"scrolled {scrolled}, hinted {hinted}: {few} for 400 rows, {many} for 1,600"
));
}
}
}
SCROLLED.with(|s| s.set(false));
HINTED.with(|h| h.set(false));
assert!(grew.is_empty(), "{grew:#?}");
}
/// The rows end up in order, after the text before them and before the
/// view after them, mounted at once and made as they scroll into
/// sight.
#[test]
fn rows_mounted_at_once_keep_their_order() {
for scrolled in [false, true] {
SCROLLED.with(|s| s.set(scrolled));
let (c, _) = rows_mounted(300, 40);
// The column: the view of the text, the rows and the view.
let mut stack = vec![c.root];
let column = std::iter::from_fn(|| {
let key = stack.pop()?;
stack.extend(&c.nodes[key as usize].children);
Some(key)
})
.find(|&key| c.nodes[key as usize].children.len() == 302)
.expect("the column");
let children = &c.nodes[column as usize].children;
let mut expected = vec!["before".to_owned()];
expected.extend((0..300).map(|i| format!("row {i} 0")));
assert_eq!(
shown(&c, c.nodes[column as usize].id),
expected,
"scrolled {scrolled}"
);
assert!(c.nodes[children[301] as usize].text.is_empty());
}
SCROLLED.with(|s| s.set(false));
}
/// Rows mounted at once, each with a component whose root is an
/// overlay (a tooltip), give the components' hosts their roots' kind
/// without a pass over the batch's mount items for each: the items
/// looked at grow with the rows, not with their square.
#[test]
fn component_roots_mounted_at_once_take_their_kind_without_a_pass_for_each() {
TIPPED.with(|t| t.set(true));
let mut grew = Vec::new();
for scrolled in [false, true] {
SCROLLED.with(|s| s.set(scrolled));
let work = |rows| {
let (c, _) = rows_mounted(rows, 0);
c.components.retag_work.get()
};
let (few, many) = (work(400), work(1_600));
eprintln!("scrolled {scrolled}: {few} items for 400 rows, {many} for 1,600");
// Four times the rows: about four times the work (it was
// about sixteen times, with a pass for each component).
if many > 5 * few {
grew.push(format!(
"scrolled {scrolled}: {few} for 400 rows, {many} for 1,600"
));
}
}
SCROLLED.with(|s| s.set(false));
TIPPED.with(|t| t.set(false));
assert!(grew.is_empty(), "{grew:#?}");
}
/// Hosts that take their component root's kind in the batch they are
/// made in are made once, with that kind, before they are inserted.
#[test]
fn component_roots_mounted_at_once_are_made_once() {
TIPPED.with(|t| t.set(true));
ROWS.with(|r| r.set(50));
let mut c = core();
c.mount_root(&Root::new::<MountRows>(|| ()));
let batch = c.commit().expect("a batch");
TIPPED.with(|t| t.set(false));
let mut made = std::collections::HashSet::new();
for item in &batch.items {
match item {
MountItem::Create { id, .. } => {
assert!(made.insert(*id), "{id:?} made twice: {:?}", batch.items);
}
MountItem::Insert { child, .. } => {
assert!(made.contains(child), "{child:?} inserted before it is made");
}
_ => {}
}
}
let tips = c
.overlays
.iter()
.filter(|&&key| c.nodes[key as usize].kind == Kind::Overlay)
.count();
assert_eq!(tips, 50);
}
/// `batch`, a first batch: every view in it is made once, before it is
/// inserted, and is still in the tree (none removed in the batch left
/// its `Create` or `Insert`).
fn made_once_before_inserted(c: &Core<FakeEngine>, batch: &MountBatch) {
let mut made = std::collections::HashSet::new();
for item in &batch.items {
let id = match item {
MountItem::Create { id, .. } => {
assert!(made.insert(*id), "{id:?} made twice: {:?}", batch.items);
*id
}
MountItem::Insert { child, .. } => {
assert!(
made.contains(child),
"{child:?} inserted before it is made: {:?}",
batch.items
);
*child
}
_ => continue,
};
assert!(c.key(id).is_ok(), "{id:?} is gone: {:?}", batch.items);
}
}
/// The views of `kind` made in `batch`.
fn made_as(batch: &MountBatch, kind: ViewKind) -> Vec<NodeId> {
batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Create { id, kind: k } if *k == kind => Some(*id),
_ => None,
})
.collect()
}
/// A component whose root is a list in its parent's viewport: its host
/// is made a view, takes the list's kind, then the list's `viewport`
/// changes the kind of its `Create`.
#[component]
fn ParentList() -> impl IntoElement {
virtual_list(|| 3usize, |_| view().h(px(20.0)).child(text("row")))
.viewport(ListViewport::Parent)
}
/// Tips and lists in their parent's viewport, all components' roots
/// taking their kind in one round of renders.
#[component]
fn ParentLists() -> impl IntoElement {
scroll().size_full().child(
view()
.flex_col()
.child(Tip::element(TipProps {}))
.child(ParentList::element(()))
.child(Tip::element(TipProps {}))
.child(ParentList::element(()))
.child(Tip::element(TipProps {})),
)
}
/// A list that is a component's root and set in its parent's viewport
/// in the round its host takes the list's kind is made once, as a
/// plain view: the viewport changes its one `Create`, not the one its
/// host had as a view.
#[test]
fn a_component_root_list_in_its_parents_viewport_is_made_once() {
let mut c = core();
c.mount_root(&Root::new::<ParentLists>(|| ()));
let batch = c.commit().expect("a batch");
made_once_before_inserted(&c, &batch);
let lists: Vec<_> = c
.nodes
.iter()
.filter(|(_, n)| n.kind == Kind::List)
.map(|(_, n)| n.id)
.collect();
assert_eq!(lists.len(), 2);
let views = made_as(&batch, ViewKind::View);
for id in &lists {
assert!(
views.contains(id),
"{id:?} not made a view: {:?}",
batch.items
);
}
assert!(
made_as(&batch, ViewKind::Scroll).len() == 1,
"{:?}",
batch.items
);
let tips = (c.overlays.iter())
.filter(|&&key| c.nodes[key as usize].kind == Kind::Overlay)
.count();
assert_eq!(tips, 3);
}
thread_local! {
/// Whether [`Vanishing`] shows its [`GoneTip`].
static SHOWN: Cell<Option<Signal<bool>>> = const { Cell::new(None) };
}
/// A tip that, as it renders, has the view holding it drop it: its
/// host takes the overlay's kind and goes in the same round.
#[component]
fn GoneTip() -> impl IntoElement {
if let Some(shown) = SHOWN.with(Cell::get) {
shown.set(false);
}
overlay()
.hint(Duration::from_millis(500))
.child(text("gone"))
}
/// Tips around a [`GoneTip`].
#[component]
fn Vanishing() -> impl IntoElement {
let shown = signal(true);
SHOWN.with(|s| s.set(Some(shown)));
view()
.flex_col()
.child(Tip::element(TipProps {}))
.child(dynamic(move || shown.get().then(|| GoneTip::element(()))))
.child(Tip::element(TipProps {}))
}
/// A host that takes its component root's kind and is removed in the
/// same round leaves neither its `Create` nor its `Insert`; the tips
/// around it are made once.
#[test]
fn a_component_root_that_takes_its_kind_and_goes_in_one_round_leaves_nothing() {
let mut c = core();
c.mount_root(&Root::new::<Vanishing>(|| ()));
let batch = c.commit().expect("a batch");
SHOWN.with(|s| s.set(None));
made_once_before_inserted(&c, &batch);
let tips = (c.overlays.iter())
.filter(|&&key| c.nodes[key as usize].kind == Kind::Overlay)
.count();
assert_eq!(tips, 2);
}
/// A tip, then a list whose rows (made in a later round, once the
/// layout gives the list its viewport) hold a tip each.
#[component]
fn TippedList() -> impl IntoElement {
view()
.size_full()
.flex_col()
.child(Tip::element(TipProps {}))
.child(
virtual_list(
|| 40usize,
|_| view().h(px(30.0)).child(Tip::element(TipProps {})),
)
.flex_1(),
)
}
/// Hosts taking their component root's kind in several rounds of one
/// batch are each made once, before they are inserted.
#[test]
fn component_roots_taking_their_kind_in_later_rounds_are_made_once() {
let mut c = core();
c.mount_root(&Root::new::<TippedList>(|| ()));
let batch = c.commit().expect("a batch");
assert!(
c.components.retag_rounds.get() >= 2,
"the rows' tips took their kind in the first round"
);
made_once_before_inserted(&c, &batch);
let tips = (c.overlays.iter())
.filter(|&&key| c.nodes[key as usize].kind == Kind::Overlay)
.count();
assert!(tips > 1, "no row's tip: {:?}", batch.items);
}
/// `cargo test --release -p nsh-core --lib bench_component_roots_mount -- --ignored --nocapture`:
/// [`MountRows`] with a [`Tip`] in each row, mounted at once; the
/// numbers are in `docs/dev/performance.md`.
#[test]
#[ignore]
fn bench_component_roots_mount() {
println!("ms a first mount: the root's pass + the commit | mount items");
TIPPED.with(|t| t.set(true));
for scrolled in [false, true] {
SCROLLED.with(|s| s.set(scrolled));
for rows in [1_000, 10_000, 20_000] {
ROWS.with(|r| r.set(rows));
let mut best = (Duration::from_secs(3600), Duration::ZERO, 0);
for _ in 0..3 {
let mut c = core();
let start = Instant::now();
c.mount_root(&Root::new::<MountRows>(|| ()));
let mid = Instant::now();
let batch = c.commit();
let first = mid.elapsed();
if mid - start + first < best.0 + best.1 {
best = (mid - start, first, batch.map_or(0, |b| b.items.len()));
}
}
let ms = |d: Duration| d.as_secs_f64() * 1e3;
println!(
"{:<9} {rows:>6} rows | {:>8.1} + {:>8.1} = {:>8.1} | {:>6}",
if scrolled { "scrolled" } else { "plain" },
ms(best.0),
ms(best.1),
ms(best.0 + best.1),
best.2
);
}
}
SCROLLED.with(|s| s.set(false));
TIPPED.with(|t| t.set(false));
}
/// `cargo test --release -p nsh-core --lib bench_each_mount -- --ignored --nocapture`:
/// an `each` of N rows mounted at once, as `TextView` mounts a long
/// document's blocks, then, in a scroll view, scrolled down 20 points
/// a frame for 200 frames; the numbers are in `docs/dev/performance.md`.
#[test]
#[ignore]
fn bench_each_mount() {
println!(
"ms a first mount: the root's pass + the commit | mount items | µs a scrolled frame"
);
for (scrolled, hinted) in [(false, false), (true, false), (true, true)] {
SCROLLED.with(|s| s.set(scrolled));
HINTED.with(|h| h.set(hinted));
for rows in [1_000, 10_000, 50_000] {
ROWS.with(|r| r.set(rows));
let mut c = core();
let start = Instant::now();
c.mount_root(&Root::new::<MountRows>(|| ()));
let mid = Instant::now();
let batch = c.commit();
let (first, items) = (mid.elapsed(), batch.as_ref().map_or(0, |b| b.items.len()));
let scroll = batch
.iter()
.flat_map(|b| &b.items)
.find_map(|item| match item {
MountItem::Create {
id,
kind: ViewKind::Scroll,
} => Some(*id),
_ => None,
});
let frame = scroll.map(|id| {
let frames = 200;
let start = Instant::now();
for n in 1..=frames {
c.set_scroll_offset(id, point(px(0.0), px(20.0 * n as f32)), u32::MAX);
c.commit();
}
start.elapsed().as_secs_f64() * 1e6 / f64::from(frames)
});
let ms = |d: Duration| d.as_secs_f64() * 1e3;
println!(
"{:<15} {rows:>6} rows | {:>8.1} + {:>8.1} = {:>8.1} | {items:>6} | {}",
match (scrolled, hinted) {
(false, _) => "plain",
(true, false) => "scrolled",
(true, true) => "scrolled, hints",
},
ms(mid - start),
ms(first),
ms(mid - start + first),
frame.map_or("-".to_owned(), |us| format!("{us:.1}"))
);
}
}
SCROLLED.with(|s| s.set(false));
HINTED.with(|h| h.set(false));
}
}
/// The default `evaluate` timeout.
const T: std::time::Duration = std::time::Duration::from_secs(30);
fn evaluation_core() -> Core<FakeEngine> {
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Ios,
web_evaluate: true,
..Default::default()
});
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
c
}
#[test]
fn web_evaluation_correlates_replies_and_ignores_late_or_foreign_replies() {
use crate::element::Answer;
let mut c = evaluation_core();
let (one, a) = Answer::new();
let (two, b) = Answer::new();
c.start_web_evaluation(2, "1".into(), T, a.clone());
c.start_web_evaluation(2, "2".into(), T, b.clone());
let batch = c.commit().unwrap();
let ids: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command {
command: Command::Evaluate { request, .. },
..
} => Some(*request),
_ => None,
})
.collect();
let reply = |id, value| {
EventPayload::Map(vec![
("id", PayloadValue::Number(id as f64)),
(
"data",
PayloadValue::Str(format!(r#"{{"status":"ok","value":{value}}}"#)),
),
])
};
c.answer_web_evaluation(99, &reply(ids[0], 100));
assert!(a.borrow().value.is_none());
c.answer_web_evaluation(2, &reply(ids[1], 2));
c.answer_web_evaluation(2, &reply(ids[0], 1));
c.answer_web_evaluation(2, &reply(ids[0], 999));
assert_eq!(a.borrow_mut().value.take().unwrap().unwrap().value, 1);
assert_eq!(b.borrow_mut().value.take().unwrap().unwrap().value, 2);
drop((one, two));
}
#[test]
fn web_evaluation_disposal_and_timeout_release_requests() {
use crate::element::Answer;
let mut c = evaluation_core();
let (future, slot) = Answer::new();
c.start_web_evaluation(2, "new Promise(()=>{})".into(), T, slot.clone());
c.commit();
c.timeout_web_evaluation(1);
assert_eq!(
slot.borrow_mut().value.take().unwrap().unwrap_err().code(),
Some("ETIMEDOUT")
);
assert!(c.commit().unwrap().items.iter().any(|i| matches!(
i,
MountItem::Command {
command: Command::CancelEvaluate { request: 1 },
..
}
)));
drop(future);
let (future, slot) = Answer::new();
c.start_web_evaluation(2, "1".into(), T, slot.clone());
c.apply(Op::Release { id: 2 }).unwrap();
assert_eq!(
slot.borrow_mut().value.take().unwrap().unwrap_err().code(),
Some("ERR_NSH_WEBVIEW_ABORTED")
);
drop(future);
}
#[test]
fn web_evaluation_preserves_order_with_injection_and_navigation_commands() {
let mut c = evaluation_core();
apply(
&mut c,
vec![
Op::Evaluate {
id: 2,
call: 1,
script: "globalThis.x = 1; 1".into(),
timeout: T,
},
Op::Command {
id: 2,
command: Command::InjectJavaScript("globalThis.x = 2".into()),
},
Op::Evaluate {
id: 2,
call: 2,
script: "globalThis.x".into(),
timeout: T,
},
Op::Command {
id: 2,
command: Command::Reload,
},
],
);
let batch = c.commit().unwrap();
let commands: Vec<_> = batch
.items
.iter()
.filter_map(|item| match item {
MountItem::Command { id: 2, command } => Some(command),
_ => None,
})
.collect();
assert!(matches!(commands.as_slice(), [
Command::Evaluate { script: first, .. },
Command::InjectJavaScript(injected),
Command::Evaluate { script: second, .. },
Command::Reload,
] if first == "globalThis.x = 1; 1" && injected == "globalThis.x = 2" && second == "globalThis.x"));
}
#[test]
fn web_evaluation_requires_a_capable_host_even_with_a_mobile_environment() {
use crate::element::Answer;
let mut c = evaluation_core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::Ios,
..Default::default()
});
let (future, slot) = Answer::new();
c.start_web_evaluation(2, "1".into(), T, slot.clone());
assert_eq!(
slot.borrow_mut().value.take().unwrap().unwrap_err().code(),
Some("ERR_FEATURE_UNAVAILABLE_ON_PLATFORM")
);
assert!(
!c.commit()
.is_some_and(|batch| batch.items.iter().any(|item| matches!(
item,
MountItem::Command {
command: Command::Evaluate { .. },
..
}
)))
);
drop(future);
}
/// An `svg()` the platform draws as an image (the web) is sent with its text
/// color, inherited, for its `currentColor`; an image is not (#1466).
#[test]
fn svg_drawn_as_an_image_carries_its_text_color() {
let mut c = core();
view_with_classes(&mut c, 2, "text-red-500");
let image = |c: &mut Core<FakeEngine>, id: NodeId, svg: bool| {
let mut ops = vec![
Op::Create {
id,
tag: Tag::Image,
},
Op::SetProp {
id,
prop: Prop::Source(Some(ImageSource {
uri: "asset:/icon.svg".into(),
..Default::default()
})),
},
];
if svg {
ops.push(Op::SetProp {
id,
prop: Prop::Image(ImageProp::SvgCurrentColor(true)),
});
}
ops.push(Op::Insert {
parent: 2,
child: id,
before: None,
});
apply(c, ops);
};
image(&mut c, 3, true);
image(&mut c, 4, false);
let color_of = |batch: &MountBatch, id: NodeId| {
batch.items.iter().rev().find_map(|i| match i {
MountItem::Image { id: i, options, .. } if *i == id => Some(options.current_color),
_ => None,
})
};
let batch = c.commit().unwrap();
assert_eq!(color_of(&batch, 3), Some(Some(Color(0xfb2c_36ff))));
assert_eq!(color_of(&batch, 4), Some(None));
// The ancestor's color changes: the svg's is sent again.
c.apply(class_op(2, "text-blue-500")).unwrap();
let batch = c.commit().unwrap();
let blue = color_of(&batch, 3).flatten().unwrap();
assert_ne!(blue, Color(0xfb2c_36ff));
assert_eq!(color_of(&batch, 4), None);
}
/// #1614: a card whose header / `flex: 1` body / footer sit along `main`,
/// inside a parent along the other axis that doesn't stretch it. Returns
/// the card's and the body's frames.
type CardFrame = Option<Bounds<Points>>;
fn flex_one_card(vertical: bool, align: &str) -> (CardFrame, CardFrame, CardFrame) {
let (main, cross) = if vertical {
("height", "width")
} else {
("width", "height")
};
let min = if vertical { "minHeight" } else { "minWidth" };
let (dir, outer) = if vertical {
("column", "row")
} else {
("row", "column")
};
let mut c = core();
let fixed = |id| style_op(id, &[(main, StyleValue::Number(20.0))]);
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(
2,
&[
("flexDirection", StyleValue::Str(outer)),
("alignItems", StyleValue::Str(align)),
],
),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(
3,
&[
("flexDirection", StyleValue::Str(dir)),
("gap", StyleValue::Number(12.0)),
("padding", StyleValue::Number(16.0)),
(cross, StyleValue::Number(280.0)),
],
),
Op::Create {
id: 4,
tag: Tag::View,
},
fixed(4),
Op::Create {
id: 5,
tag: Tag::View,
},
style_op(
5,
&[
("flexDirection", StyleValue::Str(dir)),
("flex", StyleValue::Number(1.0)),
("gap", StyleValue::Number(4.0)),
(min, StyleValue::Str("auto")),
],
),
Op::Create {
id: 6,
tag: Tag::View,
},
fixed(6),
];
for i in 0..5 {
ops.push(Op::Create {
id: 10 + i,
tag: Tag::View,
});
ops.push(fixed(10 + i));
ops.push(Op::Insert {
parent: 5,
child: 10 + i,
before: None,
});
}
for child in [4, 5, 6] {
ops.push(Op::Insert {
parent: 3,
child,
before: None,
});
}
ops.push(Op::Insert {
parent: 2,
child: 3,
before: None,
});
ops.push(Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
});
apply(&mut c, ops);
let batch = c.commit().unwrap();
(
frame_of(&batch, 3),
frame_of(&batch, 5),
frame_of(&batch, 6),
)
}
#[test]
fn a_card_holds_its_flex_one_body() {
for vertical in [true, false] {
for align in ["flex-start", "center", "flex-end", "stretch"] {
// Stretched across a column, a row card is that column's width.
if !vertical && align == "stretch" {
continue;
}
let (card, body, footer) = flex_one_card(vertical, align);
let main = |f: CardFrame| {
f.map(|f| {
if vertical {
f.size.height.0
} else {
f.size.width.0
}
})
};
let start =
|f: CardFrame| f.map(|f| if vertical { f.origin.y.0 } else { f.origin.x.0 });
// 5×20 + 4×4 = 116; 16+20+12+116+12+20+16 = 212.
let what = format!("vertical {vertical}, {align}");
assert_eq!(main(body), Some(116.0), "{what}");
assert_eq!(main(card), Some(212.0), "{what}");
assert_eq!(start(footer), Some(176.0), "{what}");
}
}
}
/// A scroll view with more in sight than a turn's budget: what shows is
/// made at once, the overscan around it [`pace::PACE_VIEWS`] a turn.
#[test]
fn a_scroll_view_makes_its_overscan_over_turns() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// Rows of 1: 100 in sight, 100 in the overscan, the rest far.
for i in 0..400u32 {
ops.extend(child_view(10 + i, 2, 1.0, &[]));
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
let made = created_in(&batch);
for i in 0..100 {
assert!(made.contains(&(10 + i)), "row {i} shows: {made:?}");
}
let overscan = |made: &[NodeId]| made.iter().filter(|&&id| (110..210).contains(&id)).count();
assert_eq!(overscan(&made), super::pace::PACE_VIEWS);
assert!(c.has_paced_mounts());
// The rest of the overscan, a budget a turn, nearest first.
let mut turns = 0;
let mut seen = made.len();
while c.has_paced_mounts() {
let batch = c.commit().unwrap();
let made = created_in(&batch);
assert!(made.len() <= super::pace::PACE_VIEWS);
assert!(made.windows(2).all(|w| w[0] < w[1]), "{made:?}");
seen += made.len();
turns += 1;
assert!(turns < 10);
}
// Nothing far: the window is the same as without pacing.
assert_eq!(seen, 1 + 200);
assert_eq!(turns, 3);
}
/// A turn between two display frames ([`Core::hold_paced_mounts`]) leaves
/// the overscan waiting; the next frame's turn makes its slice (#2472).
#[test]
fn a_turn_between_frames_leaves_the_overscan_waiting() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
style_op(2, &[("height", StyleValue::Number(100.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
for i in 0..400u32 {
ops.extend(child_view(10 + i, 2, 1.0, &[]));
}
apply(&mut c, ops);
c.begin_mount_turn();
c.commit().unwrap();
assert!(c.has_paced_mounts());
c.begin_mount_turn();
c.hold_paced_mounts();
let made = c.commit().map(|b| created_in(&b)).unwrap_or_default();
assert!(made.is_empty(), "{made:?}");
assert!(c.has_paced_mounts());
c.begin_mount_turn();
let made = created_in(&c.commit().unwrap());
assert_eq!(made.len(), super::pace::PACE_VIEWS);
}
/// Cells bound with more views than a turn's budget: the cells in sight
/// get theirs at once, the overscan's wait and come over turns, nearest
/// first.
#[test]
fn list_cells_out_of_sight_make_their_views_over_turns() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(400.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(100.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(8),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
c.take_paced_list_binds(usize::MAX, &mut binds);
// Each cell a column of 40 views (2.5 pt each), as JS renders a row.
let mut cells = Vec::new();
let mut ops = Vec::new();
for (slot, index) in binds.iter().flat_map(|b| b.binds.iter().copied()) {
let cell = 100 + slot * 100;
ops.extend([
Op::Create {
id: cell,
tag: Tag::Cell,
},
Op::SetProp {
id: cell,
prop: Prop::Slot(CellSlot::Item(slot)),
},
Op::Insert {
parent: 2,
child: cell,
before: None,
},
]);
ops.push(style_op(cell, &[("height", StyleValue::Number(100.0))]));
for v in 1..=40 {
ops.extend(child_view(cell + v, cell, 2.5, &[]));
}
ops.push(Op::SetProp {
id: cell,
prop: Prop::CellIndex(index),
});
cells.push((index, cell));
}
assert_eq!(cells.len(), 8);
apply(&mut c, ops);
let batch = c.commit().unwrap();
let made = created_in(&batch);
let views_of = |made: &[NodeId], index: u32| {
let cell = cells.iter().find(|c| c.0 == index).unwrap().1;
made.iter()
.filter(|&&id| id > cell && id <= cell + 40)
.count()
};
// Rows 0..4 show (0..400): every view of theirs is in this batch.
for row in 0..4 {
assert_eq!(views_of(&made, row), 40, "row {row}");
}
let waiting: usize = (4..8).map(|row| 40 - views_of(&made, row)).sum();
assert!(waiting > 0 && c.has_paced_mounts());
let last = cells.iter().find(|c| c.0 == 7).unwrap().1 + 40;
let key = c.key(last).unwrap();
assert!(!c.nodes[key as usize].created);
// Later turns: a budget each, the nearer rows first.
let mut turns = 0;
let mut first_of = Vec::new();
while c.has_paced_mounts() {
let Some(batch) = c.commit() else { break };
let made = created_in(&batch);
assert!(made.len() <= super::pace::PACE_VIEWS, "{}", made.len());
first_of.push((4..8).find(|&row| views_of(&made, row) > 0));
turns += 1;
assert!(turns < 20);
}
assert!(!c.has_paced_mounts());
assert!(c.nodes[key as usize].created);
assert!(first_of.windows(2).all(|w| w[0] <= w[1]), "{first_of:?}");
}
/// The batch of #1500: a list whose rows are long replies, ~420 views
/// each. Prints the views and core time of every commit until the list
/// settles: `cargo test -p nsh-core --release --lib -- --ignored
/// big_rows_bench --nocapture`.
#[test]
#[ignore = "benchmark"]
fn big_rows_bench() {
const ROWS: u32 = 8;
const VIEWS: u32 = 420;
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("height", StyleValue::Number(480.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(240.0)),
},
Op::SetProp {
id: 2,
prop: Prop::Count(ROWS),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let mut binds = Vec::new();
c.take_list_binds(&mut binds);
c.take_paced_list_binds(usize::MAX, &mut binds);
let mut ops = Vec::new();
for (slot, index) in binds.iter().flat_map(|b| b.binds.iter().copied()) {
let cell = 10_000 + slot * 1000;
ops.extend([
Op::Create {
id: cell,
tag: Tag::Cell,
},
Op::SetProp {
id: cell,
prop: Prop::Slot(CellSlot::Item(slot)),
},
Op::Insert {
parent: 2,
child: cell,
before: None,
},
]);
// Paragraphs of lines: a reply's nested views.
for p in 0..VIEWS / 21 {
let para = cell + 1 + p * 21;
ops.extend(child_view(para, cell, 240.0, &[]));
for l in 1..=20 {
ops.extend(child_view(para + l, para, 12.0, &[]));
}
}
ops.push(Op::SetProp {
id: cell,
prop: Prop::CellIndex(index),
});
}
apply(&mut c, ops);
let mut total = 0;
for turn in 0.. {
let start = std::time::Instant::now();
let Some(batch) = c.commit() else { break };
let took = start.elapsed();
let made = created_in(&batch).len();
total += made;
eprintln!(
"turn {turn}: {made} views, {} items, core {took:?}",
batch.items.len()
);
if turn > 200 {
break;
}
}
eprintln!("total {total} views");
}
/// Texts whose first baseline is 0.95 of their largest font size below their
/// top, in lines 1.25 of it tall, 10 points a character wide: a font with
/// half-leading as CSS sets it.
struct BaselineEngine;
impl TextEngine for BaselineEngine {
/// Characters and the largest font size.
type Prepared = (usize, f32);
fn prepare(&self, text: &AttributedText) -> (usize, f32) {
let size = text
.spans
.iter()
.fold(0.0f32, |max, s| max.max(s.style.font_size.0));
(text.text.chars().count(), size)
}
fn measure(&self, &(chars, size): &(usize, f32), _: Option<Points>) -> Size<Points> {
size_pt(chars as f32 * 10.0, size * 1.25)
}
fn first_baseline(&self, &(_, size): &(usize, f32), _: Points) -> Option<Points> {
Some(Points(size * 0.95))
}
fn layout(&self, _: &(usize, f32), _: Size<Points>) -> TextLayout {
TextLayout(Arc::new(()))
}
}
/// A view inside a text that holds text of its own tells the engine how
/// far below its top the baseline of that text is (its padding, then the
/// text's first baseline), so the engine stands it on the line by that, as
/// CSS stands an `inline-flex` box; for the other alignments, and without
/// text in it, it stays a box placed by its edges, as an image.
#[test]
fn a_view_in_a_text_stands_on_the_line_by_its_own_first_baseline() {
let mut c = Core::new(BaselineEngine, size_pt(320.0, 480.0));
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let ops = vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "ab".into(),
},
// The chip: a padded row holding its label.
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("paddingTop", StyleValue::Number(3.0)),
("paddingBottom", StyleValue::Number(5.0)),
],
),
Op::Create {
id: 6,
tag: Tag::Text,
},
style_op(6, &[("fontSize", StyleValue::Number(16.0))]),
Op::CreateText {
id: 7,
text: "NVDA".into(),
},
// A box with no text: a swatch.
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(
8,
&[
("width", StyleValue::Number(10.0)),
("height", StyleValue::Number(10.0)),
],
),
insert(6, 7),
insert(4, 6),
insert(2, 3),
insert(2, 4),
insert(2, 8),
insert(ROOT_ID, 2),
];
for op in ops {
c.apply(op).unwrap();
}
c.commit().unwrap();
let baseline = |c: &mut Core<BaselineEngine>, i: usize| {
let layout = c.nodes[c.key(2).unwrap() as usize].layout.unwrap();
let cx = c.text_cx(layout);
let a = cx.text.attachments[i];
(cx.alignments.baseline(a.index), a.height)
};
// The label's baseline is 15.2 below its top (16 x 0.95), under the
// chip's padding; the label is 20 tall (16 x 1.25), the chip 28.
assert_eq!(
baseline(&mut c, 0),
(Some(Points(3.0 + 15.2)), Points(28.0))
);
// The swatch stands on its bottom edge.
assert_eq!(baseline(&mut c, 1), (None, Points(10.0)));
// A style replaces the one before it: the padding goes with each.
let set = |c: &mut Core<BaselineEngine>, align: &'static str| {
c.apply(style_op(
4,
&[
("paddingTop", StyleValue::Number(3.0)),
("paddingBottom", StyleValue::Number(5.0)),
("verticalAlign", StyleValue::Str(align)),
],
))
.unwrap();
c.commit().unwrap();
};
// Another alignment places the box by its edges.
set(&mut c, "middle");
assert_eq!(baseline(&mut c, 0).0, None);
set(&mut c, "baseline");
assert_eq!(baseline(&mut c, 0).0, Some(Points(3.0 + 15.2)));
}
/// Only text that takes part in a view's flow gives it its baseline: a
/// `display: none` text before the label has no box, so the label's
/// baseline stays the view's, and it is the shown text's once shown; an
/// absolutely positioned text, out of the flow, never gives it.
#[test]
fn a_hidden_or_positioned_text_gives_a_view_in_a_text_no_baseline() {
let mut c = Core::new(BaselineEngine, size_pt(320.0, 480.0));
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let text = |id: NodeId, size: f32, extra: &[(&'static str, StyleValue)]| {
let mut style = vec![("fontSize", StyleValue::Number(size))];
style.extend_from_slice(extra);
[Op::Create { id, tag: Tag::Text }, style_op(id, &style)]
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "ab".into(),
},
Op::Create {
id: 4,
tag: Tag::View,
},
style_op(
4,
&[
("paddingTop", StyleValue::Number(3.0)),
("paddingBottom", StyleValue::Number(5.0)),
],
),
];
// A text out of the flow first, then a hidden one, then the label.
ops.extend(text(10, 40.0, &[("position", StyleValue::Str("absolute"))]));
ops.extend(text(8, 80.0, &[("display", StyleValue::Str("none"))]));
ops.extend(text(6, 16.0, &[]));
ops.extend([
Op::CreateText {
id: 11,
text: "Away".into(),
},
Op::CreateText {
id: 9,
text: "Big".into(),
},
Op::CreateText {
id: 7,
text: "NVDA".into(),
},
insert(10, 11),
insert(8, 9),
insert(6, 7),
insert(4, 10),
insert(4, 8),
insert(4, 6),
insert(2, 3),
insert(2, 4),
insert(ROOT_ID, 2),
]);
for op in ops {
c.apply(op).unwrap();
}
c.commit().unwrap();
let baseline = |c: &mut Core<BaselineEngine>| {
let layout = c.nodes[c.key(2).unwrap() as usize].layout.unwrap();
let cx = c.text_cx(layout);
let a = cx.text.attachments[0];
cx.alignments.baseline(a.index)
};
let display = |c: &mut Core<BaselineEngine>, value: &'static str| {
c.apply(style_op(
8,
&[
("fontSize", StyleValue::Number(80.0)),
("display", StyleValue::Str(value)),
],
))
.unwrap();
c.commit().unwrap();
};
// The label's: 15.2 below its top (16 x 0.95), under the padding.
assert_eq!(baseline(&mut c), Some(Points(3.0 + 15.2)));
// Shown, the big text comes first: its baseline is 76 down.
display(&mut c, "flex");
assert_eq!(baseline(&mut c), Some(Points(3.0 + 76.0)));
// Hidden again, the label's is back.
display(&mut c, "none");
assert_eq!(baseline(&mut c), Some(Points(3.0 + 15.2)));
}
#[test]
fn a_row_aligned_by_baseline_lines_its_texts_up_by_their_first_baselines() {
let mut c = Core::new(BaselineEngine, size_pt(320.0, 480.0));
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
let text = |id, size: f32| {
[
Op::Create { id, tag: Tag::Text },
Op::SetStyle {
id,
style: style(&[("fontSize", StyleValue::Number(size))]),
patch: Default::default(),
},
]
};
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, "flex-row items-baseline"),
];
ops.extend(text(3, 30.0));
ops.extend(text(5, 10.0));
ops.extend([
Op::CreateText {
id: 4,
text: "Chat".into(),
},
Op::CreateText {
id: 6,
text: "2 people".into(),
},
insert(3, 4),
insert(5, 6),
insert(2, 3),
insert(2, 5),
insert(ROOT_ID, 2),
]);
for op in ops {
c.apply(op).unwrap();
}
let batch = c.commit().unwrap();
let top = |id| frame_of(&batch, id).map(|f| f.origin.y.0);
// The title's baseline is 28.5 below the row's top; the small text's,
// 9.5 below its own, so it starts 19 down. By their bottom edges (37.5
// and 12.5 tall) it would start 25 down, its baseline 6 under the title's.
assert_eq!(top(3), Some(0.0));
assert_eq!(top(5), Some(19.0));
// Aligned another way, the texts' layouts cached for baselines are not
// kept: by their bottom edges, then by baseline again.
c.apply(style_op(2, &[("alignItems", StyleValue::Str("flex-end"))]))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 5).map(|f| f.origin.y.0), Some(25.0));
c.apply(style_op(2, &[("alignItems", StyleValue::Str("baseline"))]))
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 5).map(|f| f.origin.y.0), Some(19.0));
}
#[test]
fn a_lowered_sibling_keeps_a_new_default_view_above_it() {
let mut c = core();
let z = |v: f32| style(&[("zIndex", StyleValue::Number(v))]);
let create = |id| Op::Create { id, tag: Tag::View };
let append = |child| Op::Insert {
parent: 1,
child,
before: None,
};
apply(
&mut c,
vec![create(2), create(3), create(4), append(2), append(3)],
);
let batch = c.commit().unwrap();
// A first fill: each goes on top, in order.
assert_eq!(insert_items(&batch), vec![(1, 2, None), (1, 3, None)]);
// In order, a new view goes below the next sibling.
apply(
&mut c,
vec![Op::Insert {
parent: 1,
child: 4,
before: Some(3),
}],
);
let batch = c.commit().unwrap();
assert_eq!(insert_items(&batch), vec![(1, 4, Some(3))]);
// 3 lowered below the others: 4, inserted again before it, now goes on
// top, not below 3.
apply(
&mut c,
vec![Op::SetStyle {
id: 3,
style: z(-1.0),
patch: StylePatch::default(),
}],
);
c.commit();
apply(
&mut c,
vec![
Op::Remove {
parent: 1,
child: 4,
},
Op::Insert {
parent: 1,
child: 4,
before: Some(3),
},
],
);
let batch = c.commit().unwrap();
assert_eq!(insert_items(&batch), vec![(1, 4, None)]);
}
/// A component's first fill and later changes of its children.
mod first_mount {
use std::{cell::Cell, time::Instant};
use super::*;
use crate::{element::Root, prelude::*};
thread_local! {
static COUNT: Cell<u32> = const { Cell::new(0) };
static STEP: Cell<f32> = const { Cell::new(1.0) };
static ITEMS: Cell<Option<Signal<Vec<u32>>>> = const { Cell::new(None) };
}
/// `COUNT` plain rows under one view, row `i` `2 + STEP * i` high.
#[component]
fn Rows() -> impl IntoElement {
let n = COUNT.with(Cell::get);
let step = STEP.with(Cell::get);
view().children((0..n).map(|i| view().h(px(2.0 + step * i as f32))))
}
/// The rows of `ITEMS`, by key.
#[component]
fn EachRows() -> impl IntoElement {
let items = signal(vec![0u32, 1, 2]);
ITEMS.with(|i| i.set(Some(items)));
view().child(each(
items,
|n| *n,
|item, _| view().h(px(2.0 + item.get_untracked() as f32)),
))
}
/// The frames of the children of the root view's first child's first
/// child (the rows' parent), in tree order: (y, height).
fn row_frames(c: &Core<FakeEngine>) -> Vec<(f32, f32)> {
let mut k = c.root;
while c.nodes[k as usize].children.len() == 1 {
k = c.nodes[k as usize].children[0];
}
c.nodes[k as usize]
.children
.iter()
.map(|&k| {
let f = c.nodes[k as usize].frame;
(f.origin.y.0, f.size.height.0)
})
.collect()
}
fn mount_rows(n: u32) -> (Core<FakeEngine>, MountBatch) {
COUNT.with(|c| c.set(n));
let mut c = core();
c.mount_root(&Root::of::<Rows>());
let batch = c.commit().unwrap();
(c, batch)
}
#[test]
fn a_first_fill_appends_the_children_in_order() {
let (c, batch) = mount_rows(4);
assert_eq!(
row_frames(&c),
vec![(0.0, 2.0), (2.0, 3.0), (5.0, 4.0), (9.0, 5.0)]
);
// Each row appended in order, none placed before another.
let inserts = insert_items(&batch);
let last: Vec<_> = inserts[inserts.len() - 4..].to_vec();
assert!(
last.iter().all(|(_, _, before)| before.is_none()),
"{inserts:?}"
);
assert!(last.windows(2).all(|w| w[0].1 < w[1].1), "{inserts:?}");
}
#[test]
fn rows_added_and_reordered_after_the_first_fill_keep_their_order() {
let mut c = core();
c.mount_root(&Root::of::<EachRows>());
c.commit();
assert_eq!(row_frames(&c), vec![(0.0, 2.0), (2.0, 3.0), (5.0, 4.0)]);
let items = ITEMS.with(Cell::get).unwrap();
{
let _entered = c.components.runtime.enter();
items.set(vec![3, 2, 0, 4, 1]);
}
c.commit();
let heights: Vec<f32> = row_frames(&c).iter().map(|r| r.1).collect();
assert_eq!(heights, vec![5.0, 4.0, 2.0, 6.0, 3.0]);
}
/// The first mount of `n` views under one view (T-0930's plain rows),
/// the median of 5: `cargo test --release -p nsh-core --lib
/// first_mount_bench -- --ignored --nocapture`.
#[test]
#[ignore]
fn first_mount_bench() {
// All 2 high, as T-0930's rows.
STEP.with(|s| s.set(0.0));
mount_rows(100);
for n in [100, 1_000, 8_600, 17_200] {
let mut runs: Vec<f64> = (0..5)
.map(|_| {
let t = Instant::now();
let made = mount_rows(n);
let ms = t.elapsed().as_secs_f64() * 1e3;
drop(made);
ms
})
.collect();
runs.sort_by(f64::total_cmp);
println!("first mount n={n}: {:.1} ms", runs[2]);
}
}
}
/// A list bound after the turn's budget of views: its cell waits
/// (`pace.rs`), and what the cell holds is placed with it, so the rows
/// that show are made in the turn the cell is, down to their leaves, not
/// behind every view that waits out of sight.
#[test]
fn a_list_bound_after_the_mount_budget_makes_the_rows_that_show_at_once() {
use crate::prelude::*;
#[component]
fn Repro() -> impl IntoElement {
scroll().horizontal().flex_1().child(
view()
.w(px(1000.0))
.h_full()
.child(
view()
.flex_row()
.h(px(26.0))
.flex_none()
.children((0..64).map(|_| view().w(px(10.0)).h(px(26.0)))),
)
.child(
virtual_list(3_usize, |_| {
view().h(px(26.0)).test_id("row").child(
view().child(
view().child(view().w(px(40.0)).h(px(20.0)).test_id("label")),
),
)
})
.estimated_item_size(px(26.0))
.flex_1(),
),
)
}
let mut c = core();
c.begin_mount_turn();
c.mount_root(&crate::element::Root::of::<Repro>());
// One turn: nothing that shows is left for a later one.
let items = c.commit().unwrap().items;
let frames = |test_id: &str| -> Vec<_> {
items
.iter()
.filter_map(|item| match item {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.map(|id| {
items.iter().rev().find_map(|item| match item {
MountItem::Frame { id: i, frame } if *i == id => Some(frame.size),
_ => None,
})
})
.collect()
};
assert_eq!(frames("row"), vec![Some(size_pt(1000.0, 26.0)); 3]);
assert_eq!(frames("label"), vec![Some(size_pt(40.0, 20.0)); 3]);
}
#[test]
fn a_list_bound_after_the_mount_budget_gives_its_row_a_frame() {
use crate::prelude::*;
#[component]
fn Repro() -> impl IntoElement {
scroll().horizontal().flex_1().child(
view()
.w(px(1000.0))
.h_full()
.child(
view()
.flex_row()
.h(px(26.0))
.flex_none()
.children((0..64).map(|_| view().w(px(10.0)).h(px(26.0)))),
)
.child(
virtual_list(1_usize, |_| {
view()
.h(px(26.0))
.test_id("row")
.child(view().w(px(40.0)).h(px(20.0)).test_id("label"))
})
.estimated_item_size(px(26.0))
.flex_1(),
),
)
}
let mut c = core();
c.begin_mount_turn();
c.mount_root(&crate::element::Root::of::<Repro>());
let mut items = c.commit().unwrap().items;
for _ in 0..50 {
if !c.has_paced_mounts() {
break;
}
c.begin_mount_turn();
if let Some(batch) = c.commit() {
items.extend(batch.items);
}
}
assert!(!c.has_paced_mounts());
let mut made = vec![ROOT_ID];
for item in &items {
match item {
MountItem::Create { id, .. } => made.push(*id),
MountItem::Frame { id, .. } => assert!(
made.contains(id),
"a paced list cell receives its native frame only after Create: {item:?}"
),
_ => {}
}
}
let row = items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some("row") => {
Some(*id)
}
_ => None,
})
.expect("row created");
let frame = items
.iter()
.rev()
.find_map(|item| match item {
MountItem::Frame { id, frame } if *id == row => Some(*frame),
_ => None,
})
.expect("row received a frame");
assert_eq!(frame.size, size_pt(1000.0, 26.0));
// The list's cell waited too: its cached logical frame must become
// its native frame after Create, not just the frames of its children.
let cell = items
.iter()
.find_map(|item| match item {
MountItem::Insert { parent, child, .. } if *child == row => Some(*parent),
_ => None,
})
.expect("the row is inserted into its cell");
let frame = items
.iter()
.rev()
.find_map(|item| match item {
MountItem::Frame { id, frame } if *id == cell => Some(*frame),
_ => None,
})
.expect("the cell received a frame after Create");
assert_eq!(frame, rect(0.0, 0.0, 1000.0, 26.0));
// What the row holds, made in a later turn still, is placed too.
let frame_of = |test_id: &str| {
let id = items
.iter()
.find_map(|item| match item {
MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
Some(*id)
}
_ => None,
})
.expect("view created");
items.iter().rev().find_map(|item| match item {
MountItem::Frame { id: i, frame } if *i == id => Some(*frame),
_ => None,
})
};
assert_eq!(
frame_of("label").expect("label frame").size,
size_pt(40.0, 20.0)
);
}
/// A part's classes (a page's `headerClass`, a list's `contentClass`) that
/// name design tokens follow the tokens, as a view's `class` does.
mod part_class_tokens {
use super::*;
use crate::{color::rgb, element::AdaptiveColor};
/// A stack with screen 3, its header's classes `names`.
fn page(c: &mut Core<FakeEngine>, names: &str) {
apply(
c,
vec![
Op::Create {
id: 2,
tag: Tag::Stack,
},
style_op(2, &[("flex", StyleValue::Number(1.0))]),
Op::Create {
id: 3,
tag: Tag::Screen,
},
Op::SetProp {
id: 3,
prop: Prop::HeaderClass(names.into()),
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
}
/// The header's background and title colors a batch sends for screen 3.
fn header(batch: Option<MountBatch>) -> Option<(Option<Color>, Option<Color>)> {
batch?.items.iter().find_map(|i| match i {
MountItem::ScreenConfig { id: 3, config } => {
Some((config.background_color, config.title_color))
}
_ => None,
})
}
/// The sample tokens with `primary` set.
fn with_primary(color: crate::element::AdaptiveColor) -> crate::element::Tokens {
let mut tokens = crate::element::tokens::sample();
tokens.set_color("primary", color);
tokens
}
#[test]
fn a_headers_token_classes_follow_the_tokens() {
let mut c = core();
page(&mut c, "bg-primary text-primary-foreground");
let foreground = Some(Color::from(token("primary-foreground").light));
assert_eq!(
header(c.commit()),
Some((Some(Color::from(token("primary").light)), foreground))
);
// The token's value changes: the header is sent with the new one.
c.set_tokens(with_primary(AdaptiveColor::rgb(0x00ff00, 0x004400)));
assert_eq!(
header(c.commit()),
Some((Some(Color::from(rgb(0x00ff00))), foreground))
);
// It stays the token's in the other appearance.
c.set_class_environment(crate::tailwind::ClassEnvironment {
dark: true,
..Default::default()
});
assert_eq!(
header(c.commit()).map(|h| h.0),
Some(Some(Color::from(rgb(0x004400))))
);
// The same values again send nothing.
c.set_tokens(with_primary(AdaptiveColor::rgb(0x00ff00, 0x004400)));
assert_eq!(header(c.commit()), None);
}
#[test]
fn a_header_without_token_classes_is_left_alone() {
let mut c = core();
page(&mut c, "bg-[#112233]");
assert_eq!(
header(c.commit()).map(|h| h.0),
Some(Some(Color(0x1122_33ff)))
);
c.set_tokens(with_primary(rgb(0x00ff00).into()));
assert_eq!(header(c.commit()), None);
}
#[test]
fn a_lists_content_token_classes_follow_the_tokens() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
Op::SetProp {
id: 2,
prop: Prop::ListContentClass("p-(--radius) gap-2".into()),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let padding = |c: &Core<FakeEngine>| {
let key = c.key(2).unwrap();
let content = c.nodes[key as usize].list.as_ref().unwrap().content;
(content.padding.top, content.row_gap)
};
assert_eq!(padding(&c), (px(12.0), px(8.0)));
let mut tokens = crate::element::tokens::sample();
tokens.set_number("radius", 20.0);
c.set_tokens(tokens);
c.commit();
assert_eq!(padding(&c), (px(20.0), px(8.0)));
}
}
/// A style set on a view whose layout style stays what it was (a change
/// of colors: a token, the appearance, a state) lays nothing out again;
/// one that changes the layout style still does.
mod layout_kept_by_restyle {
use super::*;
/// View 2 with `classes` holding the text 3 (`hello`, classes
/// `text_classes`), committed.
fn card(classes: &str, text_classes: &str) -> Core<FakeEngine> {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, classes),
Op::Create {
id: 3,
tag: Tag::Text,
},
class_op(3, text_classes),
Op::CreateText {
id: 4,
text: "hello".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit().unwrap();
assert!(!c.needs_layout);
c
}
fn frames(batch: &MountBatch) -> Vec<NodeId> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Frame { id, .. } => Some(*id),
_ => None,
})
.collect()
}
#[test]
fn a_change_of_colors_asks_for_no_layout() {
let mut c = card("w-20 p-2 bg-red-500", "text-black");
apply(&mut c, vec![class_op(2, "w-20 p-2 bg-blue-500")]);
assert!(!c.needs_layout);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color::from(crate::element::palette::BLUE.shade(500))
);
assert_eq!(frames(&batch), [] as [NodeId; 0]);
}
#[test]
fn a_text_color_is_drawn_again_without_a_layout() {
let mut c = card("w-20 p-2", "text-black");
apply(&mut c, vec![class_op(3, "text-red-500")]);
assert!(!c.needs_layout);
let batch = c.commit().unwrap();
let color = batch.items.iter().find_map(|i| match i {
MountItem::Text { id: 3, text, .. } => Some(text.spans[0].style.color),
_ => None,
});
assert_eq!(
color,
Some(Color::from(crate::element::palette::RED.shade(500)))
);
assert_eq!(frames(&batch), [] as [NodeId; 0]);
}
#[test]
fn an_inline_color_asks_for_no_layout() {
let mut c = card("w-20 p-2", "text-black");
apply(
&mut c,
vec![style_op(
2,
&[("backgroundColor", StyleValue::Str("#0000ff"))],
)],
);
assert!(!c.needs_layout);
let batch = c.commit().unwrap();
assert_eq!(
view_style_of(&batch, 2).unwrap().background_color,
Color(0x0000_ffff)
);
assert_eq!(frames(&batch), [] as [NodeId; 0]);
}
#[test]
fn a_change_of_the_layout_style_still_lays_out() {
let mut c = card("w-20 p-2 bg-red-500", "text-black");
apply(&mut c, vec![class_op(2, "w-40 p-2 bg-red-500")]);
assert!(c.needs_layout);
let batch = c.commit().unwrap();
let frame = frame_of(&batch, 2).expect("a new frame");
assert_eq!(frame.size.width.0, 160.0);
// And back, with another color in the same change.
apply(&mut c, vec![class_op(2, "w-20 p-4 bg-blue-500")]);
assert!(c.needs_layout);
let batch = c.commit().unwrap();
assert_eq!(frame_of(&batch, 2).unwrap().size.width.0, 80.0);
// The padding moved the text.
assert!(frames(&batch).contains(&3));
}
/// 300 cards, each a text and a row of three boxes, every box given
/// another background: the restyle and its commit.
/// `cargo test --release -p nsh-core bench_restyle_colors -- --ignored --nocapture`
#[test]
#[ignore]
fn bench_restyle_colors() {
const CARDS: u32 = 300;
let mut c = core();
let mut ops = Vec::new();
let mut boxes = Vec::new();
for card in 0..CARDS {
let id = 10 + card * 10;
let (text, raw, row) = (id + 1, id + 2, id + 3);
ops.extend([
Op::Create { id, tag: Tag::View },
class_op(
id,
"p-4 gap-2 rounded-lg border border-neutral-200 bg-white",
),
Op::Create {
id: text,
tag: Tag::Text,
},
class_op(text, "text-base font-semibold text-neutral-950"),
Op::CreateText {
id: raw,
text: format!("Card {card}"),
},
Op::Insert {
parent: text,
child: raw,
before: None,
},
Op::Insert {
parent: id,
child: text,
before: None,
},
Op::Create {
id: row,
tag: Tag::View,
},
class_op(row, "flex-row gap-2"),
]);
for k in 0..3 {
let b = id + 4 + k;
boxes.push(b);
ops.extend([
Op::Create {
id: b,
tag: Tag::View,
},
class_op(b, "px-3 py-2 rounded-md bg-neutral-100"),
Op::Insert {
parent: row,
child: b,
before: None,
},
]);
}
ops.extend([
Op::Insert {
parent: id,
child: row,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
c.commit().unwrap();
let mut times = Vec::new();
let mut frames_sent = 0;
for round in 0..400 {
let class = if round % 2 == 0 {
"px-3 py-2 rounded-md bg-blue-600"
} else {
"px-3 py-2 rounded-md bg-neutral-100"
};
let ops: Vec<Op> = boxes.iter().map(|&b| class_op(b, class)).collect();
let start = std::time::Instant::now();
apply(&mut c, ops);
let batch = c.commit().unwrap();
times.push(start.elapsed());
frames_sent += frames(&batch).len();
assert!(view_style_of(&batch, boxes[0]).is_some());
}
times.sort();
println!(
"{} boxes given another background: {:.0} us (median {:.0} us), {frames_sent} frames sent",
boxes.len(),
times[0].as_secs_f64() * 1e6,
times[times.len() / 2].as_secs_f64() * 1e6,
);
}
}
/// Web view downloads: the core's state machine, the files it stages and
/// publishes (the file work is a real thread here, never an inline stub),
/// and the platform transport.
mod download_decisions {
use std::{
cell::RefCell,
future::Future,
path::{Path, PathBuf},
task::{Context, Poll, Waker},
time::{Duration, Instant},
};
use super::*;
use crate::{
prelude::*,
webview::{
CancelReason, DownloadDestination, DownloadEnd, DownloadOffer, DownloadOutcome,
DownloadProgress, WebDownload, WebDownloadPending, WebDownloadSource, WebDownloadState,
download_end, download_offer, download_progress, reply,
},
};
thread_local! {
static PENDING: RefCell<Option<WebDownloadPending>> = const { RefCell::new(None) };
static DOWNLOADS: RefCell<Vec<WebDownload>> = const { RefCell::new(Vec::new()) };
}
fn reset() {
PENDING.with(|slot| *slot.borrow_mut() = None);
DOWNLOADS.with(|list| list.borrow_mut().clear());
}
fn pending() -> Option<WebDownloadPending> {
PENDING.with(|slot| slot.borrow().clone())
}
fn downloads() -> Vec<WebDownload> {
DOWNLOADS.with(|list| list.borrow().clone())
}
/// The download events the core queued for JS: `(node, state, reason)`.
fn queued_downloads(c: &mut Core<FakeEngine>) -> Vec<(NodeId, String, Option<String>)> {
let mut events = Vec::new();
c.take_events(&mut events);
events
.into_iter()
.filter_map(|event| match event {
crate::element::JsEvent::Event(
node,
EventKind::Download,
EventPayload::Map(entries),
) => {
let field = |name: &str| {
entries.iter().find_map(|(k, v)| match v {
crate::PayloadValue::Str(value) if *k == name => Some(value.clone()),
_ => None,
})
};
Some((node, field("state").unwrap_or_default(), field("reason")))
}
_ => None,
})
.collect()
}
/// A web view JS made (no component expands it), listening to both
/// download events.
fn js_web_view(c: &mut Core<FakeEngine>) -> NodeId {
apply(
c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
Op::Listen {
id: 2,
event: EventKind::DownloadPending,
enabled: true,
},
Op::Listen {
id: 2,
event: EventKind::Download,
enabled: true,
},
],
);
c.commit().expect("the web view");
2
}
/// Node `id` listens (`enabled`) or stops listening to a download event.
fn listen(c: &mut Core<FakeEngine>, id: NodeId, event: EventKind, enabled: bool) {
apply(c, vec![Op::Listen { id, event, enabled }]);
}
#[component]
fn ManualDownloads() -> impl IntoElement {
web_view("https://example.com/")
.on_download_pending(|pending: &WebDownloadPending| {
PENDING.with(|slot| *slot.borrow_mut() = Some(pending.clone()));
})
.on_download(|download: &WebDownload| {
DOWNLOADS.with(|list| list.borrow_mut().push(download.clone()));
})
.into_element()
}
#[component]
fn AutomaticDownloads() -> impl IntoElement {
web_view("https://example.com/")
.on_download(|download: &WebDownload| {
DOWNLOADS.with(|list| list.borrow_mut().push(download.clone()));
})
.into_element()
}
#[component]
fn ToggleDownloads() -> impl IntoElement {
let shown = signal(true);
view()
.child(dynamic(move || {
if shown.get() {
web_view("https://example.com/")
.on_download_pending(|pending: &WebDownloadPending| {
PENDING.with(|slot| *slot.borrow_mut() = Some(pending.clone()));
})
.on_download(|download: &WebDownload| {
DOWNLOADS.with(|list| list.borrow_mut().push(download.clone()));
})
.into_element()
} else {
view().into_element()
}
}))
.child(
view()
.w(px(5.0))
.h(px(5.0))
.on_press(move |_: &()| shown.set(false)),
)
.into_element()
}
fn web_node(batch: &MountBatch) -> NodeId {
batch
.items
.iter()
.find_map(|i| match i {
MountItem::Create { id, kind } if *kind == ViewKind::WebView => Some(*id),
_ => None,
})
.expect("a web view")
}
fn press_nodes(batch: &MountBatch) -> Vec<NodeId> {
batch
.items
.iter()
.filter_map(|i| match i {
MountItem::Events { id, events } if events.contains(EventKind::Press) => Some(*id),
_ => None,
})
.collect()
}
fn requests(items: &[MountItem]) -> Vec<(NodeId, u64, crate::webview::WebViewOperation)> {
items
.iter()
.filter_map(|i| match i {
MountItem::Command {
id,
command: Command::WebViewRequest(request),
} => Some((*id, request.id, request.operation.clone())),
_ => None,
})
.collect()
}
fn offer(id: &str, filename: &str, bytes: Option<u64>) -> EventPayload {
download_offer(&DownloadOffer {
id: id.into(),
url: format!("https://example.com/{filename}"),
filename: filename.into(),
mime_type: Some("application/octet-stream".into()),
bytes,
method: Some("GET".into()),
source: WebDownloadSource::Transfer,
})
}
fn end(id: &str, outcome: DownloadOutcome) -> EventPayload {
download_end(&DownloadEnd {
id: id.into(),
outcome,
})
}
fn reply_ok(c: &mut Core<FakeEngine>, web: NodeId, request: u64) {
assert!(c.component_event(
web,
EventKind::WebViewReply,
&reply(request, Ok(serde_json::Value::Null))
));
}
/// The engine's loop: commit (and poll the downloads' file work), then
/// hand the core's events to the listeners.
fn pump(c: &mut Core<FakeEngine>) -> Option<MountBatch> {
let batch = c.commit();
let mut events = Vec::new();
c.take_events(&mut events);
for event in events {
if let crate::element::JsEvent::Event(id, kind, payload) = event {
c.component_event(id, kind, &payload);
}
}
batch
}
fn until<T>(what: &str, mut step: impl FnMut() -> Option<T>) -> T {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
if let Some(value) = step() {
return value;
}
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(2));
}
}
/// Pumps until the core sent a platform request; returns it.
fn wait_request(c: &mut Core<FakeEngine>) -> (NodeId, u64, crate::webview::WebViewOperation) {
until("a platform request", || {
pump(c).and_then(|batch| requests(&batch.items).into_iter().next())
})
}
/// Pumps until `count` lifecycle events were reported.
fn wait_downloads(c: &mut Core<FakeEngine>, count: usize) -> Vec<WebDownload> {
until("the download's events", || {
pump(c);
let events = downloads();
(events.len() >= count).then_some(events)
})
}
fn settled<T>(answer: impl Future<Output = T>) -> Option<T> {
let mut answer = std::pin::pin!(answer);
let waker = Waker::noop();
let mut cx = Context::from_waker(waker);
match answer.as_mut().poll(&mut cx) {
Poll::Ready(value) => Some(value),
Poll::Pending => None,
}
}
fn scratch(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("nsh-core-download-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn staging_in(parent: &Path) -> Option<PathBuf> {
std::fs::read_dir(parent)
.ok()?
.filter_map(Result::ok)
.find(|entry| {
entry.file_type().is_ok_and(|t| t.is_dir())
&& entry
.file_name()
.to_string_lossy()
.starts_with(".nsh-download-")
})
.map(|entry| entry.path())
}
#[test]
fn a_manual_download_is_staged_on_accept_and_published_on_finish() {
reset();
let dir = scratch("manual");
let destination = dir.join("out.bin");
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d1", "out.bin", Some(3))
));
pump(&mut c);
let held = pending().expect("the pending download");
assert_eq!(held.source, WebDownloadSource::Transfer);
assert_eq!(held.bytes, Some(3));
assert_eq!(held.method.as_deref(), Some("GET"));
assert!(!destination.exists());
assert!(staging_in(&dir).is_none());
// Accepting stages a private directory whose leaf does not exist.
// The destination is not accepted until the platform took it.
let answer = held.accept(destination.clone());
c.apply_actions();
let (_, request, operation) = wait_request(&mut c);
let crate::webview::WebViewOperation::StartDownload { id, staging } = operation else {
panic!("StartDownload: {operation:?}");
};
assert_eq!(id, "d1");
assert!(!staging.exists(), "the staging leaf must not exist");
assert!(staging.parent().is_some_and(Path::exists));
assert!(!destination.exists());
assert_eq!(settled(answer), None, "accept waits for the platform");
// Start accepted: the destination is accepted and the platform is
// writing.
reply_ok(&mut c, web, request);
let events = wait_downloads(&mut c, 1);
assert_eq!(events[0].state, WebDownloadState::Started);
assert_eq!(events[0].source, WebDownloadSource::Transfer);
// The transfer finishes: the file is published atomically.
std::fs::write(&staging, b"abc").unwrap();
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end("d1", DownloadOutcome::Finished { bytes: 3 })
));
let events = wait_downloads(&mut c, 2);
assert_eq!(events[1].state, WebDownloadState::Finished);
assert_eq!(std::fs::read(&destination).unwrap(), b"abc");
assert!(staging_in(&dir).is_none(), "the staging directory stays");
// A late end or cancel never touches the published file.
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end(
"d1",
DownloadOutcome::Failed {
code: None,
message: "late".into()
}
)
));
let late = held.cancel();
c.apply_actions();
pump(&mut c);
assert_eq!(
settled(late),
Some(Err(crate::element::codes::DOWNLOAD_STATE.into()))
);
assert_eq!(std::fs::read(&destination).unwrap(), b"abc");
assert_eq!(downloads().len(), 2);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn cancel_waits_for_the_stop_and_the_cleanup() {
reset();
let dir = scratch("cancel-pending");
let destination = dir.join("out.bin");
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(web, EventKind::DownloadOffer, &offer("d2", "out.bin", None)));
pump(&mut c);
let held = pending().expect("the pending download");
let mut cancel = held.cancel();
c.apply_actions();
let (_, request, operation) = wait_request(&mut c);
assert!(matches!(
operation,
crate::webview::WebViewOperation::CancelDownload { ref id } if id == "d2"
));
// Not answered, and not reported, until the platform stopped.
assert_eq!(settled(&mut cancel), None);
assert!(downloads().is_empty());
reply_ok(&mut c, web, request);
let events = wait_downloads(&mut c, 1);
assert_eq!(events[0].state, WebDownloadState::Cancelled);
assert_eq!(events[0].reason, Some(CancelReason::App));
assert_eq!(settled(cancel), Some(Ok(())));
assert!(!destination.exists());
assert!(staging_in(&dir).is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_unanswered_offer_times_out_after_the_stop() {
use std::time::SystemTime;
reset();
let dir = scratch("timeout");
let destination = dir.join("out.bin");
let clock = crate::time::Clock::manual(SystemTime::UNIX_EPOCH);
let _clock = clock.enter();
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(web, EventKind::DownloadOffer, &offer("d3", "out.bin", None)));
pump(&mut c);
clock.advance_to(
crate::time::now() + crate::webview::downloads::OFFER_TIMEOUT + Duration::from_secs(1),
);
let (_, request, operation) = wait_request(&mut c);
assert!(matches!(
operation,
crate::webview::WebViewOperation::CancelDownload { ref id } if id == "d3"
));
assert!(downloads().is_empty());
reply_ok(&mut c, web, request);
let events = wait_downloads(&mut c, 1);
assert_eq!(events[0].state, WebDownloadState::Cancelled);
assert_eq!(events[0].reason, Some(CancelReason::Timeout));
assert!(!destination.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn publish_refuses_a_destination_that_appeared_and_keeps_it() {
reset();
let dir = scratch("appeared");
let destination = dir.join("out.bin");
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d4", "out.bin", Some(3))
));
pump(&mut c);
let held = pending().expect("the pending download");
let answer = held.accept(destination.clone());
c.apply_actions();
let (_, request, operation) = wait_request(&mut c);
assert!(matches!(
operation,
crate::webview::WebViewOperation::StartDownload { .. }
));
reply_ok(&mut c, web, request);
let _ = wait_downloads(&mut c, 1);
assert_eq!(settled(answer), Some(Ok(())));
let staging = staging_in(&dir).expect("the staging directory");
let staging = staging.join("out.bin");
std::fs::write(&destination, b"the app's").unwrap();
std::fs::write(&staging, b"abc").unwrap();
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end("d4", DownloadOutcome::Finished { bytes: 3 })
));
let events = wait_downloads(&mut c, 2);
assert_eq!(std::fs::read(&destination).unwrap(), b"the app's");
assert!(matches!(events[1].state, WebDownloadState::Failed));
assert_eq!(
events[1].code.as_deref(),
Some(crate::element::codes::DOWNLOAD_DESTINATION)
);
assert!(staging_in(&dir).is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn overwrite_replaces_the_destination_and_a_size_mismatch_fails() {
reset();
let dir = scratch("overwrite");
let destination = dir.join("out.bin");
std::fs::write(&destination, b"old").unwrap();
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d5", "out.bin", Some(3))
));
pump(&mut c);
let held = pending().expect("the pending download");
let answer = held.accept(DownloadDestination::new(destination.clone()).overwrite(true));
c.apply_actions();
let (_, request, _) = wait_request(&mut c);
reply_ok(&mut c, web, request);
let _ = wait_downloads(&mut c, 1);
assert_eq!(settled(answer), Some(Ok(())));
let staging = staging_in(&dir).expect("staging").join("out.bin");
std::fs::write(&staging, b"new").unwrap();
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end("d5", DownloadOutcome::Finished { bytes: 3 })
));
let events = wait_downloads(&mut c, 2);
assert_eq!(events[1].state, WebDownloadState::Finished);
assert_eq!(std::fs::read(&destination).unwrap(), b"new");
// Declared size not met: failed, destination untouched, staging
// cleaned.
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d6", "out.bin", Some(9))
));
pump(&mut c);
let held = pending().expect("the second pending download");
drop(held.accept(DownloadDestination::new(destination.clone()).overwrite(true)));
c.apply_actions();
let (_, request, _) = wait_request(&mut c);
reply_ok(&mut c, web, request);
let _ = wait_downloads(&mut c, 3);
let staging = staging_in(&dir).expect("staging").join("out.bin");
std::fs::write(&staging, b"new").unwrap();
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end("d6", DownloadOutcome::Finished { bytes: 3 })
));
let events = wait_downloads(&mut c, 4);
assert_eq!(events[3].state, WebDownloadState::Failed);
assert_eq!(
events[3].code.as_deref(),
Some(crate::element::codes::DOWNLOAD_SIZE)
);
assert_eq!(std::fs::read(&destination).unwrap(), b"new");
assert!(staging_in(&dir).is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn automatic_downloads_land_in_the_apps_data_directory() {
reset();
let dir = scratch("automatic");
let mut c = core();
c.set_data_dir(Some(dir.clone()));
c.mount_root(&crate::element::Root::new::<AutomaticDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d7", "a.bin", Some(2))
));
let (_, request, operation) = wait_request(&mut c);
let crate::webview::WebViewOperation::StartDownload { staging, .. } = operation else {
panic!("StartDownload: {operation:?}");
};
reply_ok(&mut c, web, request);
let events = wait_downloads(&mut c, 1);
assert_eq!(events[0].state, WebDownloadState::Started);
std::fs::write(&staging, b"hi").unwrap();
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end("d7", DownloadOutcome::Finished { bytes: 2 })
));
let events = wait_downloads(&mut c, 2);
assert_eq!(events[1].state, WebDownloadState::Finished);
let expected = dir.join("downloads").join("d7").join("a.bin");
assert_eq!(std::fs::read(&expected).unwrap(), b"hi");
let _ = std::fs::remove_dir_all(&dir);
}
/// An app whose web views may show `hosts` (`capabilities.webview`).
fn webview_hosts(hosts: &[&str]) -> Arc<crate::access::Access> {
Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "webview": { "hosts": hosts } }),
)
.unwrap(),
granted: None,
})
}
/// An offer of a download whose response came from `url`.
fn offer_at(id: &str, url: &str) -> EventPayload {
download_offer(&DownloadOffer {
id: id.into(),
url: url.into(),
filename: "secret".into(),
mime_type: Some("application/octet-stream".into()),
bytes: Some(6),
method: Some("GET".into()),
source: WebDownloadSource::Transfer,
})
}
/// The offer's URL is the response's, after the platform followed its
/// redirects: a download that ended up on a host `webview.hosts` does
/// not allow is never offered to the app, its transfer is released and
/// the app hears it failed with `ERR_ACCESS_DENIED`. One on a granted
/// host is offered as before.
#[test]
fn a_held_download_from_a_host_the_grant_does_not_allow_is_refused() {
reset();
let dir = scratch("refused-manual");
let mut c = core();
c.set_access(webview_hosts(&["example.com"]));
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
let secret = "http://127.0.0.1:18732/secret";
assert!(c.component_event(web, EventKind::DownloadOffer, &offer_at("r1", secret)));
let (node, request, operation) = wait_request(&mut c);
assert_eq!(node, web);
assert!(
matches!(
operation,
crate::webview::WebViewOperation::CancelDownload { ref id } if id == "r1"
),
"the refused transfer is released: {operation:?}"
);
assert!(pending().is_none(), "a refused download is never offered");
let events = downloads();
assert_eq!(events.len(), 1);
assert_eq!(events[0].state, WebDownloadState::Failed);
assert_eq!(events[0].url, secret);
assert_eq!(
events[0].code.as_deref(),
Some(crate::element::codes::ACCESS_DENIED)
);
reply_ok(&mut c, web, request);
pump(&mut c);
assert_eq!(downloads().len(), 1, "the stop reports nothing more");
assert!(staging_in(&dir).is_none());
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer_at("a1", "https://example.com/report.bin")
));
pump(&mut c);
let held = pending().expect("a download from a granted host is offered");
assert_eq!(held.url, "https://example.com/report.bin");
let _ = std::fs::remove_dir_all(&dir);
}
/// An automatic download takes the same grant: a refused one stages
/// nothing in the app's data directory.
#[test]
fn an_automatic_download_from_a_host_the_grant_does_not_allow_stages_nothing() {
reset();
let dir = scratch("refused-automatic");
let mut c = core();
c.set_access(webview_hosts(&["example.com"]));
c.set_data_dir(Some(dir.clone()));
c.mount_root(&crate::element::Root::new::<AutomaticDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
let secret = "http://127.0.0.1:18732/secret";
assert!(c.component_event(web, EventKind::DownloadOffer, &offer_at("r2", secret)));
let (_, request, operation) = wait_request(&mut c);
assert!(
matches!(
operation,
crate::webview::WebViewOperation::CancelDownload { ref id } if id == "r2"
),
"the refused transfer is released, never started: {operation:?}"
);
reply_ok(&mut c, web, request);
let events = wait_downloads(&mut c, 1);
assert_eq!(events[0].state, WebDownloadState::Failed);
assert_eq!(
events[0].code.as_deref(),
Some(crate::element::codes::ACCESS_DENIED)
);
assert!(!dir.join("downloads").join("r2").exists());
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer_at("a2", "https://example.com/report.bin")
));
let (_, _, operation) = wait_request(&mut c);
assert!(
matches!(
operation,
crate::webview::WebViewOperation::StartDownload { ref id, .. } if id == "a2"
),
"a download from a granted host starts: {operation:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// A download of the page's own content (`data:`, `blob:`, an opaque
/// one too) reaches no host: `webview.hosts` leaves it offered, as
/// before.
#[test]
fn a_download_of_the_pages_own_content_takes_no_host_grant() {
reset();
let dir = scratch("page-content");
let mut c = core();
c.set_access(webview_hosts(&["example.com"]));
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
for (id, url) in [
("d1", "data:text/plain;base64,aGk="),
("d2", "blob:null/0b3c9a6e-58a1-4b8e-9d1c-3f0e8e4f2a11"),
("d3", "BLOB:https://elsewhere.test/1f2e"),
] {
assert!(c.component_event(web, EventKind::DownloadOffer, &offer_at(id, url)));
pump(&mut c);
let held = pending().unwrap_or_else(|| panic!("{url} is offered"));
assert_eq!(held.url, url);
assert!(
!downloads()
.iter()
.any(|e| e.state == WebDownloadState::Failed),
"{url} is not refused"
);
reset();
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn teardown_cancels_and_cleans_only_after_the_stop_is_acknowledged() {
reset();
let dir = scratch("teardown");
let destination = dir.join("out.bin");
let mut c = core();
c.mount_root(&crate::element::Root::new::<ToggleDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
let press = press_nodes(&batch)[0];
assert!(c.component_event(web, EventKind::DownloadOffer, &offer("d8", "out.bin", None)));
pump(&mut c);
let held = pending().expect("the pending download");
drop(held.accept(destination.clone()));
c.apply_actions();
let (_, request, _) = wait_request(&mut c);
reply_ok(&mut c, web, request);
let _ = wait_downloads(&mut c, 1);
let staging = staging_in(&dir).expect("staging").join("out.bin");
std::fs::write(&staging, b"abc").unwrap();
// The view goes: cancelled with teardown, and the platform is told
// to stop; the staging file stays until it says its writer
// stopped.
assert!(c.component_event(press, EventKind::Press, &EventPayload::None));
let (_, request, operation) = wait_request(&mut c);
assert!(matches!(
operation,
crate::webview::WebViewOperation::CancelDownload { ref id } if id == "d8"
));
// The unified contract: no terminal event before the stop ack and
// the cleanup. The listener went with the node, so the files and
// the command are what can be observed.
assert_eq!(downloads().len(), 1);
assert!(staging.exists(), "the writer may still hold it");
reply_ok(&mut c, web, request);
until("the staging cleanup", || {
pump(&mut c);
(!staging.exists()).then_some(())
});
assert!(!destination.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn duplicates_foreign_replies_and_unbound_decisions_change_nothing() {
reset();
let dir = scratch("duplicates");
let destination = dir.join("out.bin");
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(web, EventKind::DownloadOffer, &offer("d9", "out.bin", None)));
pump(&mut c);
let held = pending().expect("the pending download");
assert_eq!(
settled(WebDownloadPending::default().cancel()),
Some(Err(crate::webview::downloads::UNBOUND.into()))
);
let mut first = held.accept(destination.clone());
let second = held.accept(destination.clone());
c.apply_actions();
let (_, request, _) = wait_request(&mut c);
assert_eq!(
settled(second),
Some(Err(crate::element::codes::DOWNLOAD_STATE.into()))
);
assert_eq!(settled(&mut first), None);
// A reply from another node must not consume the request.
assert!(c.component_event(
web.wrapping_add(2),
EventKind::WebViewReply,
&reply(request, Ok(serde_json::Value::Null))
));
assert_eq!(settled(&mut first), None);
reply_ok(&mut c, web, request);
let _ = wait_downloads(&mut c, 1);
assert_eq!(settled(first), Some(Ok(())));
// Progress is accepted and surfaces nothing.
assert!(c.component_event(
web,
EventKind::DownloadProgress,
&download_progress(&DownloadProgress {
id: "d9".into(),
received: 10
})
));
assert_eq!(downloads().len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_queued_end_then_core_drop_cleans_the_staging_only() {
reset();
let dir = scratch("shutdown");
let destination = dir.join("out.bin");
std::fs::write(&destination, b"keep").unwrap();
let sink = crate::webview::downloads::DownloadCleanup::new();
let mut c = core();
c.set_download_cleanup(sink.clone());
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d10", "out.bin", None)
));
pump(&mut c);
let held = pending().expect("the pending download");
drop(held.accept(DownloadDestination::new(destination.clone()).overwrite(true)));
c.apply_actions();
let (_, request, _) = wait_request(&mut c);
reply_ok(&mut c, web, request);
let _ = wait_downloads(&mut c, 1);
let staging = staging_in(&dir).expect("the staging directory");
std::fs::write(staging.join("out.bin"), b"partial").unwrap();
// The platform's End is queued (and recorded by the sink at send
// time) but the engine stops before consuming it: dropping the
// whole core must clean the stopped staging, not just a failed
// send.
sink.dispatch(
web,
EventKind::DownloadEnd,
&end("d10", DownloadOutcome::Finished { bytes: 3 }),
);
assert!(staging.exists(), "a live core may still publish");
drop(c);
until("the sink's cleanup", || (!staging.exists()).then_some(()));
assert_eq!(std::fs::read(&destination).unwrap(), b"keep");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_late_stop_after_failed_cancel_and_core_drop_cleans_staging() {
reset();
let dir = scratch("failed-cancel-shutdown");
let destination = dir.join("out.bin");
std::fs::write(&destination, b"keep").unwrap();
let sink = crate::webview::downloads::DownloadCleanup::new();
let mut c = core();
c.set_download_cleanup(sink.clone());
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let web = web_node(&c.commit().unwrap());
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("late-stop", "out.bin", None)
));
pump(&mut c);
let held = pending().expect("the pending download");
drop(held.accept(DownloadDestination::new(destination.clone()).overwrite(true)));
c.apply_actions();
let (_, start, _) = wait_request(&mut c);
reply_ok(&mut c, web, start);
let _ = wait_downloads(&mut c, 1);
let staging = staging_in(&dir).expect("the staging directory");
std::fs::write(staging.join("out.bin"), b"partial").unwrap();
let answer = held.cancel();
c.apply_actions();
let (_, cancel, _) = wait_request(&mut c);
assert!(c.component_event(
web,
EventKind::WebViewReply,
&reply(cancel, Err("stop not confirmed".into()))
));
pump(&mut c);
assert!(matches!(settled(answer), Some(Err(_))));
drop(c);
assert!(staging.exists(), "a failed cancel cannot authorize cleanup");
sink.dispatch(
web + 2,
EventKind::WebViewReply,
&reply(cancel, Ok(crate::JsonValue::Null)),
);
assert!(staging.exists(), "a foreign reply cannot authorize cleanup");
sink.dispatch(
web,
EventKind::WebViewReply,
&reply(cancel, Ok(crate::JsonValue::Null)),
);
until("the late stop's cleanup", || {
(!staging.exists()).then_some(())
});
assert_eq!(std::fs::read(&destination).unwrap(), b"keep");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_finish_before_the_start_reply_starts_once_then_finishes() {
reset();
let dir = scratch("end-before-start");
let destination = dir.join("out.bin");
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d11", "out.bin", Some(3))
));
pump(&mut c);
let held = pending().expect("the pending download");
let answer = held.accept(destination.clone());
c.apply_actions();
let (_, request, _) = wait_request(&mut c);
let staging = staging_in(&dir).expect("staging").join("out.bin");
std::fs::write(&staging, b"abc").unwrap();
// The native setter re-entered: the writer finished before its
// Start reply. The app hears started, then finished.
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end("d11", DownloadOutcome::Finished { bytes: 3 })
));
let events = wait_downloads(&mut c, 2);
assert_eq!(events[0].state, WebDownloadState::Started);
assert_eq!(events[1].state, WebDownloadState::Finished);
assert_eq!(events[0].bytes, None);
assert_eq!(events[1].bytes, Some(3), "the real file length");
assert_eq!(settled(answer), Some(Ok(())));
assert_eq!(std::fs::read(&destination).unwrap(), b"abc");
// The late Start reply is not a second start.
reply_ok(&mut c, web, request);
pump(&mut c);
assert_eq!(downloads().len(), 2);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_rejected_destination_keeps_the_offer_available() {
reset();
let dir = scratch("destination-retry");
let occupied = dir.join("keep.bin");
std::fs::write(&occupied, b"keep").unwrap();
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let web = web_node(&c.commit().unwrap());
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("retry", "out.bin", Some(3))
));
pump(&mut c);
let held = pending().unwrap();
let mut refused = held.accept(occupied.clone());
c.apply_actions();
let refusal = until("destination refusal", || {
pump(&mut c);
settled(&mut refused)
});
assert!(refusal.is_err());
assert_eq!(std::fs::read(&occupied).unwrap(), b"keep");
assert!(downloads().is_empty());
let destination = dir.join("out.bin");
let accepted = held.accept(destination.clone());
c.apply_actions();
let (_, request, operation) = wait_request(&mut c);
let crate::webview::WebViewOperation::StartDownload { staging, .. } = operation else {
panic!("retry must start the same held download");
};
reply_ok(&mut c, web, request);
assert_eq!(settled(accepted), Some(Ok(())));
std::fs::write(staging, b"abc").unwrap();
assert!(c.component_event(
web,
EventKind::DownloadEnd,
&end("retry", DownloadOutcome::Finished { bytes: 3 })
));
let events = wait_downloads(&mut c, 2);
assert_eq!(events[1].state, WebDownloadState::Finished);
assert_eq!(std::fs::read(destination).unwrap(), b"abc");
assert_eq!(std::fs::read(occupied).unwrap(), b"keep");
std::fs::remove_dir_all(dir).unwrap();
}
/// A cancel whose stop the platform confirms with an end instead of a
/// reply to the stop command: the end is the acknowledgement, so the
/// cancel completes (its terminal event is the cancellation, its
/// staging is cleaned) and the late reply changes nothing.
fn cancel_ended_by(name: &str, outcome: DownloadOutcome) {
reset();
let dir = scratch(name);
let destination = dir.join("out.bin");
let mut c = core();
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("ended", "out.bin", Some(3))
));
pump(&mut c);
let held = pending().expect("the pending download");
drop(held.accept(destination.clone()));
c.apply_actions();
let (_, start, _) = wait_request(&mut c);
reply_ok(&mut c, web, start);
let events = wait_downloads(&mut c, 1);
assert_eq!(events[0].state, WebDownloadState::Started);
let staging = staging_in(&dir).expect("staging").join("out.bin");
std::fs::write(&staging, b"abc").unwrap();
let mut cancel = downloads()[0].cancel();
c.apply_actions();
let (_, cancel_request, operation) = wait_request(&mut c);
assert!(matches!(
operation,
crate::webview::WebViewOperation::CancelDownload { ref id } if id == "ended"
));
assert_eq!(settled(&mut cancel), None, "the cancel waits for the stop");
// The writer ended before the platform answered the stop: the
// cancel was asked for first, so it stands, and its cleanup runs.
assert!(c.component_event(web, EventKind::DownloadEnd, &end("ended", outcome)));
let events = wait_downloads(&mut c, 2);
assert_eq!(events[1].state, WebDownloadState::Cancelled);
assert_eq!(events[1].reason, Some(CancelReason::App));
assert_eq!(settled(cancel), Some(Ok(())));
assert!(staging_in(&dir).is_none(), "the staging directory goes");
assert!(!destination.exists(), "a cancel publishes nothing");
// The late reply answers a command the end already settled.
reply_ok(&mut c, web, cancel_request);
pump(&mut c);
assert_eq!(downloads().len(), 2, "no second terminal event");
assert!(!destination.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_finish_before_the_cancel_reply_still_finishes_the_cancel() {
cancel_ended_by(
"cancel-ended-finish",
DownloadOutcome::Finished { bytes: 3 },
);
}
#[test]
fn a_failure_before_the_cancel_reply_still_finishes_the_cancel() {
cancel_ended_by(
"cancel-ended-failure",
DownloadOutcome::Failed {
code: None,
message: "the network went".into(),
},
);
}
#[test]
fn a_completed_stage_no_poll_took_is_cleaned_when_the_core_drops() {
reset();
let dir = scratch("unpolled-stage");
let destination = dir.join("out.bin");
let mut c = core();
// The core's notify is the only sign the file thread finished the
// stage: it queues the signal first, then notifies.
let notified = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let count = notified.clone();
c.set_task_notify(std::sync::Arc::new(move || {
count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}));
c.mount_root(&crate::element::Root::new::<ManualDownloads>(|| ()));
let batch = c.commit().unwrap();
let web = web_node(&batch);
assert!(c.component_event(
web,
EventKind::DownloadOffer,
&offer("d14", "out.bin", None)
));
pump(&mut c);
let held = pending().expect("the pending download");
drop(held.accept(destination.clone()));
// One notification is the executor's for the action; the second is
// the file thread's, after the staged signal was queued.
c.apply_actions();
let staging = until("the queued stage", || {
(notified.load(std::sync::atomic::Ordering::SeqCst) >= 2)
.then(|| staging_in(&dir))
.flatten()
});
assert!(staging.exists());
// No commit takes the signal: the staging directory no session
// ever learned must still go when the core does.
drop(c);
until("the staged directory's cleanup", || {
(!staging.exists()).then_some(())
});
assert!(!destination.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_last_download_listener_removed_cancels_with_no_listener() {
reset();
let dir = scratch("no-listener");
let mut c = core();
let web = js_web_view(&mut c);
assert!(c.component_event(web, EventKind::DownloadOffer, &offer("nl", "out.bin", None)));
pump(&mut c);
// Both listeners removed and given back before the turn ends: the
// mask it ended with still has them, so nothing is cancelled.
apply(
&mut c,
vec![
Op::Listen {
id: web,
event: EventKind::DownloadPending,
enabled: false,
},
Op::Listen {
id: web,
event: EventKind::Download,
enabled: false,
},
Op::Listen {
id: web,
event: EventKind::DownloadPending,
enabled: true,
},
Op::Listen {
id: web,
event: EventKind::Download,
enabled: true,
},
],
);
if let Some(batch) = c.commit() {
assert!(requests(&batch.items).is_empty(), "both are back");
}
// One listener still hears the download and decides its offer.
listen(&mut c, web, EventKind::Download, false);
if let Some(batch) = c.commit() {
assert!(
requests(&batch.items).is_empty(),
"a remaining listener keeps the download"
);
}
// The last one goes: the view stays, and its download is stopped.
listen(&mut c, web, EventKind::DownloadPending, false);
let batch = c.commit().expect("the cancel command");
let (node, request, operation) = requests(&batch.items)
.into_iter()
.next()
.expect("a cancel command");
assert_eq!(node, web);
assert!(matches!(
operation,
crate::webview::WebViewOperation::CancelDownload { ref id } if id == "nl"
));
assert!(c.key(web).is_ok(), "the view itself stays mounted");
assert!(
!batch
.items
.iter()
.any(|i| matches!(i, MountItem::Remove { id } if *id == web)),
"the view is not released"
);
// Nothing is reported until the platform confirms its writer
// stopped.
let mut events = Vec::new();
c.take_events(&mut events);
assert!(events.is_empty(), "the cancel waits for the stop");
reply_ok(&mut c, web, request);
let queued = queued_downloads(&mut c);
assert_eq!(queued.len(), 1);
assert_eq!(queued[0].0, web);
assert_eq!(queued[0].1, WebDownloadState::Cancelled.to_string());
assert_eq!(
queued[0].2.as_deref(),
Some(CancelReason::NoListener.as_str())
);
let _ = std::fs::remove_dir_all(&dir);
}
}
#[path = "reconciliation_tests.rs"]
mod reconciliation_cleanup;
#[path = "component_host_tests.rs"]
mod component_host;
// Structural variants share positions without changing immediate restyling.
mod positional_regressions {
use super::*;
const CLASSES: &str = "w-10 h-4 bg-red-500 first:bg-green-500 last:bg-blue-500 odd:pt-1 even:pb-2 only:px-3 last:text-white first:z-10 odd:pointer-events-none last:max-w-prose";
fn snapshot(c: &Core<FakeEngine>, children: &[Key]) -> Vec<String> {
children
.iter()
.map(|&key| {
let n = &c.nodes[key as usize];
format!(
"{:?}",
(
n.id,
&n.view_style,
&n.text_style,
&n.class_props,
&n.base_layout,
n.direction,
n.rtl,
n.z_index,
n.wants_fixed,
)
)
})
.collect()
}
// The ordinary resolver counts the actual sibling list while the
// parent's children moved (otherwise it takes the bits each child was
// last styled at). Compare the shared-position pass with that
// independent path.
fn check(c: &mut Core<FakeEngine>, parent: NodeId) {
let parent = c.key(parent).unwrap();
c.positions_changed(parent);
let children = c.nodes[parent as usize].children.clone();
let expected = snapshot(c, &children);
let flags = c.nodes[parent as usize].positional;
c.nodes[parent as usize].positional |= super::Positional::QUEUED;
for &key in &children {
if c.nodes[key as usize]
.classes
.as_ref()
.is_some_and(|classes| classes.deps() & crate::tailwind::deps::POSITION != 0)
{
c.restyle(key);
}
}
c.nodes[parent as usize].positional = flags;
assert_eq!(snapshot(c, &children), expected);
}
/// What restyling each of `parent`'s children on its own (a hover, a
/// press) gives, taking the bits each was last styled at, is what
/// counting its siblings gives.
fn kept_positions_match_counted(c: &mut Core<FakeEngine>, parent: NodeId) {
let parent = c.key(parent).unwrap();
let children = c.nodes[parent as usize].children.clone();
for &key in &children {
c.restyle(key);
}
let kept = snapshot(c, &children);
let flags = c.nodes[parent as usize].positional;
c.nodes[parent as usize].positional |= super::Positional::QUEUED;
for &key in &children {
c.restyle(key);
}
c.nodes[parent as usize].positional = flags;
assert_eq!(kept, snapshot(c, &children));
}
/// A child restyled on its own after its siblings moved takes the bits
/// its last styling counted: also one whose classes were cleared while
/// they moved, and given back after.
#[test]
fn a_child_restyled_on_its_own_keeps_its_counted_position() {
let mut c = core();
view_with_classes(&mut c, 2, "");
for id in [4, 6, 8] {
child(&mut c, id, 2);
}
c.commit();
c.apply(Op::Insert {
parent: 2,
child: 4,
before: None,
})
.unwrap();
c.commit();
kept_positions_match_counted(&mut c, 2);
// 6, first, loses its classes; a row comes before it; it gets them
// back: second.
c.apply(class_op(6, "")).unwrap();
c.commit();
apply(
&mut c,
vec![
Op::Create {
id: 10,
tag: Tag::View,
},
class_op(10, CLASSES),
Op::Insert {
parent: 2,
child: 10,
before: Some(6),
},
],
);
c.commit();
c.apply(class_op(6, CLASSES)).unwrap();
c.commit();
kept_positions_match_counted(&mut c, 2);
}
/// An overlay given a hint becomes a tooltip's, which counts among no
/// siblings: the rows after it move up a place.
#[test]
fn an_overlay_given_a_hint_moves_its_siblings_up() {
let mut c = core();
view_with_classes(&mut c, 2, "");
child(&mut c, 4, 2);
apply(
&mut c,
vec![
Op::Create {
id: 6,
tag: Tag::Overlay,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
],
);
child(&mut c, 8, 2);
c.commit();
let third = c.nodes[c.key(8).unwrap() as usize].position_used;
c.apply(overlay_prop(
6,
crate::OverlayProp::Hint(Some(std::time::Duration::from_millis(300))),
))
.unwrap();
c.commit();
assert_ne!(c.nodes[c.key(8).unwrap() as usize].position_used, third);
kept_positions_match_counted(&mut c, 2);
}
/// Rows mounted one insert at a time have their positions looked at
/// once per parent before the commit styles them: the siblings looked
/// at grow with the rows, not with their square.
#[test]
fn positions_are_looked_at_once_per_parent_as_rows_mount() {
let work = |rows: NodeId| {
let mut c = core();
view_with_classes(&mut c, 2, "");
for i in 0..rows {
let id = 10 + 2 * i;
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, "w-10 h-4 odd:bg-red-500 last:bg-blue-500"),
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
c.commit();
c.components.position_work.get()
};
let (few, many) = (work(400), work(1_600));
// Four times the rows: about four times the work (sixteen before).
assert!(
many <= few * 6,
"{few} siblings looked at for 400 rows, {many} for 1,600"
);
}
fn child(c: &mut Core<FakeEngine>, id: NodeId, parent: NodeId) {
apply(
c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, CLASSES),
Op::Insert {
parent,
child: id,
before: None,
},
],
);
check(c, parent);
}
#[test]
fn shared_positions_match_individual_resolution_after_tree_edits() {
let mut c = core();
view_with_classes(&mut c, 2, "");
view_with_classes(&mut c, 100, "");
for id in [4, 6, 8, 10] {
child(&mut c, id, 2);
}
// Text markers do not consume the first, last or odd/even positions.
for (id, before) in [(40, Some(4)), (42, Some(8)), (44, None)] {
apply(
&mut c,
vec![
Op::CreateText {
id,
text: "".into(),
},
Op::Insert {
parent: 2,
child: id,
before,
},
],
);
check(&mut c, 2);
}
// An ordinary sibling still consumes an element position.
c.apply(Op::Create {
id: 52,
tag: Tag::View,
})
.unwrap();
c.apply(class_op(52, "w-10 h-4")).unwrap();
c.apply(Op::Insert {
parent: 2,
child: 52,
before: Some(8),
})
.unwrap();
check(&mut c, 2);
// The core's own decorations are excluded too. A decoration with
// structural classes keeps the resolver's existing index-0 fallback.
c.apply(Op::Create {
id: 46,
tag: Tag::View,
})
.unwrap();
let decoration = c.key(46).unwrap();
c.nodes[decoration as usize].decoration = true;
c.apply(class_op(46, CLASSES)).unwrap();
c.apply(Op::Insert {
parent: 2,
child: 46,
before: Some(6),
})
.unwrap();
check(&mut c, 2);
// Setting classes after insertion must register the parent's
// positional children before the next append.
c.apply(Op::Create {
id: 48,
tag: Tag::View,
})
.unwrap();
c.apply(Op::Insert {
parent: 100,
child: 48,
before: None,
})
.unwrap();
c.apply(class_op(48, CLASSES)).unwrap();
assert!(
c.nodes[c.key(100).unwrap() as usize]
.positional
.has(super::Positional::CHILDREN)
);
child(&mut c, 50, 100);
for op in [
Op::Insert {
parent: 2,
child: 10,
before: Some(4),
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: 100,
child: 6,
before: Some(48),
},
Op::Remove {
parent: 2,
child: 8,
},
Op::Remove {
parent: 100,
child: 50,
},
Op::Remove {
parent: 100,
child: 48,
},
] {
c.apply(op).unwrap();
check(&mut c, 2);
check(&mut c, 100);
}
// A real tooltip overlay also does not count among the rows.
c.apply(Op::Create {
id: 60,
tag: Tag::View,
})
.unwrap();
c.apply(Op::SetProp {
id: 2,
prop: Prop::Tooltip(crate::overlay::TooltipContent::Node(60)),
})
.unwrap();
let overlay = c.overlay_state.tooltips[&2].overlay;
c.apply(class_op(overlay, CLASSES)).unwrap();
check(&mut c, 2);
child(&mut c, 62, 2);
c.commit();
check(&mut c, 2);
check(&mut c, 100);
// The sole element in the second parent is still both first and last.
let only = &c.nodes[c.key(6).unwrap() as usize];
assert_eq!(only.view_style.background_color, Color(0x2b7f_ffff));
assert_eq!(only.text_style.color, Some(Color(0xffff_ffff)));
}
#[test]
fn positional_fixed_style_still_settles_after_reordering() {
let mut c = core();
view_with_classes(&mut c, 2, "");
for id in [4, 6, 8] {
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, "w-10 h-4 last:fixed"),
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
c.commit();
for id in [4, 6, 8] {
assert_eq!(c.nodes[c.key(id).unwrap() as usize].fixed_view, id == 8);
}
c.apply(Op::Insert {
parent: 2,
child: 4,
before: None,
})
.unwrap();
c.commit();
for id in [4, 6, 8] {
assert_eq!(c.nodes[c.key(id).unwrap() as usize].fixed_view, id == 4);
}
check(&mut c, 2);
}
}
#[test]
fn span_padding_widens_its_box_in_the_line() {
// <Text>a <Text bg paddingHorizontal=4>b</Text> c</Text>
let mut c = core();
let span_style = |padding: f32| {
style_op(
4,
&[
("backgroundColor", StyleValue::Str("#ff0000")),
("paddingHorizontal", StyleValue::Number(padding)),
],
)
};
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::Text,
},
Op::CreateText {
id: 3,
text: "a ".into(),
},
Op::Create {
id: 4,
tag: Tag::Text,
},
span_style(4.0),
Op::CreateText {
id: 5,
text: "b".into(),
},
Op::CreateText {
id: 6,
text: " c".into(),
},
Op::Insert {
parent: 4,
child: 5,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
Op::Insert {
parent: 2,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 6,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let text = text_item(&batch).unwrap();
// An empty attachment at each end of the span takes its padding in the
// line, in the span's background.
assert_eq!(text.text, "a \u{FFFC}b\u{FFFC} c");
let pads: Vec<_> = text
.attachments
.iter()
.map(|a| (a.index, a.width, a.height))
.collect();
assert_eq!(
pads,
[(2, Points(4.0), Points(0.0)), (4, Points(4.0), Points(0.0))]
);
for i in 2..5 {
assert_eq!(text.background_at(i).map(|b| b.node), Some(4));
}
assert_eq!(text.background_at(5), None);
// Copies and reads without them.
assert_eq!(text.copied_text(0..text.len_utf16()), "a b c");
assert_eq!(text.visible_text(), "a b c");
// Another padding lays the text out again.
apply(&mut c, vec![span_style(6.0)]);
let text = text_item(&c.commit().unwrap()).unwrap();
assert_eq!(text.attachments[0].width, Points(6.0));
// No padding, no attachments.
apply(&mut c, vec![span_style(0.0)]);
let text = text_item(&c.commit().unwrap()).unwrap();
assert_eq!(text.text, "a b c");
assert!(text.attachments.is_empty());
// Vertical padding is the background's only: no attachments, the
// room above and below in the background.
apply(
&mut c,
vec![style_op(
4,
&[
("backgroundColor", StyleValue::Str("#ff0000")),
("paddingTop", StyleValue::Number(3.0)),
("paddingBottom", StyleValue::Number(1.0)),
],
)],
);
let text = text_item(&c.commit().unwrap()).unwrap();
assert_eq!(text.text, "a b c");
assert!(text.attachments.is_empty());
let b = text.background_at(2).unwrap();
assert_eq!((b.top, b.bottom), (Points(3.0), Points(1.0)));
}
#[test]
fn node_record_sizes() {
// #1345: the per-node records the core keeps for every node.
let node = std::mem::size_of::<super::Node>();
eprintln!("Node {node} B");
assert!(node <= 600, "Node grew to {node} bytes");
}
#[test]
fn style_constants_match_default() {
assert_eq!(
crate::style::ViewStyle::DEFAULT,
crate::style::ViewStyle::default()
);
assert_eq!(
crate::style::TextStyle::DEFAULT,
crate::style::TextStyle::default()
);
}
/// #1345: a text block's only raw text run has no node of its own.
mod folded_runs {
use super::*;
fn last_text(c: &mut Core<FakeEngine>) -> Option<String> {
let batch = c.commit()?;
batch.items.iter().rev().find_map(|i| match i {
MountItem::Text { text, .. } => Some(text.text.clone()),
_ => None,
})
}
fn insert(parent: NodeId, child: NodeId, before: Option<NodeId>) -> Op {
Op::Insert {
parent,
child,
before,
}
}
fn block(c: &mut Core<FakeEngine>, id: NodeId) {
apply(
c,
vec![Op::Create { id, tag: Tag::Text }, insert(ROOT_ID, id, None)],
);
}
fn raw_nodes(c: &Core<FakeEngine>) -> usize {
c.nodes
.iter()
.filter(|(_, n)| n.kind == Kind::RawText)
.count()
}
fn run(id: NodeId, text: &str) -> Op {
Op::CreateText {
id,
text: text.into(),
}
}
#[test]
fn a_blocks_only_run_shows_without_a_node() {
let mut c = core();
block(&mut c, 2);
apply(&mut c, vec![run(3, "hello"), insert(2, 3, None)]);
assert_eq!(last_text(&mut c).as_deref(), Some("hello"));
assert_eq!(raw_nodes(&c), 0);
assert_eq!(c.text_content(2), "hello");
apply(
&mut c,
vec![Op::SetText {
id: 3,
text: "world".into(),
}],
);
assert_eq!(last_text(&mut c).as_deref(), Some("world"));
assert_eq!(raw_nodes(&c), 0);
}
#[test]
fn a_second_child_gives_the_run_its_node_in_order() {
let mut c = core();
block(&mut c, 2);
apply(
&mut c,
vec![
run(3, "a"),
insert(2, 3, None),
run(4, "b"),
insert(2, 4, None),
],
);
assert_eq!(last_text(&mut c).as_deref(), Some("ab"));
assert_eq!(raw_nodes(&c), 2);
// Before the folded run: it gets its node first.
let mut c = core();
block(&mut c, 2);
apply(&mut c, vec![run(3, "b"), insert(2, 3, None)]);
c.commit();
apply(&mut c, vec![run(4, "a"), insert(2, 4, Some(3))]);
assert_eq!(last_text(&mut c).as_deref(), Some("ab"));
apply(
&mut c,
vec![Op::SetText {
id: 3,
text: "c".into(),
}],
);
assert_eq!(last_text(&mut c).as_deref(), Some("ac"));
}
#[test]
fn a_folded_run_moves_and_goes() {
let mut c = core();
block(&mut c, 2);
block(&mut c, 5);
apply(&mut c, vec![run(3, "x"), insert(2, 3, None)]);
c.commit();
assert_eq!(c.text_content(2), "x");
assert!(matches!(
c.apply(Op::Remove {
parent: 5,
child: 3
}),
Err(ApplyError::NotAChild(3))
));
apply(
&mut c,
vec![Op::Remove {
parent: 2,
child: 3,
}],
);
assert_eq!(c.text_content(2), "");
// Moved to another block without a Remove too.
apply(&mut c, vec![insert(5, 3, None)]);
assert_eq!(c.text_content(5), "x");
apply(&mut c, vec![insert(2, 3, None)]);
assert_eq!(c.text_content(5), "");
assert_eq!(c.text_content(2), "x");
assert_eq!(raw_nodes(&c), 0);
// Its block goes: it is loose until released.
apply(
&mut c,
vec![
Op::Remove {
parent: ROOT_ID,
child: 2,
},
Op::Release { id: 2 },
],
);
apply(&mut c, vec![insert(5, 3, None)]);
assert_eq!(c.text_content(5), "x");
apply(&mut c, vec![Op::Release { id: 3 }]);
assert_eq!(c.text_content(5), "");
assert!(c.runs.is_empty() && c.folded.is_empty());
assert!(matches!(
c.apply(run(5, "dup")),
Err(ApplyError::DuplicateNode(5))
));
}
#[test]
fn folded_runs_count_for_the_node_quota() {
let mut c = core();
c.set_max_nodes(3);
apply(&mut c, vec![run(2, "a"), run(3, "b")]);
assert!(matches!(
c.apply(run(4, "c")),
Err(ApplyError::TooManyNodes(3))
));
assert!(matches!(
c.apply(Op::Create {
id: 4,
tag: Tag::View
}),
Err(ApplyError::TooManyNodes(3))
));
apply(&mut c, vec![Op::Release { id: 3 }]);
apply(
&mut c,
vec![Op::Create {
id: 4,
tag: Tag::View,
}],
);
assert!(matches!(
c.apply(run(5, "d")),
Err(ApplyError::TooManyNodes(3))
));
}
#[test]
fn a_node_cannot_reuse_a_folded_runs_id() {
let mut c = core();
block(&mut c, 2);
apply(&mut c, vec![run(3, "hello")]);
for folded in [false, true] {
if folded {
apply(&mut c, vec![insert(2, 3, None)]);
}
assert!(matches!(
c.apply(Op::Create {
id: 3,
tag: Tag::Scroll
}),
Err(ApplyError::DuplicateNode(3))
));
assert!(c.runs.contains_key(&3));
assert!(!c.slots.contains(3));
}
assert_eq!(c.text_content(2), "hello");
apply(&mut c, vec![style_op(3, &[])]);
assert_eq!(raw_nodes(&c), 1);
assert_eq!(c.text_content(2), "hello");
}
#[test]
fn a_full_slab_keeps_a_blocks_folded_text() {
let mut c = core();
block(&mut c, 2);
apply(&mut c, vec![run(3, "hello"), insert(2, 3, None)]);
apply(
&mut c,
vec![Op::Create {
id: 4,
tag: Tag::View,
}],
);
c.commit();
c.set_max_nodes(3);
assert!(matches!(
c.apply(insert(2, 4, None)),
Err(ApplyError::TooManyNodes(3))
));
assert_eq!(c.text_content(2), "hello");
assert_eq!(c.folded.len(), 1);
assert_eq!(raw_nodes(&c), 0);
c.set_max_nodes(10);
apply(&mut c, vec![insert(2, 4, None)]);
assert_eq!(raw_nodes(&c), 1);
assert_eq!(c.text_content(2), "hello");
assert!(c.folded.is_empty());
}
#[test]
fn a_run_in_a_span_folds_and_keeps_its_place() {
// <Text>a<Text bold>b</Text>c</Text>
let mut c = core();
block(&mut c, 2);
apply(
&mut c,
vec![
run(3, "a"),
insert(2, 3, None),
Op::Create {
id: 4,
tag: Tag::Text,
},
run(5, "b"),
insert(4, 5, None),
insert(2, 4, None),
run(6, "c"),
insert(2, 6, None),
],
);
assert_eq!(last_text(&mut c).as_deref(), Some("abc"));
// The span's run stays without a node; the block's got theirs.
assert_eq!(raw_nodes(&c), 2);
assert_eq!(c.folded.len(), 1);
}
#[test]
fn a_run_under_a_view_has_its_node() {
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::View,
},
insert(ROOT_ID, 2, None),
run(3, "v"),
insert(2, 3, None),
],
);
assert_eq!(raw_nodes(&c), 1);
assert!(c.runs.is_empty());
}
}
/// #1345: the issue's 300 × 50 table (15,000 cells, each a view holding
/// a text block and its raw text run), with and without runs folded into
/// their blocks.
/// `cargo test --release -p nsh-core --lib raw_text_table_bench --
/// --ignored --nocapture` (`NSH_RUNS=nodes` for every run as a node)
#[test]
#[ignore]
fn raw_text_table_bench() {
use std::time::Instant;
fn rss_kib() -> u64 {
std::fs::read_to_string("/proc/self/status")
.ok()
.and_then(|s| {
s.lines()
.find(|l| l.starts_with("VmRSS:"))
.and_then(|l| l.split_whitespace().nth(1)?.parse().ok())
})
.unwrap_or(0)
}
let fold = std::env::var("NSH_RUNS").map_or(true, |v| v != "nodes");
let mut c = Core::new(crate::ApproxTextEngine, size_pt(1600.0, 900.0));
c.fold_runs = fold;
let before = rss_kib();
let mut ops = Vec::new();
let mut id: NodeId = 2;
let table = id;
ops.push(Op::Create {
id: table,
tag: Tag::View,
});
for r in 0..300 {
id += 1;
let row = id;
ops.push(Op::Create {
id: row,
tag: Tag::View,
});
ops.push(style_op(row, &[("flexDirection", StyleValue::Str("row"))]));
for col in 0..50 {
let (cell, text, run) = (id + 1, id + 2, id + 3);
id += 3;
ops.push(Op::Create {
id: cell,
tag: Tag::View,
});
ops.push(style_op(
cell,
&[
("width", StyleValue::Number(32.0)),
("padding", StyleValue::Number(2.0)),
],
));
ops.push(Op::Create {
id: text,
tag: Tag::Text,
});
ops.push(Op::CreateText {
id: run,
text: format!("{r}:{col}"),
});
for (parent, child) in [(text, run), (cell, text), (row, cell)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
}
ops.push(Op::Insert {
parent: table,
child: row,
before: None,
});
}
ops.push(Op::Insert {
parent: ROOT_ID,
child: table,
before: None,
});
let t = Instant::now();
apply(&mut c, ops);
let batch = c.commit().unwrap();
let mount_ms = t.elapsed().as_secs_f64() * 1e3;
let after = rss_kib();
let texts = batch
.items
.iter()
.filter(|i| matches!(i, MountItem::Text { .. }))
.count();
let node = std::mem::size_of::<super::Node>();
println!(
"{}: nodes {}, runs without nodes {}, slab capacity {}, Node {node} B, Run {} B, texts {texts}",
if fold { "folded" } else { "nodes" },
c.nodes.len(),
c.runs.len(),
c.nodes.capacity(),
std::mem::size_of::<super::Run>(),
);
println!(
"RSS growth {:.1} MiB, first mount + commit {mount_ms:.1} ms",
(after - before) as f64 / 1024.0
);
let mut times = Vec::new();
for i in 0..21 {
let t = Instant::now();
let _ = c.apply(Op::SetText {
id: 6,
text: format!("x{i}"),
});
let _ = c.commit();
times.push(t.elapsed().as_secs_f64() * 1e6);
}
times.sort_by(f64::total_cmp);
println!("set one run's text + commit: median {:.0} µs", times[10]);
let mut times = Vec::new();
for i in 0..5 {
let t = Instant::now();
c.set_viewport(size_pt(1500.0 + i as f32 * 10.0, 900.0));
let _ = c.commit();
times.push(t.elapsed().as_secs_f64() * 1e3);
}
times.sort_by(f64::total_cmp);
println!("resize + full relayout + commit: median {:.1} ms", times[2]);
}
/// With nothing focused, a backend reports raw keys at the window's root
/// (`ROOT_ID`, or a dialog's root): an app's `on_key_down` on its
/// top-level view hears them and a capture there decides, as a browser
/// reports them at `document.body` (#2362).
#[test]
fn unfocused_keys_reach_the_windows_root() {
use crate::{keymap::Keystroke, prelude::*};
#[component]
fn Listening() -> impl IntoElement {
view()
.on_key_down(|_: &KeyEvent| {})
.capture_keys(KeyCapture::keys([
Keystroke::parse_with("space", false).unwrap()
]))
.child(view().test_id("child"))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Listening>());
let batch = c.commit().unwrap();
assert!(c.key_interest(crate::ROOT_ID));
let space = Keystroke::parse_with("space", false).unwrap();
assert!(c.key_captured(crate::ROOT_ID, Some(&space)));
let a = Keystroke::parse_with("a", false).unwrap();
assert!(!c.key_captured(crate::ROOT_ID, Some(&a)));
let mut path = Vec::new();
c.key_path(crate::ROOT_ID, &mut path);
assert_eq!(path.last(), Some(&crate::ROOT_ID));
assert_eq!(path.len(), 2, "the mount root, then the window root");
let mounted_content = |batch: &crate::MountBatch| {
batch.items.iter().rev().find_map(|item| match item {
MountItem::ViewProps { id, props } if *id == crate::ROOT_ID => Some(props.key_content),
_ => None,
})
};
let content = path[0];
assert_eq!(mounted_content(&batch), Some(Some(content)));
c.apply(Op::Remove {
parent: crate::ROOT_ID,
child: content,
})
.unwrap();
let batch = c.commit().unwrap();
assert_eq!(mounted_content(&batch), Some(None));
}
/// A root without listeners or captures builds no key event: an app that
/// listens nowhere pays nothing for the unfocused path.
#[test]
fn unfocused_keys_are_free_without_a_root_listener() {
use crate::prelude::*;
#[component]
fn Quiet() -> impl IntoElement {
view().child(view().on_key_down(|_: &KeyEvent| {}))
}
let mut c = core();
c.mount_root(&crate::element::Root::of::<Quiet>());
let batch = c.commit().unwrap();
assert!(!c.key_interest(crate::ROOT_ID));
assert!(!batch.items.iter().any(|item| matches!(
item,
MountItem::ViewProps {
id: crate::ROOT_ID,
..
}
)));
}
#[test]
fn unfocused_keys_follow_named_window_content_changes() {
use crate::{
KeyCapture,
desktop::{DesktopCommand, OpenWindow},
props::{AccessibilityProp, AccessibilityState},
};
let root = 2;
let content = 4;
let mut c = core();
c.set_environment(crate::element::Environment {
os: crate::platform::Os::MacOs,
..Default::default()
});
let mut open = OpenWindow::default();
open.options.id = "panel".into();
apply(
&mut c,
vec![
Op::Create {
id: root,
tag: Tag::Modal,
},
Op::Insert {
parent: ROOT_ID,
child: root,
before: None,
},
Op::Create {
id: content,
tag: Tag::Input,
},
Op::Insert {
parent: root,
child: content,
before: None,
},
Op::Command {
id: root,
command: Command::Desktop(Box::new(DesktopCommand::OpenWindow(Box::new(open)))),
},
],
);
let mounted_content = |batch: &crate::MountBatch| {
batch.items.iter().rev().find_map(|item| match item {
MountItem::ViewProps { id, props } if *id == root => Some(props.key_content),
_ => None,
})
};
let listen = |enabled| Op::Listen {
id: content,
event: EventKind::KeyUp,
enabled,
};
assert_eq!(mounted_content(&c.commit().unwrap()).flatten(), None);
c.apply(listen(true)).unwrap();
assert_eq!(mounted_content(&c.commit().unwrap()), Some(Some(content)));
assert!(c.key_interest(root));
assert!(!c.key_interest(ROOT_ID));
let disable = |disabled| Op::SetProp {
id: content,
prop: Prop::Accessibility(AccessibilityProp::State(AccessibilityState {
disabled,
..Default::default()
})),
};
c.apply(disable(true)).unwrap();
assert_eq!(mounted_content(&c.commit().unwrap()), None);
assert!(!c.key_interest(root));
c.apply(disable(false)).unwrap();
assert_eq!(mounted_content(&c.commit().unwrap()), None);
assert!(c.key_interest(root));
c.apply(listen(false)).unwrap();
assert_eq!(mounted_content(&c.commit().unwrap()), Some(None));
let capture = |rule| Op::SetProp {
id: root,
prop: Prop::KeyCapture(rule),
};
c.apply(capture(KeyCapture::All)).unwrap();
assert_eq!(mounted_content(&c.commit().unwrap()), Some(Some(content)));
assert!(!c.key_captured(root, None), "the input keeps its keys");
c.apply(capture(KeyCapture::None)).unwrap();
assert_eq!(mounted_content(&c.commit().unwrap()), Some(None));
}
/// [`WordsEngine`]'s lines, kept by its layout for [`TextEngine::lines`].
struct LinesEngine;
fn word_lines(text: &str, max: f32) -> Vec<f32> {
let mut lines = vec![0.0f32];
for word in text.split(' ') {
let width = word.chars().count() as f32 * 8.0;
let line = lines.last_mut().unwrap();
if *line > 0.0 && *line + 8.0 + width > max {
lines.push(width);
} else if *line > 0.0 {
*line += 8.0 + width;
} else {
*line = width;
}
}
lines
}
impl TextEngine for LinesEngine {
type Prepared = String;
fn prepare(&self, text: &AttributedText) -> String {
text.text.clone()
}
fn measure(&self, text: &String, max_width: Option<Points>) -> Size<Points> {
let lines = word_lines(text, max_width.map_or(f32::INFINITY, |m| m.0));
let widest = lines.iter().copied().fold(0.0, f32::max);
size_pt(widest, lines.len() as f32 * 16.0)
}
fn layout(&self, text: &String, size: Size<Points>) -> TextLayout {
TextLayout(Arc::new(word_lines(text, size.width.0)))
}
fn lines(&self, layout: &TextLayout) -> Vec<crate::TextLine> {
layout.downcast::<Vec<f32>>().map_or_else(Vec::new, |l| {
l.iter()
.map(|&w| crate::TextLine {
width: Points(w),
..crate::TextLine::default()
})
.collect()
})
}
}
/// `text-pretty` breaks a paragraph whose last line holds a lone word
/// narrower, as many lines with a longer last one; a paragraph that ends
/// well, or fits on a line, keeps its box's width.
#[test]
fn pretty_text_takes_words_down_to_a_short_last_line() {
// At 200: "aaaa bbbb cccc dddd eeee" (192) and "ff" (16).
let text = "aaaa bbbb cccc dddd eeee ff";
let mut cx = words_context(text, 0);
cx.pretty = Some(Box::new((f32::NAN, Points::ZERO)));
let width = pretty_width(&LinesEngine, &mut cx, Points(200.0));
assert!(width < Points(200.0), "{width:?}");
let lines = word_lines(text, width.0);
assert_eq!(lines.len(), 2);
assert!(
lines[1] >= width.0 * PRETTY_LAST_LINE,
"{lines:?} at {width:?}"
);
// Asked again: the same, from what it kept.
assert_eq!(pretty_width(&LinesEngine, &mut cx, Points(200.0)), width);
let mut cx = words_context("aaaa bbbb cccc dddd eeee ffff gggg", 0);
assert_eq!(
pretty_width(&LinesEngine, &mut cx, Points(200.0)),
Points(200.0)
);
let mut cx = words_context("aaaa bbbb", 0);
assert_eq!(
pretty_width(&LinesEngine, &mut cx, Points(200.0)),
Points(200.0)
);
// A clamp keeps its lines where they are.
let mut cx = words_context(text, 2);
assert_eq!(
pretty_width(&LinesEngine, &mut cx, Points(200.0)),
Points(200.0)
);
}
#[test]
fn text_pretty_wraps_and_inherits_with_white_space() {
let mut c = core();
view_with_classes(&mut c, 2, "text-pretty");
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::Text,
},
Op::CreateText {
id: 4,
text: "hello".into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
c.commit();
let (no_wrap, _, _, pretty) = c.inherited_text_wrap(c.key(3).unwrap());
assert_eq!((no_wrap, pretty), (Some(false), true));
c.apply(class_op(3, "whitespace-normal")).unwrap();
c.commit();
assert!(!c.inherited_text_wrap(c.key(3).unwrap()).3);
}
/// Rust's `text_pretty` on a view reaches the texts in it, as the class
/// does; a text's own `whitespace_nowrap` takes it back.
#[test]
fn rust_text_pretty_inherits_as_the_class() {
use crate::{element::Root, prelude::*};
#[component]
fn PrettyTexts() -> impl IntoElement {
view()
.text_pretty()
.child(text("pretty"))
.child(text("one line").whitespace_nowrap())
}
let mut c = core();
c.mount_root(&Root::new::<PrettyTexts>(|| ()));
let batch = c.commit().unwrap();
let wrap = |label: &str| {
let id = batch
.items
.iter()
.find_map(|item| match item {
MountItem::Text { id, text, .. } if &*text.text == label => Some(*id),
_ => None,
})
.unwrap_or_else(|| panic!("no text {label:?}"));
let (no_wrap, _, _, pretty) = c.inherited_text_wrap(c.key(id).unwrap());
(no_wrap, pretty)
};
assert_eq!(wrap("pretty"), (Some(false), true));
assert_eq!(wrap("one line"), (Some(true), false));
}
#[test]
fn an_overlay_leaves_escape_to_focused_content_that_captures_it() {
use crate::{KeyCapture, keymap::Keystroke, tailwind::state::FOCUSED};
// #2424: an editor in a popover takes Escape first; the overlay binds
// it again once the focus leaves the editor or the rule drops it.
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[]);
add(&mut c, 4, Tag::Overlay, 2, &[]);
add(&mut c, 6, Tag::View, 4, &[]);
add(&mut c, 8, Tag::View, 6, &[]);
add(&mut c, 10, Tag::View, 4, &[]);
apply(
&mut c,
vec![
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
Op::Listen {
id: 4,
event: EventKind::Cancel,
enabled: true,
},
],
);
let escape_bound = |c: &mut Core<FakeEngine>| -> Option<bool> {
let batch = c.commit()?;
batch.items.iter().rev().find_map(|i| match i {
MountItem::Keymap(k) => {
Some(k.bindings().iter().any(|b| b.id == overlay::ESCAPE_BINDING))
}
_ => None,
})
};
assert_eq!(escape_bound(&mut c), Some(true));
let escape = Keystroke::parse_with("escape", false).unwrap();
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::KeyCapture(KeyCapture::keys([escape])),
}],
);
// No focus in the editor yet: the overlay keeps Escape.
assert_ne!(escape_bound(&mut c), Some(false));
c.set_states(8, FOCUSED);
assert_eq!(escape_bound(&mut c), Some(false), "the editor's");
// The focus on another view of the overlay: Escape cancels again.
c.set_states(8, 0);
c.set_states(10, FOCUSED);
assert_eq!(escape_bound(&mut c), Some(true));
c.set_states(10, 0);
c.set_states(8, FOCUSED);
assert_eq!(escape_bound(&mut c), Some(false));
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::KeyCapture(KeyCapture::None),
}],
);
assert_eq!(escape_bound(&mut c), Some(true), "the rule dropped it");
// Back still cancels the overlay while the content takes Escape.
apply(
&mut c,
vec![Op::SetProp {
id: 6,
prop: Prop::KeyCapture(KeyCapture::All),
}],
);
assert_eq!(escape_bound(&mut c), Some(false));
js_events(&mut c);
assert!(c.overlay_cancel());
let events = js_events(&mut c);
assert!(
events.contains(&(4, EventKind::Cancel, EventPayload::None)),
"{events:?}"
);
}
#[test]
fn a_focus_outside_the_overlay_does_not_take_its_escape() {
use crate::{KeyCapture, keymap::Keystroke, tailwind::state::FOCUSED};
let mut c = core();
add(&mut c, 2, Tag::View, ROOT_ID, &[]);
add(&mut c, 4, Tag::Overlay, 2, &[]);
add(&mut c, 6, Tag::View, 4, &[]);
let escape = Keystroke::parse_with("escape", false).unwrap();
apply(
&mut c,
vec![
overlay_prop(
4,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
),
Op::Listen {
id: 4,
event: EventKind::Cancel,
enabled: true,
},
Op::SetProp {
id: 2,
prop: Prop::KeyCapture(KeyCapture::keys([escape])),
},
],
);
c.commit();
c.set_states(2, FOCUSED);
c.commit();
assert!(!c.focus_takes_escape());
}
mod by_name {
use super::*;
use crate::{
element::{ComponentElement, Registry, Root},
prelude::*,
};
#[component]
fn Later() -> impl IntoElement {
text("later")
}
#[component]
fn Page() -> impl IntoElement {
view()
.child(text("first"))
.child(ComponentElement::<Later>::named(()))
}
/// A component made by name shows nothing until a set registers it,
/// then it is made where it was mounted.
#[test]
fn a_component_made_by_name_is_made_when_its_set_registers_it() {
let mut c = core();
c.mount_root(&Root::new::<Page>(|| ()));
let batch = c.commit().unwrap();
assert_eq!(super::views::texts(&batch), ["first"]);
let mut registry = Registry::new();
registry.register::<Later>();
c.extend_components(registry);
let batch = c.commit().unwrap();
assert_eq!(super::views::texts(&batch), ["later"]);
}
/// Registered already (a native runtime): made at once.
#[test]
fn a_registered_component_made_by_name_is_made_at_once() {
let mut c = core();
let mut registry = Registry::new();
registry.register::<Later>();
c.set_components(registry);
c.mount_root(&Root::new::<Page>(|| ()));
let batch = c.commit().unwrap();
assert_eq!(super::views::texts(&batch), ["first", "later"]);
}
}
/// Resolved class style cache (`Core::resolved_styles`) equivalence, sharing,
/// invalidation, and mount/restyle benchmarks.
mod resolved_style_cache {
use std::time::Instant;
use serde_json::json;
use super::{Prop as NodeProp, *};
use crate::{
element::Registry,
platform::Appearance,
prelude::*,
tailwind::{ClassEnvironment, Platform, state},
};
#[derive(Clone, PartialEq, Props)]
struct StyledBoxProps {
#[prop(default)]
class: crate::element::Prop<Option<SharedString>>,
}
#[component]
fn StyledBox(props: StyledBoxProps) -> impl IntoElement {
view()
.bg(crate::element::palette::INDIGO.shade(500))
.p(px(8.0))
.app_class(props.class)
}
fn setup_core() -> Core<FakeEngine> {
let mut c = core();
let mut registry = Registry::new();
registry.register::<StyledBox>();
c.set_components(registry);
c.set_safe_area(crate::EdgeInsets {
top: px(12.0),
..Default::default()
});
c
}
fn node_snapshot(c: &Core<FakeEngine>, id: NodeId) -> Option<String> {
let key = c.key(id).ok()?;
let n = &c.nodes[key as usize];
let layout = n.layout.map(|l| c.layout.style(l));
Some(format!(
"{:?} | {:?}",
(
&n.view_style,
&n.text_style,
&n.paint,
&n.class_props,
&layout,
&n.base_layout,
&n.sticky,
),
(
n.wants_fixed,
n.rtl,
n.has_logical,
n.z_index,
n.vertical_align,
n.resting_fill,
n.frame,
n.direction,
n.object_fit,
n.child_perspective,
)
))
}
fn assert_cores_match(a: &mut Core<FakeEngine>, b: &mut Core<FakeEngine>, ids: &[NodeId]) {
let ba = a.commit();
let bb = b.commit();
match (ba, bb) {
(None, None) => {}
(Some(ba), Some(bb)) => {
assert_eq!(
format!("{:?}", ba.items),
format!("{:?}", bb.items),
"MountBatch items diverged"
);
}
(ba, bb) => panic!("MountBatch presence diverged: {ba:?} vs {bb:?}"),
}
for &id in ids {
assert_eq!(
node_snapshot(a, id),
node_snapshot(b, id),
"Node {id} state diverged"
);
}
}
fn apply_both(
cached: &mut Core<FakeEngine>,
uncached: &mut Core<FakeEngine>,
build_ops: impl Fn() -> Vec<Op>,
) {
apply(cached, build_ops());
for op in build_ops() {
uncached.apply(op).unwrap();
}
}
#[test]
fn resolved_class_style_cache_matches_uncached_resolution() {
let mut cached = setup_core();
let mut uncached = setup_core();
uncached.resolve_uncached = true;
// Build a diverse tree mixing shared Tailwind classes, bordered cards
// (`currentColor`), shadows/transforms (`Parts`), `!important`, logical
// properties, breakpoints, `w-screen`/`h-screen`, interactions, positional
// variants, `group`, `data-*`, `ch`, `space-y-*`, `env()`, `fixed`,
// `sticky`, `inline_style`, `Input`, and a Rust component with `app_class`.
let build_ops = || {
let mut ops = vec![
// Color-inheriting wrapper for `currentColor` borders.
Op::Create {
id: 2,
tag: Tag::View,
},
class_op(2, "p-2 text-red-600 dark:text-amber-300"),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// Repeated shared views & texts (hitting resolved_styles cache).
for i in 0..8 {
let card = 10 + i * 4;
let title = card + 1;
let raw = card + 2;
let badge = card + 3;
ops.extend([
Op::Create {
id: card,
tag: Tag::View,
},
class_op(
card,
"p-3 gap-2 rounded-s-lg ps-4 pe-2 ms-1 border bg-white dark:bg-zinc-900 shadow-sm hover:bg-blue-500 active:scale-95 focus:border-emerald-500 disabled:opacity-50 sm:w-40 md:px-6 rtl:bg-green-500",
),
Op::Create {
id: title,
tag: Tag::Text,
},
class_op(title, "text-sm font-semibold text-neutral-900 dark:text-white"),
Op::CreateText {
id: raw,
text: format!("Item {i}"),
},
Op::Create {
id: badge,
tag: Tag::View,
},
class_op(
badge,
"px-2 py-1 rounded border border-neutral-300 bg-neutral-100 !bg-amber-200 z-10",
),
Op::Insert {
parent: title,
child: raw,
before: None,
},
Op::Insert {
parent: card,
child: title,
before: None,
},
Op::Insert {
parent: card,
child: badge,
before: None,
},
Op::Insert {
parent: 2,
child: card,
before: None,
},
]);
}
// Positional container + children.
ops.extend([
Op::Create {
id: 100,
tag: Tag::View,
},
class_op(100, "flex-col gap-1"),
Op::Insert {
parent: ROOT_ID,
child: 100,
before: None,
},
]);
for i in 0..5 {
let row = 101 + i;
ops.extend([
Op::Create {
id: row,
tag: Tag::View,
},
class_op(
row,
"h-6 first:mt-2 last:mb-2 odd:bg-neutral-100 even:bg-white only:rounded-xl",
),
Op::Insert {
parent: 100,
child: row,
before: None,
},
]);
}
// Edge/excluded cases: `group`, `data-*`, `ch`, `space-y-*`, `env()`, `fixed`,
// `sticky`, `inline_style`, `Input`, and a Rust component.
ops.extend([
Op::Create {
id: 200,
tag: Tag::View,
},
class_op(200, "group space-y-2 p-2"),
Op::Insert {
parent: ROOT_ID,
child: 200,
before: None,
},
Op::Create {
id: 201,
tag: Tag::View,
},
class_op(
201,
"h-8 bg-white group-hover:bg-yellow-500 data-open:border-red-500 border",
),
Op::SetProp {
id: 201,
prop: NodeProp::ProjectedData(vec!["open"].into()),
},
Op::Insert {
parent: 200,
child: 201,
before: None,
},
Op::Create {
id: 202,
tag: Tag::View,
},
class_op(
202,
"max-w-prose pt-[env(safe-area-inset-top)] sticky top-4",
),
Op::Insert {
parent: 200,
child: 202,
before: None,
},
Op::Create {
id: 203,
tag: Tag::View,
},
class_op(
203,
"fixed bottom-2 right-2 w-screen h-screen bg-blue-500 !bg-emerald-500",
),
style_op(203, &[("backgroundColor", StyleValue::Str("#ff00ff"))]),
Op::Insert {
parent: ROOT_ID,
child: 203,
before: None,
},
Op::Create {
id: 204,
tag: Tag::Input,
},
class_op(204, "px-2 py-1 bg-white placeholder:text-neutral-400"),
Op::Insert {
parent: ROOT_ID,
child: 204,
before: None,
},
Op::Create {
id: 205,
tag: Tag::View,
},
Op::SetProp {
id: 205,
prop: NodeProp::Component(std::any::type_name::<StyledBox>().into()),
},
Op::SetProp {
id: 205,
prop: rust_prop::<StyledBoxProps>(
"class",
Some(json!("rounded-lg m-2 bg-rose-500")),
),
},
Op::Insert {
parent: ROOT_ID,
child: 205,
before: None,
},
]);
ops
};
let mut ids: Vec<NodeId> = vec![ROOT_ID, 2, 100, 200, 201, 202, 203, 204, 205];
for i in 0..8 {
let card = 10 + i * 4;
ids.extend([card, card + 1, card + 3]);
}
ids.extend(101..106);
apply_both(&mut cached, &mut uncached, build_ops);
assert_cores_match(&mut cached, &mut uncached, &ids);
// Toggle dark mode.
cached.set_appearance(Appearance::Dark);
uncached.set_appearance(Appearance::Dark);
assert_cores_match(&mut cached, &mut uncached, &ids);
// Resize across responsive breakpoints + w-screen/h-screen.
cached.set_viewport(size_pt(820.0, 500.0));
uncached.set_viewport(size_pt(820.0, 500.0));
assert_cores_match(&mut cached, &mut uncached, &ids);
// Flip RTL on root.
apply_both(&mut cached, &mut uncached, || {
vec![style_op(ROOT_ID, &[("direction", StyleValue::Str("rtl"))])]
});
assert_cores_match(&mut cached, &mut uncached, &ids);
// Toggle interaction & disabled states on shared views and group.
cached.set_states(10, state::HOVERED | state::PRESSED);
uncached.set_states(10, state::HOVERED | state::PRESSED);
cached.set_states(14, state::FOCUSED | state::DISABLED);
uncached.set_states(14, state::FOCUSED | state::DISABLED);
cached.set_states(200, state::HOVERED);
uncached.set_states(200, state::HOVERED);
assert_cores_match(&mut cached, &mut uncached, &ids);
// Switch inherited `currentColor` on wrapper `2`.
apply_both(&mut cached, &mut uncached, || {
vec![class_op(2, "p-2 text-blue-500")]
});
assert_cores_match(&mut cached, &mut uncached, &ids);
// Switch to light appearance + terminal cell layout to verify `resting_fill` matches.
cached.set_appearance(Appearance::Light);
uncached.set_appearance(Appearance::Light);
let env = crate::element::Environment {
cell: Some(size_pt(8.0, 16.0)),
..Default::default()
};
cached.set_environment(env);
uncached.set_environment(env);
cached.set_states(10, state::HOVERED);
uncached.set_states(10, state::HOVERED);
assert_cores_match(&mut cached, &mut uncached, &ids);
// Verify hovered shared card `10` keeps its resting background in `resting_fill`.
let k10 = cached.key(10).unwrap();
assert!(cached.nodes[k10 as usize].resting_fill.is_some());
// Switch back off terminal and update tokens + Tailwind theme.
let env_off = crate::element::Environment::default();
cached.set_environment(env_off);
uncached.set_environment(env_off);
let (tokens, _) = test_tokens(Some(r##"{"primary": "#123456"}"##)).unwrap();
cached.set_tokens(tokens.clone());
uncached.set_tokens(tokens);
assert_cores_match(&mut cached, &mut uncached, &ids);
cached.set_tailwind_theme("{}");
uncached.set_tailwind_theme("{}");
assert_cores_match(&mut cached, &mut uncached, &ids);
}
#[test]
fn repeated_classes_share_resolved_styles_and_layout_records() {
let mut c = setup_core();
// 7 distinct class strings (> `LayoutTree`'s `SHARED = 4` window),
// including bordered `currentColor`, shadow `Parts`, text styles, and a token class.
let classes = [
"p-4 gap-2 rounded-lg border border-neutral-200 bg-white",
"p-3 rounded-md border bg-white",
"text-base font-semibold text-neutral-950",
"flex-row items-center gap-3 px-4 py-2 shadow-sm",
"w-12 h-8 rounded bg-neutral-100 hover:bg-neutral-200",
"ps-4 pe-2 rounded-s-md bg-blue-600",
"p-2 bg-primary text-white",
];
let mut ops = Vec::new();
for i in 0..70 {
let id = 10 + i as NodeId;
ops.extend([
Op::Create { id, tag: Tag::View },
class_op(id, classes[i % classes.len()]),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]);
}
apply(&mut c, ops);
let _ = c.commit();
assert_eq!(c.resolved_styles.len(), classes.len());
// Nodes cycling through > 4 distinct styles still share exact `Rc` records.
for offset in 0..classes.len() {
let k0 = c.key(10 + offset as NodeId).unwrap();
let k1 = c.key(10 + (offset + classes.len()) as NodeId).unwrap();
let n0 = &c.nodes[k0 as usize];
let n1 = &c.nodes[k1 as usize];
assert!(std::ptr::eq(
c.layout.style(n0.layout.unwrap()),
c.layout.style(n1.layout.unwrap())
));
assert!(super::opt_rc_eq(
n0.view_style.0.as_ref(),
n1.view_style.0.as_ref()
));
assert!(super::opt_rc_eq(
n0.text_style.0.as_ref(),
n1.text_style.0.as_ref()
));
assert!(super::opt_rc_eq(
n0.class_props.as_ref(),
n1.class_props.as_ref()
));
}
let token_node = c.key(16).unwrap();
let plain_node = c.key(10).unwrap();
let token_view_before = c.nodes[token_node as usize].view_style.0.clone().unwrap();
let plain_view_before = c.nodes[plain_node as usize].view_style.0.clone().unwrap();
// Value-only token change evicts only token-dependent cache entries (`bg-primary`),
// restyling those nodes with a fresh `Rc` while keeping non-token entries shared.
let (tokens, _) = test_tokens(Some(r##"{"primary": "#abcdef"}"##)).unwrap();
c.set_tokens(tokens);
assert_eq!(c.resolved_styles.len(), classes.len());
let token_view_after = c.nodes[token_node as usize].view_style.0.as_ref().unwrap();
let plain_view_after = c.nodes[plain_node as usize].view_style.0.as_ref().unwrap();
assert!(!std::rc::Rc::ptr_eq(&token_view_before, token_view_after));
assert!(std::rc::Rc::ptr_eq(&plain_view_before, plain_view_after));
// Replacing the Tailwind theme clears the full cache and restyles every node.
c.set_tailwind_theme("{}");
assert_eq!(c.resolved_styles.len(), classes.len());
let plain_view_themed = c.nodes[plain_node as usize].view_style.0.as_ref().unwrap();
assert!(!std::rc::Rc::ptr_eq(&plain_view_before, plain_view_themed));
// Changing platform clears `resolved_styles`. None of these classes use
// platform variants, so nothing needs restyling and entries rebuild only
// lazily; the nodes' existing (platform-independent) styles stay valid.
let pre_platform = c.nodes[plain_node as usize].view_style.0.clone();
c.set_class_environment(ClassEnvironment {
platform: Platform::Android,
..Default::default()
});
let plain_view_platform = c.nodes[plain_node as usize].view_style.0.as_ref().unwrap();
assert!(std::rc::Rc::ptr_eq(
pre_platform.as_ref().unwrap(),
plain_view_platform
));
}
#[test]
fn platform_only_classes_restyle_when_platform_changes() {
let mut c = setup_core();
// The view style a batch last mounts on `id`, if any: the core's
// observable output rather than its internal bookkeeping.
let mounted_bg = |batch: &crate::mount::MountBatch, id: NodeId| {
batch.items.iter().rev().find_map(|item| match item {
crate::mount::MountItem::ViewStyle { id: x, style } if *x == id => {
Some(style.background_color)
}
_ => None,
})
};
apply(
&mut c,
vec![
Op::Create {
id: 10,
tag: Tag::View,
},
class_op(10, "ios:bg-red-500"),
Op::Create {
id: 11,
tag: Tag::View,
},
class_op(11, "android:bg-blue-500 ios:dark:bg-green-500"),
Op::Insert {
parent: ROOT_ID,
child: 10,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 11,
before: None,
},
],
);
let batch = c.commit().unwrap();
// On iOS the `ios:` rule applies, the `android:` one does not.
assert!(mounted_bg(&batch, 10).is_some_and(|bg| bg != crate::style::Color::TRANSPARENT));
assert!(mounted_bg(&batch, 11).is_none_or(|bg| bg == crate::style::Color::TRANSPARENT));
c.set_class_environment(ClassEnvironment {
platform: Platform::Android,
..Default::default()
});
let batch = c
.commit()
.expect("the platform change must restyle both views");
// `ios:bg-red-500` unmounts its background, `android:bg-blue-500` mounts one:
// both are platform-only dependent classes, with no other dependency bits.
assert_eq!(
mounted_bg(&batch, 10),
Some(crate::style::Color::TRANSPARENT)
);
assert!(mounted_bg(&batch, 11).is_some_and(|bg| bg != crate::style::Color::TRANSPARENT));
}
/// Extended equivalence coverage beyond `resolved_class_style_cache_matches_uncached_resolution`:
/// combined variants, class-environment toggles (dark / motion / pointer /
/// terminal), orientation, transitions and keyframe animations, cached
/// `fixed` / `sticky` / perspective / object-fit / paint records, inline
/// text spans, interaction sequences, re-classing and class removal.
#[test]
fn resolved_class_style_cache_matches_uncached_extended() {
use crate::tailwind::Pointer;
let mut cached = setup_core();
let mut uncached = setup_core();
uncached.resolve_uncached = true;
let build_ops = || {
let mut ops = Vec::new();
// Combined variants, repeated 4x for cache hits.
for i in 0..4 {
let id = 300 + i;
ops.extend([
Op::Create { id, tag: Tag::View },
class_op(
id,
"p-1 sm:dark:hover:bg-red-500 dark:md:px-8 rtl:ms-4 \
motion-safe:transition-transform motion-reduce:transition-none \
landscape:p-4 portrait:p-2 pointer-coarse:m-2 pointer-fine:m-1 \
terminal:rounded-none",
),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]);
}
// Transitions / keyframe animations, repeated.
for i in 0..4 {
let id = 310 + i;
ops.extend([
Op::Create { id, tag: Tag::View },
class_op(
id,
"transition-transform duration-150 ease-out animate-pulse p-2 bg-white",
),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]);
}
// Cached (no inline style) fixed / sticky / perspective / object-fit / paint.
for (id, cls, tag) in [
(320, "fixed bottom-0 right-2 p-2 bg-blue-500", Tag::View),
(321, "fixed bottom-0 right-2 p-2 bg-blue-500", Tag::View),
(322, "sticky top-4 bg-white z-10 p-1", Tag::View),
(323, "sticky top-4 bg-white z-10 p-1", Tag::View),
(324, "perspective-normal p-2", Tag::View),
(325, "perspective-normal p-2", Tag::View),
(330, "object-cover w-10 h-10", Tag::Image),
(331, "object-cover w-10 h-10", Tag::Image),
(340, "fill-red-500 stroke-blue-500 w-8 h-8", Tag::Canvas),
(341, "fill-red-500 stroke-blue-500 w-8 h-8", Tag::Canvas),
] {
ops.extend([
Op::Create { id, tag },
class_op(id, cls),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]);
}
// Inline text spans with vertical alignment.
ops.extend([
Op::Create {
id: 350,
tag: Tag::Text,
},
class_op(350, "text-base text-neutral-900"),
Op::Create {
id: 351,
tag: Tag::Text,
},
class_op(351, "align-middle text-red-500 bg-amber-100"),
Op::CreateText {
id: 352,
text: "middle".into(),
},
Op::Create {
id: 353,
tag: Tag::Text,
},
class_op(353, "align-text-top text-blue-500"),
Op::CreateText {
id: 354,
text: "top".into(),
},
Op::Insert {
parent: 351,
child: 352,
before: None,
},
Op::Insert {
parent: 353,
child: 354,
before: None,
},
Op::Insert {
parent: 350,
child: 351,
before: None,
},
Op::Insert {
parent: 350,
child: 353,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 350,
before: None,
},
]);
// Positional + interaction combinations.
ops.extend([
Op::Create {
id: 365,
tag: Tag::View,
},
class_op(365, "flex-col"),
Op::Insert {
parent: ROOT_ID,
child: 365,
before: None,
},
]);
for i in 0..5 {
let row = 360 + i;
ops.extend([
Op::Create {
id: row,
tag: Tag::View,
},
class_op(
row,
"h-5 first:bg-red-100 odd:hover:bg-blue-100 even:active:bg-green-100",
),
Op::Insert {
parent: 365,
child: row,
before: None,
},
]);
}
ops
};
let mut ids: Vec<NodeId> = vec![ROOT_ID, 350, 351, 353, 365];
ids.extend(300..304);
ids.extend(310..314);
ids.extend([320, 321, 322, 323, 324, 325, 330, 331, 340, 341]);
ids.extend(360..365);
let env =
|dark: bool, reduce_motion: bool, pointer: Pointer, terminal: bool| ClassEnvironment {
dark,
platform: Platform::Ios,
reduce_motion,
pointer,
terminal,
};
apply_both(&mut cached, &mut uncached, build_ops);
assert_cores_match(&mut cached, &mut uncached, &ids);
// Dark, reduce-motion, fine pointer, terminal — one at a time, then combined.
for e in [
env(true, false, Pointer::Coarse, false),
env(true, true, Pointer::Coarse, false),
env(true, true, Pointer::Fine, false),
env(true, true, Pointer::Fine, true),
env(false, false, Pointer::Coarse, false),
] {
cached.set_class_environment(e);
uncached.set_class_environment(e);
assert_cores_match(&mut cached, &mut uncached, &ids);
}
// Orientation + breakpoint crossings.
for viewport in [
size_pt(500.0, 1000.0),
size_pt(900.0, 600.0),
size_pt(400.0, 800.0),
] {
cached.set_viewport(viewport);
uncached.set_viewport(viewport);
assert_cores_match(&mut cached, &mut uncached, &ids);
}
// Interaction sequences: hover, hover+press, release, and row positional states.
for states in [state::HOVERED, state::HOVERED | state::PRESSED, 0] {
cached.set_states(300, states);
uncached.set_states(300, states);
cached.set_states(361, states);
uncached.set_states(361, states);
cached.set_states(362, states);
uncached.set_states(362, states);
assert_cores_match(&mut cached, &mut uncached, &ids);
}
// RTL flip on root, then back.
apply_both(&mut cached, &mut uncached, || {
vec![style_op(ROOT_ID, &[("direction", StyleValue::Str("rtl"))])]
});
assert_cores_match(&mut cached, &mut uncached, &ids);
apply_both(&mut cached, &mut uncached, || {
vec![style_op(ROOT_ID, &[("direction", StyleValue::Str("ltr"))])]
});
assert_cores_match(&mut cached, &mut uncached, &ids);
// Re-class a cached node to a different class, then remove its classes.
apply_both(&mut cached, &mut uncached, || {
vec![class_op(300, "p-8 bg-emerald-500 rounded-full")]
});
assert_cores_match(&mut cached, &mut uncached, &ids);
apply_both(&mut cached, &mut uncached, || vec![class_op(300, "")]);
assert_cores_match(&mut cached, &mut uncached, &ids);
}
/// Filling `resolved_styles` past its 4096-entry bound clears it; resolution
/// must stay equivalent across evictions, and previously hot shared classes
/// must still resolve correctly afterwards.
#[test]
fn resolved_cache_eviction_preserves_equivalence() {
let mut cached = setup_core();
let mut uncached = setup_core();
uncached.resolve_uncached = true;
let build_base = || {
let mut ops = Vec::new();
for i in 0..4 {
let id = 10 + i;
ops.extend([
Op::Create { id, tag: Tag::View },
class_op(id, "h-4"),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]);
}
// A hot shared class that eviction will drop again and again.
ops.extend([
Op::Create {
id: 20,
tag: Tag::View,
},
class_op(20, "p-4 bg-white rounded border"),
Op::Insert {
parent: ROOT_ID,
child: 20,
before: None,
},
]);
ops
};
let ids: Vec<NodeId> = vec![ROOT_ID, 10, 11, 12, 13, 20];
apply_both(&mut cached, &mut uncached, build_base);
assert_cores_match(&mut cached, &mut uncached, &ids);
for round in 0..4300u32 {
let id = 10 + (round % 4) as NodeId;
let unique = round / 4;
apply_both(&mut cached, &mut uncached, || {
vec![class_op(id, &format!("w-[{unique}px] h-4"))]
});
// Node 20 alternates between two shared classes so its entries are
// re-created after every eviction.
if round % 16 == 0 {
apply_both(&mut cached, &mut uncached, || {
vec![class_op(
20,
if round % 32 == 0 {
"p-4 bg-white rounded border"
} else {
"p-4 bg-neutral-100 rounded"
},
)]
});
}
if round == 2048 {
assert_cores_match(&mut cached, &mut uncached, &ids);
}
}
assert!(cached.resolved_styles.len() <= super::classes::RESOLVED_STYLE_CACHE);
assert_cores_match(&mut cached, &mut uncached, &ids);
}
/// `cargo test --release -p nsh-core --lib bench_tailwind_class_mount -- --ignored --nocapture`:
/// compares shared-class mounts, 0%-cache-hit unique-class control mounts,
/// and appearance restyles on shared bordered views.
#[test]
#[ignore]
fn bench_tailwind_class_mount() {
let repeated_classes = [
"p-4 gap-2 rounded-lg border border-neutral-200 bg-white dark:bg-zinc-900",
"flex-row items-center justify-between gap-2 px-3 py-2 bg-neutral-100 rounded-md",
"text-base font-semibold text-neutral-950 dark:text-white",
"px-2 py-1 rounded bg-blue-600 text-white shadow-sm",
"p-2 gap-1 rounded border border-neutral-300 bg-white",
"flex-1 gap-1 px-3 py-2 bg-white rounded-md",
"text-xs text-neutral-500",
"h-10 px-4 rounded-lg bg-emerald-500 text-white",
"p-3 gap-2 rounded-xl border border-neutral-200 bg-neutral-50",
"flex-row gap-3 items-center py-2 px-3",
];
for count in [2_000usize, 10_000usize] {
let ops: Vec<Op> = (0..count)
.flat_map(|i| {
let id = 10 + i as NodeId;
[
Op::Create { id, tag: Tag::View },
class_op(id, repeated_classes[i % repeated_classes.len()]),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]
})
.collect();
let mut c = setup_core();
let t = Instant::now();
apply(&mut c, ops);
let batch = c.commit().unwrap();
let ms = t.elapsed().as_secs_f64() * 1e3;
println!(
"repeated {count:>6} views | {ms:>7.2} ms | {} mount items",
batch.items.len()
);
}
for count in [2_000usize, 10_000usize] {
let unique: Vec<String> = (0..count)
.map(|i| {
format!(
"w-[{}px] px-3 py-2 rounded-md border border-neutral-200 bg-white",
20 + (i % 4096) + (i / 4096) * 4096
)
})
.collect();
let ops: Vec<Op> = unique
.iter()
.enumerate()
.flat_map(|(i, cls)| {
let id = 10 + i as NodeId;
[
Op::Create { id, tag: Tag::View },
class_op(id, cls),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]
})
.collect();
let mut c = setup_core();
let t = Instant::now();
apply(&mut c, ops);
let batch = c.commit().unwrap();
let ms = t.elapsed().as_secs_f64() * 1e3;
println!(
"unique {count:>6} views | {ms:>7.2} ms | {} mount items",
batch.items.len()
);
}
// Restyling 5,000 shared views via dark-appearance toggles.
let count = 5_000usize;
let ops: Vec<Op> = (0..count)
.flat_map(|i| {
let id = 10 + i as NodeId;
[
Op::Create { id, tag: Tag::View },
class_op(id, repeated_classes[i % repeated_classes.len()]),
Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
},
]
})
.collect();
let mut c = setup_core();
apply(&mut c, ops);
let _ = c.commit();
let rounds = 20;
let t = Instant::now();
let mut total_items = 0usize;
for r in 0..rounds {
c.set_appearance(if r % 2 == 0 {
Appearance::Dark
} else {
Appearance::Light
});
total_items += c.commit().map_or(0, |b| b.items.len());
}
let ms = t.elapsed().as_secs_f64() * 1e3 / rounds as f64;
println!(
"restyle_dark {count} views | {ms:>7.2} ms/toggle | {} mount items/toggle",
total_items / rounds
);
}
}
/// `allowNavigation` reaches the web view's backend as host patterns, and
/// a list with a pattern that does not read is refused with a message and
/// leaves the web view not narrowed.
#[test]
fn allow_navigation_reaches_the_web_view() {
let narrowed = |hosts: &[&str]| {
let mut c = core();
c.set_access(Arc::new(crate::access::Access {
declared: crate::access::Capabilities::from_json(
&serde_json::json!({ "webview": { "hosts": ["*"] } }),
)
.unwrap(),
granted: None,
}));
let prop = Prop::Native(NativeProp::AllowNavigation(Some(
hosts.iter().map(|h| Arc::<str>::from(*h)).collect(),
)));
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::WebView,
},
Op::SetProp { id: 2, prop },
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
let batch = c.commit().unwrap();
let hosts = batch.items.iter().rev().find_map(|i| match i {
MountItem::NativeProps {
id: 2,
props: crate::NativeProps::WebView(p),
} => Some(p.allow_navigation.clone()),
_ => None,
});
(hosts.flatten(), c.denied.clone())
};
let (hosts, denied) = narrowed(&["127.0.0.1", "*.localhost"]);
let hosts = hosts.expect("narrowed");
assert!(hosts.allows("http://127.0.0.1:8001/"));
assert!(!hosts.allows("http://127.0.0.1:8002.evil.test/"));
assert!(denied.is_empty(), "{denied:?}");
let (hosts, denied) = narrowed(&["http://127.0.0.1:*"]);
assert!(hosts.is_none());
assert!(
denied.iter().any(|m| m.starts_with("`allowNavigation`")),
"{denied:?}"
);
}
/// A tab bar (a horizontal scroll view) that gets 60 tabs in one turn,
/// past the 45 it has: every tab's views are made within a few display
/// frames, the turns between them making none (NsVim's `nsvim *.rs`).
#[test]
fn a_tab_bar_makes_every_tab_added_in_one_turn_over_frames() {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::Scroll,
},
Op::SetProp {
id: 2,
prop: Prop::Horizontal(true),
},
style_op(2, &[("height", StyleValue::Number(30.0))]),
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
];
// A tab: a row of an icon, a label and a close button, narrow enough
// for all 105 to be in content culling's window (a viewport past the
// bar's), so pacing alone holds them back.
let tab = |ops: &mut Vec<Op>, i: u32| {
let id = 1000 + i * 10;
ops.extend(child_view(
id,
2,
30.0,
&[
("width", StyleValue::Number(6.0)),
("flexDirection", StyleValue::Str("row")),
],
));
for (n, w) in [1.0, 4.0, 1.0].into_iter().enumerate() {
ops.extend(child_view(
id + 1 + n as u32,
id,
30.0,
&[("width", StyleValue::Number(w))],
));
}
};
for i in 0..45 {
tab(&mut ops, i);
}
apply(&mut c, ops);
let mut made = Vec::new();
let frame = |c: &mut Core<FakeEngine>, made: &mut Vec<NodeId>| {
// A turn between two frames (a timer), then the frame's.
c.begin_mount_turn();
c.hold_paced_mounts();
if let Some(batch) = c.commit() {
made.extend(created_in(&batch));
}
c.begin_mount_turn();
if let Some(batch) = c.commit() {
made.extend(created_in(&batch));
}
};
for _ in 0..20 {
frame(&mut c, &mut made);
if !c.has_paced_mounts() {
break;
}
}
assert!(!c.has_paced_mounts());
assert_eq!(made.iter().filter(|&&id| id >= 1000).count(), 45 * 4);
let mut ops = Vec::new();
for i in 45..105 {
tab(&mut ops, i);
}
apply(&mut c, ops);
let mut frames = 0;
loop {
frame(&mut c, &mut made);
frames += 1;
if !c.has_paced_mounts() {
break;
}
assert!(frames < 40, "still waiting after {frames} frames");
}
assert!(frames > 1, "the tabs were paced over frames ({frames})");
for i in 0..105u32 {
for n in 0..4 {
let id = 1000 + i * 10 + n;
assert!(made.contains(&id), "tab {i} view {n} was never made");
}
}
}
/// `cargo test -p nsh-core --release bench_measure_list_row -- --ignored --nocapture`
///
/// The coordinate conversion of a row inside a virtualized list, once with
/// no scrolls in flight and once with an instant scroll's report still
/// outstanding. Compile it on both sides of a measurement change and
/// alternate the runs.
#[test]
#[ignore]
fn bench_measure_list_row() {
use std::{hint::black_box, time::Instant};
let mut c = core();
apply(
&mut c,
vec![
Op::Create {
id: 2,
tag: Tag::List,
},
style_op(2, &[("flexGrow", StyleValue::Number(1.0))]),
Op::SetProp {
id: 2,
prop: Prop::EstimatedItemSize(px(50.0)),
},
Op::SetProp {
id: 2,
prop: Prop::FollowEnd(Some(px(80.0)), false),
},
Op::SetProp {
id: 2,
prop: Prop::Count(100),
},
Op::Insert {
parent: ROOT_ID,
child: 2,
before: None,
},
],
);
c.commit();
let (mut next_id, mut cells) = (100, Vec::new());
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
c.commit();
c.apply(Op::Command {
id: 2,
command: Command::ScrollToEnd { animated: false },
})
.unwrap();
let mut at = scrolled(&c.commit().unwrap(), 0.0);
for _ in 0..4 {
render_binds(&mut c, &mut next_id, &mut cells, 50.0);
if let Some(batch) = c.commit() {
at = scrolled(&batch, at);
}
}
c.set_scroll_offset(2, point(px(0.0), px(at)), u32::MAX);
c.commit();
let last = *cells
.iter()
.max_by(|&&a, &&b| {
let y = |id| c.nodes[c.key(id).unwrap() as usize].frame.origin.y.0;
y(a).total_cmp(&y(b))
})
.unwrap();
assert!(c.measure(last).is_some(), "the row is placed");
let iterations = 200_000u32;
let run = |c: &Core<FakeEngine>, label: &str| {
let mut samples = [std::time::Duration::ZERO; 7];
for sample in &mut samples {
let start = Instant::now();
for _ in 0..iterations {
black_box(black_box(c).measure(black_box(last)));
}
*sample = start.elapsed() / iterations;
}
samples.sort_unstable();
eprintln!(
"measure {label}: min / median {} / {} ns",
samples[0].as_nanos(),
samples[3].as_nanos(),
);
};
// Steady state: every scroll's report is in, nothing pending.
run(&c, "settled");
// An instant scroll whose report is still in flight: the window the
// shown-offset pipeline serves.
c.apply(Op::Command {
id: 2,
command: Command::ScrollTo {
x: px(0.0),
y: px(0.0),
animated: false,
},
})
.unwrap();
c.commit();
run(&c, "in-flight");
}
/// A `data:` image with no size in its style lays out at its own size, as an
/// asset does: the bytes are in hand, so their header gives the size. One
/// side set keeps the aspect ratio. (Native platforms had laid it out at
/// nothing; Omamail #545.)
#[test]
fn data_image_uses_the_size_in_its_bytes() {
// A 60×30 PNG's header, percent-encoded into a `data:` URI.
let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
png.extend(60u32.to_be_bytes());
png.extend(30u32.to_be_bytes());
png.extend([8, 6, 0, 0, 0, 0, 0, 0, 0]);
let uri: String = std::iter::once("data:image/png,".to_owned())
.chain(png.iter().map(|b| format!("%{b:02X}")))
.collect();
let source = || {
Prop::Source(Some(ImageSource {
uri: uri.as_str().into(),
..ImageSource::default()
}))
};
let mut c = core();
let mut ops = Vec::new();
// Unsized; a width; a max width narrower than the image; stretched to
// the column (320 points) within a max width.
for (id, align, side) in [
(2, "flex-start", None),
(3, "flex-start", Some(("width", 120.0))),
(4, "flex-start", Some(("maxWidth", 40.0))),
(5, "stretch", Some(("maxWidth", 100.0))),
] {
ops.push(Op::Create {
id,
tag: Tag::Image,
});
let mut style = vec![("alignSelf", StyleValue::Str(align))];
if let Some((prop, value)) = side {
style.push((prop, StyleValue::Number(value)));
}
ops.push(style_op(id, &style));
ops.push(Op::SetProp { id, prop: source() });
ops.push(Op::Insert {
parent: ROOT_ID,
child: id,
before: None,
});
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
assert_eq!(
frame_of(&batch, 2).map(|f| (f.size.width.0, f.size.height.0)),
Some((60.0, 30.0))
);
assert_eq!(
frame_of(&batch, 3).map(|f| (f.size.width.0, f.size.height.0)),
Some((120.0, 60.0))
);
assert_eq!(
frame_of(&batch, 4).map(|f| (f.size.width.0, f.size.height.0)),
Some((40.0, 20.0))
);
assert_eq!(
frame_of(&batch, 5).map(|f| (f.size.width.0, f.size.height.0)),
Some((100.0, 50.0))
);
}
#[test]
fn overlays_keep_the_snap_margin_from_the_window_unless_they_set_one() {
use StyleValue::Number;
let place = |margin: Option<f32>, snap: Option<f32>| {
let mut c = core();
if let Some(snap) = snap {
c.set_snap_to_window_margin(crate::geometry::px(snap));
}
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[("width", Number(20.0)), ("height", Number(20.0))],
);
add(&mut c, 8, Tag::Overlay, ROOT_ID, &[]);
add(
&mut c,
10,
Tag::View,
8,
&[("width", Number(40.0)), ("height", Number(30.0))],
);
let mut props = vec![overlay_prop(
8,
crate::OverlayProp::Anchor(crate::overlay::OverlayAnchor::Node(2)),
)];
if let Some(margin) = margin {
props.push(overlay_prop(
8,
crate::OverlayProp::Margin(crate::geometry::px(margin)),
));
}
apply(&mut c, props);
frame_of(&c.commit().unwrap(), 8).map(|f| f.origin.x.0)
};
// 8 points by default, the app's default, and an overlay's own margin.
assert_eq!(place(None, None), Some(8.0));
assert_eq!(place(None, Some(12.0)), Some(12.0));
assert_eq!(place(Some(0.0), Some(12.0)), Some(0.0));
}
/// A clipping parent (`overflow-hidden`, 200×100) holding a focusable view
/// with `classes`, placed by the parent's `padding`.
fn focus_ring_in_clip(classes: &str, padding: f32) -> Core<FakeEngine> {
let mut c = core();
add(
&mut c,
2,
Tag::View,
ROOT_ID,
&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(100.0)),
("padding", StyleValue::Number(padding)),
("overflow", StyleValue::Str("hidden")),
],
);
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::View,
},
class_op(3, classes),
Op::Insert {
parent: 2,
child: 3,
before: None,
},
],
);
c.commit().unwrap();
c
}
#[test]
fn a_focus_outline_a_clipping_parent_would_cut_is_drawn_inside() {
use crate::tailwind::state::FOCUSED;
let mut c = focus_ring_in_clip("w-full h-10 focus:outline-2 focus:outline-offset-1", 0.0);
c.set_states(3, FOCUSED);
let style = view_style_of(&c.commit().unwrap(), 3).unwrap();
assert_eq!(style.outline.width, px(2.0));
assert_eq!(style.outline.offset, px(-2.0));
// Without the focus there is no ring to move.
c.set_states(3, 0);
let style = view_style_of(&c.commit().unwrap(), 3).unwrap();
assert!(!style.outline.is_visible());
}
#[test]
fn a_focus_outline_with_room_stays_outside() {
use crate::tailwind::state::FOCUSED;
let mut c = focus_ring_in_clip("w-20 h-10 focus:outline-2 focus:outline-offset-1", 4.0);
c.set_states(3, FOCUSED);
let style = view_style_of(&c.commit().unwrap(), 3).unwrap();
assert_eq!(style.outline.offset, px(1.0));
}
#[test]
fn a_focus_outline_moves_inside_once_its_room_is_gone() {
use crate::tailwind::state::FOCUSED;
let mut c = focus_ring_in_clip("w-full h-10 focus:outline-2", 4.0);
c.set_states(3, FOCUSED);
let style = view_style_of(&c.commit().unwrap(), 3).unwrap();
assert_eq!(style.outline.offset, px(0.0));
// The parent loses its padding: the field now touches the clip.
apply(
&mut c,
vec![style_op(
2,
&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(100.0)),
("padding", StyleValue::Number(0.0)),
("overflow", StyleValue::Str("hidden")),
],
)],
);
let style = view_style_of(&c.commit().unwrap(), 3).unwrap();
assert_eq!(style.outline.offset, px(-2.0));
}
#[test]
fn a_focus_ring_shadow_a_clipping_parent_would_cut_is_inset() {
use crate::tailwind::state::FOCUSED;
let mut c = focus_ring_in_clip("w-full h-10 shadow-md focus:ring-2", 0.0);
c.set_states(3, FOCUSED);
let style = view_style_of(&c.commit().unwrap(), 3).unwrap();
let shadows = &style.effects.as_ref().unwrap().box_shadows;
let rings: Vec<_> = shadows
.iter()
.filter(|s| s.spread == px(2.0) && s.blur == px(0.0))
.collect();
assert_eq!(rings.len(), 1);
assert!(rings[0].inset);
// The blurred drop shadow is not a ring and stays outside.
assert!(shadows.iter().any(|s| s.blur.0 > 0.0 && !s.inset));
}
#[test]
fn a_focus_ring_in_a_scroll_view_fits_its_content_not_its_viewport() {
use crate::tailwind::state::FOCUSED;
let mut c = core();
add(
&mut c,
2,
Tag::Scroll,
ROOT_ID,
&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(100.0)),
("padding", StyleValue::Number(4.0)),
],
);
// A field at the top of the content, with room, and one far below
// the viewport: scrolled out of sight, not clipped for good.
for id in [3, 4] {
apply(
&mut c,
vec![
Op::Create { id, tag: Tag::View },
class_op(id, "w-full h-40 focus:outline-2"),
Op::Insert {
parent: 2,
child: id,
before: None,
},
],
);
}
c.commit().unwrap();
c.set_states(4, FOCUSED);
let style = view_style_of(&c.commit().unwrap(), 4).unwrap();
assert_eq!(style.outline.offset, px(0.0));
// Without the padding the ring passes the content's edges.
apply(
&mut c,
vec![style_op(
2,
&[
("width", StyleValue::Number(200.0)),
("height", StyleValue::Number(100.0)),
("padding", StyleValue::Number(0.0)),
],
)],
);
let style = view_style_of(&c.commit().unwrap(), 4).unwrap();
assert_eq!(style.outline.offset, px(-2.0));
}
/// A bubble sized by its content in a 200pt column, holding wrapping text
/// above a horizontal scroll (or a plain view) of `wide` points: the frames
/// of the bubble and of the text (#4182).
fn widened_bubble(scroll: bool, wide: f32) -> (Bounds<Points>, Bounds<Points>) {
let mut c = core();
let mut ops = vec![
Op::Create {
id: 2,
tag: Tag::View,
},
style_op(
2,
&[
("maxWidth", StyleValue::Number(200.0)),
("alignItems", StyleValue::Str("flex-start")),
],
),
Op::Create {
id: 3,
tag: Tag::View,
},
style_op(3, &[("padding", StyleValue::Number(10.0))]),
Op::Create {
id: 4,
tag: Tag::Text,
},
Op::CreateText {
id: 5,
text: "x".repeat(50),
},
Op::Create {
id: 6,
tag: if scroll { Tag::Scroll } else { Tag::View },
},
Op::Create {
id: 7,
tag: Tag::View,
},
style_op(
7,
&[
("width", StyleValue::Number(wide)),
("height", StyleValue::Number(20.0)),
],
),
];
if scroll {
ops.push(Op::SetProp {
id: 6,
prop: Prop::Horizontal(true),
});
}
for (parent, child) in [(4, 5), (6, 7), (3, 4), (3, 6), (2, 3), (ROOT_ID, 2)] {
ops.push(Op::Insert {
parent,
child,
before: None,
});
}
apply(&mut c, ops);
let batch = c.commit().unwrap();
(frame_of(&batch, 3).unwrap(), frame_of(&batch, 4).unwrap())
}
#[test]
fn a_bubble_widened_by_its_content_is_as_tall_as_its_text_there() {
for scroll in [false, true] {
let (bubble, text) = widened_bubble(scroll, 300.0);
assert_eq!(
bubble.size.height.0,
text.size.height.0 + 20.0 + 20.0,
"scroll={scroll}"
);
}
}
/// A box shorter than its lines (#4205) keeps the lines that fit, the last
/// one cut as the text says, on every engine: the mounted text carries the
/// line limit the box makes.
#[test]
fn a_box_shorter_than_its_lines_keeps_the_lines_that_fit() {
// `(max_lines, ellipsize)` of a long wrapping text with `classes`.
fn laid(classes: &str) -> (u32, crate::EllipsizeMode) {
let mut c = Core::new(crate::ApproxTextEngine, size_pt(320.0, 480.0));
c.set_tokens(crate::element::tokens::sample());
apply(
&mut c,
vec![
Op::Create {
id: 3,
tag: Tag::Text,
},
class_op(3, classes),
Op::CreateText {
id: 4,
text: "The quick brown fox jumps over the lazy dog and keeps running far away"
.into(),
},
Op::Insert {
parent: 3,
child: 4,
before: None,
},
Op::Insert {
parent: ROOT_ID,
child: 3,
before: None,
},
],
);
let batch = c.commit().unwrap();
batch
.items
.iter()
.rev()
.find_map(|i| match i {
MountItem::Text { id: 3, text, .. } => Some((text.max_lines, text.ellipsize)),
_ => None,
})
.unwrap()
}
use crate::EllipsizeMode::{Clip, Tail};
// `h-10` holds one 24pt line of `text-base`.
assert_eq!(laid("self-start w-40 h-10 text-base"), (1, Tail));
assert_eq!(laid("self-start w-40 h-10 text-base text-clip"), (1, Clip));
assert_eq!(laid("self-start w-40 h-14 text-base"), (2, Tail));
// A smaller `numberOfLines` stays; a larger one is cut to the box.
assert_eq!(
laid("self-start w-40 h-14 text-base line-clamp-1"),
(1, Tail)
);
assert_eq!(
laid("self-start w-40 h-10 text-base line-clamp-3"),
(1, Tail)
);
// Room for every line, or lines that never wrap: no limit.
assert_eq!(laid("self-start w-40 text-base").0, 0);
assert_eq!(
laid("self-start w-40 h-10 text-base whitespace-nowrap").0,
0
);
}
/// Without a native header (desktop), a screen's drawn `header` is a view
/// in its screen: a view in it is measured from the window, with the
/// offset of whatever is beside the stack, so an overlay anchored to it
/// opens at the view (#4227).
#[test]
fn a_view_in_a_drawn_header_is_measured_from_the_window() {
let mut c = core();
c.set_header_heights(crate::NO_NATIVE_HEADER.0, crate::NO_NATIVE_HEADER.1);
let insert = |parent, child| Op::Insert {
parent,
child,
before: None,
};
apply(
&mut c,
vec![
Op::Create {
id: 30,
tag: Tag::View,
},
style_op(
30,
&[
("flex", StyleValue::Number(1.0)),
("flexDirection", StyleValue::Str("row")),
],
),
Op::Create {
id: 20,
tag: Tag::View,
},
style_op(20, &[("width", StyleValue::Number(224.0))]),
Op::Create {
id: 2,
tag: Tag::Stack,
},
style_op(2, &[("flex", StyleValue::Number(1.0))]),
Op::Create {
id: 3,
tag: Tag::Screen,
},
Op::Create {
id: 4,
tag: Tag::HeaderItem,
},
Op::SetProp {
id: 4,
prop: Prop::HeaderSlot(crate::HeaderSlot::Header),
},
Op::Create {
id: 6,
tag: Tag::View,
},
style_op(
6,
&[
("flexDirection", StyleValue::Str("row")),
("justifyContent", StyleValue::Str("flex-end")),
("height", StyleValue::Number(44.0)),
],
),
Op::Create {
id: 8,
tag: Tag::View,
},
style_op(
8,
&[
("width", StyleValue::Number(28.0)),
("height", StyleValue::Number(28.0)),
],
),
Op::Create {
id: 16,
tag: Tag::View,
},
style_op(16, &[("flex", StyleValue::Number(1.0))]),
insert(6, 8),
insert(4, 6),
insert(3, 4),
insert(3, 16),
insert(2, 3),
insert(30, 20),
insert(30, 2),
insert(ROOT_ID, 30),
],
);
c.set_viewport(size_pt(1024.0, 480.0));
c.commit().unwrap();
let m = c.measure(8).expect("laid out");
assert_eq!(m.page.x.0, 1024.0 - 28.0);
assert_eq!(m.page.y.0, 0.0);
}