From 50f3ff211c220ea14b994024a36ad323de4ae7df Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 05:44:40 +0100 Subject: [PATCH] input: Pointer, Seen, Owners, Input::event and hit_test are crate-private; the pointer tests that need them live in the crate Finding public-surface-and-scale-rule-twice (surface half). hit_test, Hit and HitKind had no consumer inside the crate and are deleted; Input, Seen and Owners are pub(crate), Pointer private, hit and pointer modules private. The Rig tests (hit-testing, press state, the wheel, drafts) moved to src/input/tests.rs with three small doubles (Port, Counter, Boxes), because thing-testkit's types name the library build of thing-core, not the test build. The Core::frame tests stay in tests/input.rs. The contract documents both share are tests/support/mod.rs. The F03, F01/F05/F06 and F04 fixtures the Rig tests loaded are replaced by documents built in tests/support (a target on a board, the shared surfaces, a Select and a TextInput); no feature flag, no doc(hidden). Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/input/hit.rs | 34 +- crates/thing-core/src/input/mod.rs | 10 +- crates/thing-core/src/input/pointer.rs | 38 +- crates/thing-core/src/input/tests.rs | 960 +++++++++++++++++++++++++ crates/thing-core/tests/input.rs | 959 +----------------------- crates/thing-core/tests/support/mod.rs | 189 +++++ 6 files changed, 1214 insertions(+), 976 deletions(-) create mode 100644 crates/thing-core/src/input/tests.rs create mode 100644 crates/thing-core/tests/support/mod.rs diff --git a/crates/thing-core/src/input/hit.rs b/crates/thing-core/src/input/hit.rs index ab634c7..e114275 100644 --- a/crates/thing-core/src/input/hit.rs +++ b/crates/thing-core/src/input/hit.rs @@ -12,24 +12,9 @@ use thing_contract::{Node, NodeId}; use crate::layout::{LaidTree, Rect}; use crate::render::Rendered; -/// What the topmost thing under a point is: a node, or a modal overlay's scrim (the viewport -/// beyond everything the modal holds). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum HitKind { - Node, - Scrim, -} - -/// The topmost thing under a point. For a `Scrim` the node is the modal overlay. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Hit { - pub node: NodeId, - pub kind: HitKind, -} - /// What a press can activate: a control, or a modal's scrim (its dismissal). #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Control { +pub(super) enum Control { Button, Toggle, Slider, @@ -39,9 +24,9 @@ pub enum Control { } #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Target { - pub node: NodeId, - pub control: Control, +pub(super) struct Target { + pub(super) node: NodeId, + pub(super) control: Control, } /// Where a point lands before any node is asked what it takes: the topmost node under it, or the @@ -87,15 +72,6 @@ pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeI } } -/// The topmost node drawn at `point` (a modal's scrim when nothing in the modal is there), read -/// from the last good frame: what the user saw when they pressed. -pub fn hit_test(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option { - Some(match reach(rendered, laid, index, point, k)? { - Reach::Scrim(m) => Hit { node: laid.nodes[m].id.clone(), kind: HitKind::Scrim }, - Reach::Node(i) => Hit { node: laid.nodes[i].id.clone(), kind: HitKind::Node }, - }) -} - fn control_of(node: &Node) -> Option { match node { Node::Button(_) => Some(Control::Button), @@ -110,7 +86,7 @@ fn control_of(node: &Node) -> Option { /// The node `point` activates: the nearest activatable node at or above the topmost one under it /// (a Button's label hits the Button), or a modal's scrim. A point on a Box, on text outside a /// control or on a non-modal overlay's root targets nothing. -pub fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option { +pub(super) fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option { let mut at = match reach(rendered, laid, index, point, k)? { Reach::Scrim(m) => return Some(Target { node: laid.nodes[m].id.clone(), control: Control::Scrim }), Reach::Node(i) => Some(i), diff --git a/crates/thing-core/src/input/mod.rs b/crates/thing-core/src/input/mod.rs index 3cbdf59..ea8b60b 100644 --- a/crates/thing-core/src/input/mod.rs +++ b/crates/thing-core/src/input/mod.rs @@ -5,10 +5,12 @@ pub mod drafts; pub mod event; -pub mod hit; -pub mod pointer; +mod hit; +mod pointer; + +#[cfg(test)] +mod tests; pub use drafts::{Drafts, current}; pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; -pub use hit::{Control, Hit, HitKind, Target, hit_test, target}; -pub use pointer::{Input, Owners, Pointer, Seen}; +pub(crate) use pointer::{Input, Owners, Seen}; diff --git a/crates/thing-core/src/input/pointer.rs b/crates/thing-core/src/input/pointer.rs index 46e01ee..7bebfa2 100644 --- a/crates/thing-core/src/input/pointer.rs +++ b/crates/thing-core/src/input/pointer.rs @@ -16,16 +16,16 @@ use crate::render::{Rendered, ScrollOffsets, clamp, device_scale}; use crate::time::Timestamp; /// The last good frame and how it was drawn: what every event is judged against. -pub struct Seen<'a> { - pub rendered: &'a Rendered, - pub laid: &'a LaidTree, - pub tree: &'a BoundTree, - pub metrics: Metrics, +pub(crate) struct Seen<'a> { + pub(crate) rendered: &'a Rendered, + pub(crate) laid: &'a LaidTree, + pub(crate) tree: &'a BoundTree, + pub(crate) metrics: Metrics, /// Device px per logical px (Pixels), which turns a wheel's logical units into the device px /// scroll offsets are held in. - pub scale: f32, + pub(crate) scale: f32, /// The theme's body text size in logical px: what one wheel line is in Pixels. A guess, unmeasured. - pub line: f32, + pub(crate) line: f32, } impl Seen<'_> { @@ -36,13 +36,13 @@ impl Seen<'_> { } /// The owners an event writes through: activation, drafts and scroll positions. -pub struct Owners<'a> { - pub commands: &'a mut Commands, - pub drafts: &'a mut Drafts, - pub scroll: &'a mut ScrollOffsets, - pub ids: &'a mut dyn IdSource, - pub port: &'a mut dyn StatePort, - pub ledger: &'a mut Ledger, +pub(crate) struct Owners<'a> { + pub(crate) commands: &'a mut Commands, + pub(crate) drafts: &'a mut Drafts, + pub(crate) scroll: &'a mut ScrollOffsets, + pub(crate) ids: &'a mut dyn IdSource, + pub(crate) port: &'a mut dyn StatePort, + pub(crate) ledger: &'a mut Ledger, } /// The one press in progress. A Slider's press also holds the draft it replaced, so a cancel can put it back. @@ -54,13 +54,13 @@ enum Press { /// The owner of press state. No node holds a pressed or hover flag. #[derive(Clone, Debug, Default, PartialEq)] -pub struct Pointer { +struct Pointer { press: Option, } /// The routes every pointer and wheel event takes; it owns the `Pointer`. #[derive(Clone, Debug, Default, PartialEq)] -pub struct Input { +pub(crate) struct Input { pointer: Pointer, } @@ -81,13 +81,13 @@ fn placed_rect(rendered: &Rendered, node: &NodeId) -> Option { } impl Input { - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self::default() } /// Drop the press in progress, as the platform taking the pointer does, and as leaving the /// surface does: a Slider draft the press wrote goes back to what it was. - pub fn cancel(&mut self, surface: &str, drafts: &mut Drafts) { + pub(crate) fn cancel(&mut self, surface: &str, drafts: &mut Drafts) { if let Some(Press::Drag { node, prior }) = self.pointer.press.take() { drafts.restore(surface, &node, prior); } @@ -95,7 +95,7 @@ impl Input { /// Route one event. Keys, text, composition and the window gaining or losing the user are not pointer input and change nothing, /// and only the primary button presses. The diagnostics are the activations' refusals. - pub fn event(&mut self, event: &InputEvent, seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp) -> Vec { + pub(crate) fn event(&mut self, event: &InputEvent, seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp) -> Vec { let surface = seen.tree.resolved().document().record_key(); match event { InputEvent::PointerDown { at, button: PointerButton::Primary, .. } => return self.down(*at, seen, owners, &surface), diff --git a/crates/thing-core/src/input/tests.rs b/crates/thing-core/src/input/tests.rs new file mode 100644 index 0000000..21ab1ca --- /dev/null +++ b/crates/thing-core/src/input/tests.rs @@ -0,0 +1,960 @@ +//! Pointer input: a press, a drag and a wheel reach the node the user saw drawn, in Pixels (at several +//! scales) and in Cells, and end in the one activation primitive, in drafts or in scroll offsets. +//! Hit-testing reads the geometry render placed, so every test derives its points from `Placed` +//! and never from authored numbers. These tests live in the crate because `Input`, `Seen` and `Owners` +//! are not public; for the same reason they cannot use `thing-testkit`'s state port (its types name the +//! library build of this crate, not this test build), so `Port`, `Counter` and `Boxes` below are the three +//! small doubles they need. The contract documents they press are `tests/support`, shared with the host tests. + +use std::collections::HashMap; + +use thing_contract::*; +use thing_testkit::build::*; + +use super::hit::{Reach, Target, reach, target}; +use super::pointer::{Owners, Seen}; +use super::{Drafts, Input, InputEvent, Modifiers, PointerButton, WheelUnit}; +use crate::bind::{Binder, BoundTree, Instance}; +use crate::command::Commands; +use crate::diagnostic::{Code, Diagnostic}; +use crate::layout::{Constraint, LaidTree, LayoutFrame, Leaf, Measure, Metrics, Rect, TextLayout, TextRequest, layout}; +use crate::port::{Address, Change, Entry, IdSource, Interest, Ledger, Lookup, Prefix, Record, StatePort, StateValue, SubscriptionId}; +use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, render}; +use crate::resolve::{Limits, resolve}; +use crate::theme::Theme; +use crate::time::Timestamp; + +#[path = "../../tests/support/mod.rs"] +mod support; +use support::*; + +/// Records by address, the interests asked of the port and the changes queued for a drain. +#[derive(Clone, Default)] +struct Port { + records: HashMap, + interests: Vec<(SubscriptionId, Interest)>, + queue: Vec, +} + +impl Port { + fn new() -> Self { + Self::default() + } + + fn put(&mut self, provider: &ProviderId, document: &SurfaceDocument) { + let address = Address { provider: provider.clone(), schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key: RecordKey::new(document.record_key()) }; + self.records.insert(address.clone(), Entry { address, record: Record::Surface(document.clone()) }); + } + + fn put_item(&mut self, provider: &ProviderId, id: &str, title: &str) { + let address = Address { provider: provider.clone(), schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new(id) }; + let value = StateValue::Record(vec![("Id".into(), StateValue::Text(id.into())), ("Title".into(), StateValue::Text(title.into()))]); + let record = Record::State { schema: address.schema.clone(), value }; + self.records.insert(address.clone(), Entry { address, record }); + } +} + +impl StatePort for Port { + fn read(&self, address: &Address) -> Lookup { + self.records.get(address).map_or(Lookup::Absent, |entry| Lookup::Present(entry.clone())) + } + + fn list(&self, prefix: &Prefix) -> Vec { + let mut held: Vec<_> = self.records.values().filter(|entry| prefix.matches(&entry.address)).collect(); + held.sort_by(|a, b| a.address.key.as_str().cmp(b.address.key.as_str())); + held.into_iter().map(|entry| Lookup::Present(entry.clone())).collect() + } + + fn subscribe(&mut self, interest: Interest) -> SubscriptionId { + let id = SubscriptionId(self.interests.len() as u64); + self.interests.push((id, interest)); + id + } + + fn unsubscribe(&mut self, id: SubscriptionId) { + self.interests.retain(|(held, _)| *held != id); + } + + fn drain(&mut self) -> Vec { + std::mem::take(&mut self.queue) + } +} + +/// Ids that differ by a counter. +#[derive(Default)] +struct Counter(u128); + +impl IdSource for Counter { + fn fill(&mut self, bytes: &mut [u8; 16]) { + self.0 += 1; + *bytes = self.0.to_be_bytes(); + } +} + +/// Fixed control sizes and no text: these documents hold boxes and controls only. +struct Boxes { + cells: bool, +} + +impl Measure for Boxes { + fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) { + let control = |w: f32, h: f32| if self.cells { (w / 8.0, 1.0) } else { (w, h) }; + match leaf { + Leaf::TextInput { multiline, .. } => control(200.0, if *multiline { 72.0 } else { 24.0 }), + Leaf::Toggle { .. } => control(40.0, 20.0), + Leaf::Slider { .. } => control(160.0, 20.0), + Leaf::Select { .. } => control(160.0, 24.0), + Leaf::Text { .. } | Leaf::Image { .. } => (0.0, 0.0), + } + } + + fn text(&mut self, _: &TextRequest, _: f32) -> TextLayout { + TextLayout { lines: vec![] } + } +} + +/// Pixels at two scales, and Cells: the modes the pointer must agree with the laid geometry in. +const MODES: [(Metrics, f32); 3] = [(Metrics::Pixels, 1.0), (Metrics::Pixels, 1.5), (Metrics::Cells, 1.0)]; + +fn viewport(metrics: Metrics) -> (f32, f32) { + match metrics { + Metrics::Pixels => (400.0, 320.0), + Metrics::Cells => (50.0, 20.0), + } +} + +fn measure(metrics: Metrics) -> Boxes { + Boxes { cells: metrics == Metrics::Cells } +} + +fn row_id(item: &str, node: &str) -> NodeId { + NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false))) +} + +fn feed() -> Port { + let mut state = Port::new(); + for n in 0..20 { + let id = format!("item-{n:04}"); + state.put_item(&ProviderId::new(FEED), &id, &id); + } + state +} + +// ----- the rig: the stages composed by hand, with the owners input writes through ----- + +struct Rig { + tree: BoundTree, + laid: LaidTree, + rendered: Rendered, + metrics: Metrics, + scale: f32, + surface: String, + state: Port, + ledger: Ledger, + input: Input, + commands: Commands, + drafts: Drafts, + scroll: ScrollOffsets, + ids: Counter, + now: Timestamp, +} + +impl Rig { + fn new(mut state: Port, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Self { + state.put(&document.provider_id, document); + let limits = Limits::default(); + let resolved = resolve(document, &state, &limits).tree.expect("resolves"); + let mut ledger = Ledger::new(); + let mut binder = Binder::new(limits); + binder.bind(resolved, &mut state, &mut ledger); + let tree = binder.tree(&document.record_key()).expect("bound").clone(); + let mut rig = Self { + laid: LaidTree { nodes: vec![], diagnostics: vec![] }, + rendered: Rendered { commands: vec![], placed: vec![], diagnostics: vec![] }, + tree, + metrics, + scale, + surface: document.record_key(), + state, + ledger, + input: Input::new(), + commands: Commands::new("renderer.test", 15_000), + drafts: Drafts::new(), + scroll: ScrollOffsets::default(), + ids: Counter::default(), + now: Timestamp(0), + }; + rig.draw(); + rig + } + + fn frame(&self) -> LayoutFrame { + LayoutFrame { viewport: viewport(self.metrics), scale: self.scale, metrics: self.metrics } + } + + /// The frame the user sees: layout, then render over the scroll offsets, drafts and node states. + fn draw(&mut self) { + self.laid = layout(&self.tree, &self.frame(), &mut measure(self.metrics)).expect("lays out"); + let states = self.commands.view(&self.surface); + let theme = Theme::std(); + let input = RenderInput { + scale: self.scale, + metrics: self.metrics, + viewport: viewport(self.metrics), + scroll: &self.scroll, + theme: &theme, + session: Session::new(&self.drafts, &states), + }; + self.rendered = render(&self.tree, &self.laid, &input, &mut measure(self.metrics)); + } + + fn rect(&self, id: &str) -> Rect { + self.rendered.placed.iter().find(|placed| placed.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect + } + + fn send(&mut self, event: InputEvent) -> Vec { + let theme = Theme::std(); + let seen = Seen { rendered: &self.rendered, laid: &self.laid, tree: &self.tree, metrics: self.metrics, scale: self.scale, line: theme.text["body"].size }; + let mut owners = Owners { + commands: &mut self.commands, + drafts: &mut self.drafts, + scroll: &mut self.scroll, + ids: &mut self.ids, + port: &mut self.state, + ledger: &mut self.ledger, + }; + self.input.event(&event, &seen, &mut owners, self.now) + } + + fn click(&mut self, at: (f32, f32)) -> Vec { + let mut said = self.send(down(at)); + said.extend(self.send(up(at))); + said + } + + fn minted(&mut self) -> Vec { + self.commands.take_outbound() + } + + fn draft(&self, node: &str) -> Option { + self.drafts.get(&self.surface, &nid(node)).cloned() + } + + fn offset(&self, node: &str) -> Option<(f32, f32)> { + self.scroll.get(&nid(node)) + } + + fn max_scroll(&self, node: &str) -> (f32, f32) { + self.laid.nodes.iter().find(|laid| laid.id.as_str() == node).and_then(|laid| laid.max_scroll).expect("scrolls") + } +} + +fn mods() -> Modifiers { + Modifiers::default() +} + +fn down(at: (f32, f32)) -> InputEvent { + InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers: mods() } +} + +fn up(at: (f32, f32)) -> InputEvent { + InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers: mods() } +} + +fn mv(at: (f32, f32)) -> InputEvent { + InputEvent::PointerMove { at, modifiers: mods() } +} + +fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit) -> InputEvent { + InputEvent::Wheel { at, delta, unit, modifiers: mods() } +} + +/// The top-left cell (or, in Pixels, the half-pixel) of a rect: a point that is inside it in every mode. +fn inside(rect: Rect) -> (f32, f32) { + (rect.x + 0.5, rect.y + 0.5) +} + +fn commands_of(invocations: &[CommandInvocation]) -> Vec<&str> { + invocations.iter().map(|invocation| invocation.command.as_str()).collect() +} + +fn index_of(rig: &Rig) -> std::collections::HashMap<&NodeId, &Node> { + rig.tree.index() +} + +/// Device px per logical px, as input holds it. +fn device_k(rig: &Rig) -> f32 { + match rig.metrics { + Metrics::Pixels => rig.scale, + Metrics::Cells => 1.0, + } +} + +/// The node, or the modal whose scrim it is, that a point reaches. +fn hit_node(rig: &Rig, at: (f32, f32)) -> Option { + match reach(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig))? { + Reach::Node(i) | Reach::Scrim(i) => Some(rig.laid.nodes[i].id.as_str().to_string()), + } +} + +fn rig_target(rig: &Rig, at: (f32, f32)) -> Option { + target(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig)) +} + +// ----- hit-testing agrees with the laid geometry ----- + +#[test] +fn a_point_inside_the_absolute_target_hits_target_and_one_on_the_board_only_hits_board() { + for mode in MODES { + let rig = Rig::new(Port::new(), &target_surface(), mode); + let (target, board) = (rig.rect("target"), rig.rect("board")); + // The far corner of the target. + let corner = (target.x + target.w - 0.5, target.y + target.h - 0.5); + assert_eq!(hit_node(&rig, corner).as_deref(), Some("target"), "{mode:?}"); + assert_eq!(hit_node(&rig, inside(board)).as_deref(), Some("board"), "{mode:?}"); + assert!(target.x > board.x && target.y > board.y, "{mode:?}: the target stands inside the board, away from its corner"); + } +} + +#[test] +fn a_rect_is_half_open_so_a_shared_edge_belongs_to_the_second_node() { + for mode in MODES { + let rig = Rig::new(Port::new(), &surface(column("root", None, Overflow::Visible, vec![button("a", "x", 160.0, 48.0), button("b", "x", 160.0, 48.0)]), vec![decl("x", &[])]), mode); + let (a, b) = (rig.rect("a"), rig.rect("b")); + assert_eq!(a.y + a.h, b.y, "{mode:?}: the buttons touch"); + let edge = (a.x + 0.5, b.y); + assert!(rig_target(&rig, edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}"); + let last = (a.x + 0.5, b.y - 0.25); + assert!(rig_target(&rig, last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}"); + let under = (b.x + 0.5, b.y + b.h); + assert_eq!(rig_target(&rig, under), None, "{mode:?}: the bottom edge is outside"); + let beyond = (a.x + a.w, a.y + 0.5); + assert_ne!(rig_target(&rig, beyond).map(|hit| hit.node), Some(nid("a")), "{mode:?}: the right edge is outside"); + } +} + +#[test] +fn every_visible_node_is_reached_inside_its_own_visible_rect() { + let documents = [ + (modal_surface(), Port::new()), + (rows_surface(), feed()), + (controls_surface(), Port::new()), + (nested_surface(), Port::new()), + (clip_surface(), Port::new()), + (nonmodal_surface(Anchor::Viewport), Port::new()), + (target_surface(), Port::new()), + ]; + for mode in MODES { + for (document, state) in &documents { + let rig = Rig::new(state.clone(), document, mode); + for placed in &rig.rendered.placed { + let Some(seen) = placed.visible.filter(|r| r.w >= 1.0 && r.h >= 1.0) else { continue }; + let at = inside(seen); + let hit = hit_node(&rig, at).expect("something is there"); + let reached = rig.rendered.placed.iter().find(|p| p.id.as_str() == hit).unwrap(); + let within = reached.visible.is_some_and(|r| at.0 >= r.x && at.0 < r.x + r.w && at.1 >= r.y && at.1 < r.y + r.h); + assert!(within, "{mode:?} {}: {hit} reached at {at:?} is not drawn there", document.label.as_str()); + } + } + } +} + +#[test] +fn a_node_outside_its_clip_is_not_hit_where_its_rect_reaches_past_the_clip() { + for mode in MODES { + let rig = Rig::new(Port::new(), &clip_surface(), mode); + let (frame, tall) = (rig.rect("frame"), rig.rect("tall")); + assert!(tall.y + tall.h > frame.y + frame.h, "{mode:?}: the button runs past the clip"); + let below = (tall.x + 0.5, frame.y + frame.h + 0.5); + assert!(below.1 < tall.y + tall.h); + assert_eq!(rig_target(&rig, below), None, "{mode:?}"); + assert_ne!(hit_node(&rig, below).as_deref(), Some("tall"), "{mode:?}"); + // Inside the clip it is hit. + let inside_clip = rig_target(&rig, inside(frame)); + assert_eq!(inside_clip.map(|hit| hit.node.as_str().to_string()).as_deref(), Some("tall"), "{mode:?}"); + } +} + +// ----- the edge of a node, at a scale that does not divide ----- + +/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale. +fn seam_surface() -> SurfaceDocument { + let row = |id: &str, h: f64, widths: &[f64]| { + let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect()); + if let Node::Box(b) = &mut row { + b.style.direction = Direction::Row; + b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h)); + b.style.justify_content = ContentAlign::Start; + } + row + }; + surface( + column("root", None, Overflow::Visible, vec![ + row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]), + row("r1", 13.0, &[11.0, 3.0, 17.0]), + row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]), + row("r3", 19.0, &[23.0, 29.0, 13.0]), + ]), + vec![], + ) +} + +#[test] +fn the_first_device_pixel_past_a_nodes_right_or_bottom_edge_is_not_the_node_at_every_scale() { + let scales = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0]; + let modes = scales.map(|scale| (Metrics::Pixels, scale)).into_iter().chain([(Metrics::Cells, 1.0)]); + for mode in modes { + let rig = Rig::new(Port::new(), &seam_surface(), mode); + let k = device_k(&rig); + let mut leaves = 0; + for node in rig.laid.nodes.iter().filter(|node| node.id.as_str().contains('-')) { + leaves += 1; + let (id, r) = (node.id.as_str(), node.rect); + assert!(r.w >= 1.0 && r.h >= 1.0 && r.x.fract() == 0.0 && r.y.fract() == 0.0, "{mode:?} {id}: laid in whole device px, {r:?}"); + // Device pixels, as a host at this scale reports a pointer: the pixel's corner and its centre. + let at = |dx: f32, dy: f32, off: f32| ((dx + off) / k, (dy + off) / k); + for off in [0.0, 0.5] { + let last = at(r.x + r.w - 1.0, r.y + r.h - 1.0, off); + assert_eq!(hit_node(&rig, last).as_deref(), Some(id), "{mode:?} {id} the last pixel of the node, +{off}"); + let right = at(r.x + r.w, r.y, off); + assert_ne!(hit_node(&rig, right).as_deref(), Some(id), "{mode:?} {id} the pixel right of the node, +{off}"); + let below = at(r.x, r.y + r.h, off); + assert_ne!(hit_node(&rig, below).as_deref(), Some(id), "{mode:?} {id} the pixel below the node, +{off}"); + let first = at(r.x, r.y, off); + assert_eq!(hit_node(&rig, first).as_deref(), Some(id), "{mode:?} {id} the first pixel of the node, +{off}"); + } + } + assert_eq!(leaves, 15, "{mode:?}"); + } +} + +// ----- a non-modal overlay ----- + +fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument { + let pop = Node::Overlay(OverlayNode { common: common("pop"), anchor, modal: false, dismiss: command("dismiss"), children: vec![button("pop-button", "inside", 80.0, 48.0)] }); + surface( + column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), button("other", "other", 320.0, 48.0), pop]), + vec![decl("behind", &[]), decl("other", &[]), decl("inside", &[]), decl("dismiss", &[])], + ) +} + +#[test] +fn a_press_passes_through_a_non_modal_overlays_root_to_what_lies_beneath_and_its_own_content_still_takes_it() { + let node = Anchor::Node(AnchorNode { node: nid("behind") }); + for mode in MODES { + for anchor in [Anchor::Viewport, node.clone()] { + let mut rig = Rig::new(Port::new(), &nonmodal_surface(anchor.clone()), mode); + let (behind, other, inner) = (rig.rect("behind"), rig.rect("other"), rig.rect("pop-button")); + let (a, b) = ((behind.x + behind.w - 0.5, behind.y + 0.5), (other.x + other.w - 0.5, other.y + 0.5)); + for at in [a, b] { + assert!(!(at.0 >= inner.x && at.0 < inner.x + inner.w && at.1 >= inner.y && at.1 < inner.y + inner.h), "{mode:?} {anchor:?}: {at:?} is clear of the overlay's content"); + assert_eq!(hit_node(&rig, at).as_deref().map(|id| id != "pop"), Some(true), "{mode:?} {anchor:?}: the overlay's root is not what is hit at {at:?}"); + } + rig.click(a); + assert_eq!(commands_of(&rig.minted()), ["behind"], "{mode:?} {anchor:?}: the press reaches the anchor or the node under the viewport overlay"); + rig.click(b); + assert_eq!(commands_of(&rig.minted()), ["other"], "{mode:?} {anchor:?}"); + // The overlay's own content is drawn over them and takes its press. + rig.click(inside(inner)); + assert_eq!(commands_of(&rig.minted()), ["inside"], "{mode:?} {anchor:?}"); + } + } +} + +#[test] +fn a_wheel_over_a_non_modal_overlays_root_reaches_the_pane_beneath() { + let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]); + let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("pop", false, vec![fixed("pop-body", 8.0, 16.0)])]), vec![decl("dismiss", &[])]); + for mode in MODES { + let mut rig = Rig::new(Port::new(), &document, mode); + let pane = rig.rect("pane"); + rig.send(wheel((pane.x + pane.w - 0.5, pane.y + pane.h - 0.5), (0.0, 16.0), WheelUnit::Units)); + assert!(rig.offset("pane").is_some_and(|o| o.1 > 0.0), "{mode:?}"); + } +} + +// ----- the modal ----- + +#[test] +fn a_modal_confirms_inside_the_dialog_and_dismisses_outside_it_and_never_reaches_beneath() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &modal_surface(), mode); + // Inside the dialog: the confirm button. + rig.click(inside(rig.rect("confirm"))); + assert_eq!(commands_of(&rig.minted()), ["confirm"], "{mode:?}"); + // Over a main-tree button under the scrim: the scrim's dismissal, once, and not the button's command. + let behind = rig.rect("behind"); + rig.click((behind.x + behind.w - 0.5, behind.y + 0.5)); + assert_eq!(commands_of(&rig.minted()), ["dismiss"], "{mode:?}"); + // The dialog's own body is not the scrim: nothing. + let dialog = rig.rect("dialog"); + rig.click((dialog.x + dialog.w - 0.5, dialog.y + dialog.h - 0.5)); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + // The scrim is the whole viewport: a corner far from everything dismisses. + let (w, h) = viewport(mode.0); + let far = match mode.0 { + Metrics::Pixels => (w - 1.0, h - 1.0), + Metrics::Cells => (w - 0.5, h - 0.5), + }; + assert_eq!(hit_node(&rig, far).as_deref(), Some("modal"), "{mode:?}"); + // (The overlay that dismissed above still waits on its result, so it is silent: a fresh surface.) + let mut fresh = Rig::new(Port::new(), &modal_surface(), mode); + fresh.click(far); + assert_eq!(commands_of(&fresh.minted()), ["dismiss"], "{mode:?}"); + // And the same press again, while the first waits, mints nothing more. + fresh.click(far); + assert_eq!(fresh.minted(), vec![], "{mode:?}"); + } +} + +#[test] +fn a_press_on_the_scrim_released_on_a_button_activates_nothing() { + let mut rig = Rig::new(Port::new(), &modal_surface(), MODES[0]); + let behind = rig.rect("behind"); + let (scrim, confirm) = ((behind.x + behind.w - 0.5, behind.y + 0.5), inside(rig.rect("confirm"))); + rig.send(down(scrim)); + rig.send(up(confirm)); + assert_eq!(rig.minted(), vec![]); +} + +// ----- scroll ----- + +#[test] +fn a_click_hits_the_row_drawn_there_after_a_scroll_and_not_a_row_scrolled_out() { + for mode in MODES { + let mut rig = Rig::new(feed(), &rows_surface(), mode); + let (first, second) = (row_id("item-0000", "row"), row_id("item-0001", "row")); + let (r0, r1) = (rig.rect(first.as_str()), rig.rect(second.as_str())); + let step = r1.y - r0.y; + assert!(step > 0.0); + // At rest the click at row 0's corner is row 0, whose invocation names it in `items`. + rig.click(inside(r0)); + let minted = rig.minted(); + assert_eq!((minted[0].source.as_str(), minted[0].items.clone()), ("row", vec!["item-0000".to_string()]), "{mode:?}"); + // Scrolled by one row (offsets are device px in Pixels): row 1 is drawn where row 0 was. + let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; + rig.scroll.set(nid("pane"), (0.0, step * k)); + rig.draw(); + assert_eq!(rig.rect(second.as_str()).y, r0.y, "{mode:?}"); + rig.click(inside(r0)); + assert_eq!(rig.minted()[0].items, vec!["item-0001".to_string()], "{mode:?}"); + // Row 0 is above the pane's clip now: its rect is not hit anywhere, though a point there is drawn. + let gone = rig.rendered.placed.iter().find(|p| p.id == first).unwrap(); + let pane = rig.rect("pane"); + let over = (pane.x + 0.5, gone.rect.y + 0.5); + assert!(over.1 < pane.y, "{mode:?}: the scrolled-out row is above the pane"); + assert_ne!(hit_node(&rig, over).as_deref(), Some(first.as_str()), "{mode:?}"); + assert_eq!(rig_target(&rig, over), None, "{mode:?}"); + } +} + +#[test] +fn a_wheel_moves_the_pane_and_clamps_at_the_end_then_goes_to_the_next_pane() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &nested_surface(), mode); + let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; + let (inner, outer) = (rig.rect("inner"), rig.rect("outer")); + let over = inside(inner); + let (inner_max, _) = (rig.max_scroll("inner"), 0); + assert!(inner_max.1 > 0.0 && rig.max_scroll("outer").1 > 0.0, "{mode:?}"); + // Far past the end: the inner pane clamps at its travel, the outer stays. + rig.send(wheel(over, (0.0, 100_000.0), WheelUnit::Units)); + assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), None), "{mode:?}"); + // At the end of travel the same wheel goes to the pane around it. + rig.send(wheel(over, (0.0, 16.0), WheelUnit::Units)); + assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), Some((0.0, 16.0 * k))), "{mode:?}"); + // The other way the inner pane has room, so it takes it and the outer holds. + rig.send(wheel(over, (0.0, -8.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, inner_max.1 - 8.0 * k)), "{mode:?}"); + assert_eq!(rig.offset("outer"), Some((0.0, 16.0 * k)), "{mode:?}"); + // Back to the start, then further: clamps at zero and the outer takes the rest of the way back. + rig.send(wheel(over, (0.0, -100_000.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, 0.0)), "{mode:?}"); + rig.send(wheel(over, (0.0, -4.0), WheelUnit::Units)); + assert_eq!(rig.offset("outer"), Some((0.0, 12.0 * k)), "{mode:?}"); + // A wheel off every pane moves nothing; the horizontal axis has no travel here. + let before = (rig.offset("inner"), rig.offset("outer")); + rig.send(wheel((outer.x - 0.5, outer.y - 0.5), (0.0, 10.0), WheelUnit::Units)); + rig.send(wheel(over, (10.0, 0.0), WheelUnit::Units)); + assert_eq!((rig.offset("inner"), rig.offset("outer")), before, "{mode:?}"); + } +} + +#[test] +fn a_wheel_line_is_one_cell_in_cells_and_the_body_text_size_in_pixels() { + let mut cells = Rig::new(Port::new(), &nested_surface(), (Metrics::Cells, 1.0)); + cells.send(wheel(inside(cells.rect("inner")), (0.0, 3.0), WheelUnit::Lines)); + assert_eq!(cells.offset("inner"), Some((0.0, 3.0))); + for scale in [1.0, 1.5] { + let mut pixels = Rig::new(Port::new(), &nested_surface(), (Metrics::Pixels, scale)); + pixels.send(wheel(inside(pixels.rect("inner")), (0.0, 2.0), WheelUnit::Lines)); + assert_eq!(pixels.offset("inner"), Some((0.0, 2.0 * 16.0 * scale))); + } +} + +#[test] +fn a_wheel_over_a_modal_never_scrolls_the_tree_beneath() { + let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]); + let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("modal", true, vec![fixed("dialog", 80.0, 48.0)])]), vec![decl("dismiss", &[])]); + for mode in MODES { + let mut rig = Rig::new(Port::new(), &document, mode); + rig.send(wheel(inside(rig.rect("pane")), (0.0, 16.0), WheelUnit::Units)); + assert_eq!(rig.offset("pane"), None, "{mode:?}"); + } +} + +// ----- press semantics ----- + +#[test] +fn a_press_released_elsewhere_or_with_another_button_or_after_a_cancel_activates_nothing() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let (a, b) = (inside(rig.rect("a")), inside(rig.rect("b"))); + // Down on a, up on b. + rig.send(down(a)); + rig.send(up(b)); + // Secondary and middle buttons never press. + for button in [PointerButton::Secondary, PointerButton::Middle] { + rig.send(InputEvent::PointerDown { at: a, button, modifiers: mods() }); + rig.send(InputEvent::PointerUp { at: a, button, modifiers: mods() }); + } + // Down, the platform takes the pointer, a stray up. + rig.send(down(a)); + rig.send(InputEvent::PointerCancel); + rig.send(up(a)); + // An up with no press. + rig.send(up(a)); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + // And the same button down and up mints once. + rig.click(a); + assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); + } +} + +#[test] +fn a_secondary_up_does_not_release_a_primary_press() { + let mut rig = Rig::new(Port::new(), &controls_surface(), MODES[0]); + let a = inside(rig.rect("a")); + rig.send(down(a)); + rig.send(InputEvent::PointerUp { at: a, button: PointerButton::Secondary, modifiers: mods() }); + assert_eq!(rig.minted(), vec![]); + rig.send(up(a)); + assert_eq!(commands_of(&rig.minted()), ["go"]); +} + +#[test] +fn a_busy_button_mints_once_however_often_it_is_pressed() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let a = inside(rig.rect("a")); + assert_eq!(rig.click(a), vec![]); + assert_eq!(rig.click(a), vec![], "{mode:?}: a busy press is silent, not a refusal"); + assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); + // The user sees it: the busy button is drawn disabled. + rig.draw(); + let disabled = Theme::std().colors["thing.control.disabled"].clone(); + assert!(rig.rendered.commands.iter().any(|c| matches!(c, crate::render::RenderCommand::FillRect { color, .. } if *color == disabled)), "{mode:?}"); + } +} + +#[test] +fn a_toggle_flips_its_draft_and_fires_on_change_once_per_press() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let flag = inside(rig.rect("flag")); + rig.click(flag); + let first = rig.minted(); + assert_eq!(commands_of(&first), ["flip"], "{mode:?}"); + assert_eq!(first[0].captured[0].value, InputValue::Bool(BoolValue { value: true }), "{mode:?}"); + assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true }))); + // A second press is a change to a control with an invocation waiting: it is refused and says so, it + // fires nothing more, and it leaves the draft that was sent (a busy control holds no unsent value). + let said = rig.click(flag); + assert_eq!(said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect::>(), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}"); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true })), "{mode:?}"); + } +} + +#[test] +fn a_slider_drag_writes_snapped_drafts_and_commits_once_wherever_it_is_released() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let track = rig.rect("level"); + let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); + let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); + rig.send(down(along(0.34))); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: 34 snaps to the step from min"); + rig.send(mv(along(0.76))); + assert_eq!(rig.draft("level"), value(80.0), "{mode:?}"); + // The drag is shown while it is made. + rig.draw(); + let thumb = |rig: &Rig| rig.rendered.commands.iter().filter_map(|c| match c { + crate::render::RenderCommand::FillRect { rect, .. } if rect.w <= track.h.max(1.0) + 0.01 && rect.h > 0.0 => Some(rect.x), + _ => None, + }).last(); + assert!(thumb(&rig).is_some()); + // Released far outside the track, even outside the pane: one commit of the last draft. + rig.send(mv((track.x + track.w * 3.0, track.y + 500.0))); + assert_eq!(rig.draft("level"), value(100.0), "{mode:?}: past the end clamps"); + rig.send(up((track.x - 900.0, track.y - 900.0))); + let minted = rig.minted(); + assert_eq!(commands_of(&minted), ["set"], "{mode:?}"); + assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 100.0 }), "{mode:?}"); + // Moving after the up changes nothing. + rig.send(mv(along(0.1))); + assert_eq!(rig.draft("level"), value(100.0), "{mode:?}"); + } +} + +#[test] +fn a_cancelled_slider_press_leaves_the_draft_it_found_and_fires_nothing() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let track = rig.rect("level"); + let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); + // No draft before: a press then a cancel leaves none, and a stray up commits nothing. + rig.send(down(along(0.5))); + assert!(rig.draft("level").is_some()); + rig.send(InputEvent::PointerCancel); + rig.send(up(along(0.5))); + assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?}"); + // A draft that is already waiting on a result comes back as it was. + rig.send(down(along(0.3))); + rig.send(up(along(0.3))); + assert_eq!(commands_of(&rig.minted()), ["set"]); + let held = rig.draft("level"); + rig.send(down(along(0.9))); + rig.send(mv(along(0.2))); + rig.send(InputEvent::PointerCancel); + assert_eq!((rig.draft("level"), rig.minted()), (held, vec![]), "{mode:?}"); + } +} + +#[test] +fn a_press_on_a_select_or_a_text_input_does_nothing_yet() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &fields_surface(), mode); + for id in ["field", "choice"] { + assert_eq!(rig.click(inside(rig.rect(id))), vec![], "{mode:?} {id}"); + } + assert_eq!((rig.minted(), rig.drafts.is_empty()), (vec![], true), "{mode:?}"); + } +} + +#[test] +fn a_click_while_a_command_waits_for_confirmation_is_a_refusal_the_event_returns() { + for mode in MODES { + let mut document = surface(column("root", None, Overflow::Visible, vec![button("a", "ask", 160.0, 48.0), button("b", "go", 160.0, 48.0)]), vec![decl("ask", &[]), decl("go", &[])]); + document.commands[0].confirm = Some("Sure?".into()); + let mut rig = Rig::new(Port::new(), &document, mode); + assert_eq!(rig.click(inside(rig.rect("a"))), vec![]); + assert!(rig.commands.confirming().is_some() && rig.minted().is_empty(), "{mode:?}"); + let said = rig.click(inside(rig.rect("b"))); + assert_eq!(said.iter().map(|d| d.code).collect::>(), vec![Code::ActivationRefused], "{mode:?}"); + assert_eq!(said[0].node.as_ref().map(NodeId::as_str), Some("b")); + } +} + +// ----- a control that takes no change holds no unsent value ----- + +fn result_change(sent: &CommandInvocation, clear: bool) -> Change { + let result = CommandResult::completed(sent, seq(1), None, clear, None); + let address = Address { provider: ProviderId::new(PROVIDER), schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(result.record_key()) }; + Change::Upsert(Entry { address, record: Record::Result(result) }) +} + +fn refusals(said: &[Diagnostic]) -> Vec<(Code, Option<&str>)> { + said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect() +} + +#[test] +fn a_slider_that_waits_for_its_result_takes_no_press_or_drag_and_a_completion_leaves_no_stray_draft() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let track = rig.rect("level"); + let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); + let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); + rig.send(down(along(0.3))); + rig.send(up(along(0.3))); + let sent = rig.minted().remove(0); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}"); + // The slider waits: a second press and its drag are refused, say so, and write nothing. + assert_eq!(refusals(&rig.send(down(along(0.8)))), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}"); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: the press wrote nothing"); + rig.send(mv(along(0.9))); + assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: a refused press starts no drag"); + assert_eq!(rig.send(up(along(0.9))), vec![], "{mode:?}"); + assert_eq!(rig.minted(), vec![], "{mode:?}"); + // The result clears the draft that was sent, and nothing else is left drawn on the slider. + let tree = &rig.tree; + rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger); + assert_eq!(rig.draft("level"), None, "{mode:?}"); + } +} + +#[test] +fn a_toggle_pressed_while_it_waits_is_refused_and_a_completion_leaves_the_provider_true() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let flag = inside(rig.rect("flag")); + rig.click(flag); + let sent = rig.minted().remove(0); + assert_eq!(refusals(&rig.click(flag)), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}"); + let tree = &rig.tree; + rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger); + assert_eq!(rig.draft("flag"), None, "{mode:?}: nothing survives to show a checked box the provider does not hold"); + } +} + +#[test] +fn a_slider_press_while_a_command_waits_for_confirmation_writes_no_draft() { + for mode in MODES { + let mut document = controls_surface(); + document.commands.iter_mut().find(|c| c.id.as_str() == "go").unwrap().confirm = Some("Sure?".into()); + let mut rig = Rig::new(Port::new(), &document, mode); + rig.click(inside(rig.rect("a"))); + assert!(rig.commands.confirming().is_some(), "{mode:?}"); + let track = rig.rect("level"); + let said = rig.send(down((track.x + 0.5 * track.w, track.y + 0.5))); + assert_eq!(refusals(&said), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}"); + assert_eq!((rig.draft("level"), rig.drafts.is_empty()), (None, true), "{mode:?}"); + } +} + +#[test] +fn input_other_than_the_pointer_changes_nothing() { + let mut rig = Rig::new(Port::new(), &controls_surface(), MODES[0]); + let before = (rig.rendered.clone(), rig.drafts.len()); + for event in [ + InputEvent::Key { key: crate::input::Key::Enter, modifiers: mods(), repeat: false }, + InputEvent::Text("x".into()), + InputEvent::Compose { text: "か".into(), cursor: None }, + InputEvent::Focus(true), + ] { + assert_eq!(rig.send(event), vec![]); + } + assert_eq!((rig.minted(), rig.drafts.len()), (vec![], before.1)); +} + +#[test] +fn a_slider_snaps_from_its_own_minimum_and_follows_its_own_track() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &lone_slider(20.0, 120.0, 10.0), mode); + let track = rig.rect("level"); + assert!(track.x > 0.0, "{mode:?}: the track does not start at the root's edge"); + let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); + let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); + rig.send(down(along(0.0))); + assert_eq!(rig.draft("level"), value(20.0), "{mode:?}: the track's left edge is the minimum"); + rig.send(mv(along(0.47))); + assert_eq!(rig.draft("level"), value(70.0), "{mode:?}: 20 + 47 = 67 snaps to 70 from 20"); + rig.send(mv(along(1.0))); + assert_eq!(rig.draft("level"), value(120.0), "{mode:?}"); + // A move that is not a position is not a value. + rig.send(mv((f32::NAN, track.y))); + assert_eq!(rig.draft("level"), value(120.0), "{mode:?}"); + } +} + +#[test] +fn a_track_that_shrinks_to_nothing_mid_drag_leaves_the_draft_as_it_was() { + for mode in MODES { + let mut rig = Rig::new(Port::new(), &controls_surface(), mode); + let track = rig.rect("level"); + let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); + rig.send(down((track.x + 0.5 * track.w, track.y + 0.5))); + assert_eq!(rig.draft("level"), value(50.0), "{mode:?}"); + // The surface shrinks under the pointer: the slider's rect is now zero wide. + for placed in rig.rendered.placed.iter_mut().filter(|placed| placed.id.as_str() == "level") { + placed.rect.w = 0.0; + } + // At the track's left edge (0 over 0) and past it (n over 0): neither is a value. + for x in [track.x, track.x + 10.0] { + rig.send(mv((x, track.y + 0.5))); + assert_eq!(rig.draft("level"), value(50.0), "{mode:?}: a move over a zero-width track at {x}"); + } + rig.send(up((track.x, track.y))); + let minted = rig.minted(); + assert_eq!(minted.len(), 1, "{mode:?}"); + assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 50.0 }), "{mode:?}"); + } +} + +#[test] +fn a_slider_with_no_range_or_a_step_of_zero_is_handled_by_what_it_declares() { + for mode in MODES { + for (min, max) in [(5.0, 5.0), (0.0, f64::INFINITY), (9.0, 3.0)] { + let mut rig = Rig::new(Port::new(), &lone_slider(min, max, 1.0), mode); + let at = inside(rig.rect("level")); + rig.click(at); + assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?} {min}..{max}"); + } + // No step: the raw position, unsnapped. + let mut rig = Rig::new(Port::new(), &lone_slider(0.0, 100.0, 0.0), mode); + let track = rig.rect("level"); + rig.send(down((track.x + 0.25 * track.w, track.y + 0.5))); + assert_eq!(rig.draft("level"), Some(InputValue::Number(NumberValue { value: 25.0 })), "{mode:?}"); + } +} + +#[test] +fn a_press_on_a_text_input_or_a_select_does_not_fall_through_to_the_button_around_it() { + let (input, select) = fields(); + let card = Node::Button(ButtonNode { + common: common("card"), + content: vec![fixed("pad", 160.0, 16.0), input, select], + on_activate: command("go"), + enabled: lit_bool(true), + }); + for mode in MODES { + let document = surface(column("root", None, Overflow::Visible, vec![card.clone()]), vec![decl("go", &[])]); + let mut rig = Rig::new(Port::new(), &document, mode); + for id in ["field", "choice"] { + let r = rig.rect(id); + assert!(r.w >= 1.0 && r.h >= 1.0, "{mode:?} {id}"); + assert_eq!(rig.click(inside(r)), vec![], "{mode:?} {id}"); + } + assert_eq!(rig.minted(), vec![], "{mode:?}: the card around them was not pressed"); + // The card itself still is. + rig.click(inside(rig.rect("pad"))); + assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); + } +} + +#[test] +fn a_wheel_that_is_not_a_number_or_runs_on_a_bad_scale_is_ignored_or_taken_at_one() { + let mut rig = Rig::new(Port::new(), &nested_surface(), (Metrics::Pixels, 1.5)); + let over = inside(rig.rect("inner")); + // The scale the host gave is not usable: the offset is the wheel's units as they are. + for bad in [0.0, f32::INFINITY, f32::NAN, -2.0] { + rig.scroll = ScrollOffsets::default(); + rig.scale = bad; + rig.send(wheel(over, (0.0, 10.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, 10.0)), "scale {bad}"); + } + // A delta that is not a number moves nothing, and does not reset what is scrolled. + rig.scale = 1.5; + rig.scroll.set(nid("inner"), (0.0, 30.0)); + for bad in [f32::NAN, f32::INFINITY] { + rig.send(wheel(over, (0.0, bad), WheelUnit::Units)); + rig.send(wheel(over, (bad, 0.0), WheelUnit::Units)); + assert_eq!(rig.offset("inner"), Some((0.0, 30.0)), "delta {bad}"); + } +} + +#[test] +fn a_wheel_scrolls_the_horizontal_axis_by_its_own_delta() { + let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("wide", 400.0, 400.0)]); + let document = surface(column("root", None, Overflow::Visible, vec![pane]), vec![]); + for mode in MODES { + let mut rig = Rig::new(Port::new(), &document, mode); + let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; + let over = inside(rig.rect("pane")); + assert!(rig.max_scroll("pane").0 > 0.0 && rig.max_scroll("pane").1 > 0.0, "{mode:?}"); + rig.send(wheel(over, (8.0, 4.0), WheelUnit::Units)); + assert_eq!(rig.offset("pane"), Some((8.0 * k, 4.0 * k)), "{mode:?}"); + rig.send(wheel(over, (-2.0, 0.0), WheelUnit::Units)); + assert_eq!(rig.offset("pane"), Some((6.0 * k, 4.0 * k)), "{mode:?}"); + } +} diff --git a/crates/thing-core/tests/input.rs b/crates/thing-core/tests/input.rs index ac14fff..58d0dfd 100644 --- a/crates/thing-core/tests/input.rs +++ b/crates/thing-core/tests/input.rs @@ -1,17 +1,18 @@ -//! Pointer input: a press, a drag and a wheel reach the node the user saw drawn, in Pixels (at two -//! scales) and in Cells, and end in the one activation primitive, in drafts or in scroll offsets. -//! Hit-testing reads the geometry render placed, so every test derives its points from `Placed` -//! and never from authored numbers. Ordering is forced: a test that depends on an order puts the -//! events in one frame or in two, and says which. +//! Pointer input through `Core::frame`, the one way a host reaches it: a click lands on the node the +//! user saw drawn, in the frame the user saw it, and mints through the one activation primitive. The +//! routes themselves (hit-testing, press state, the wheel) are tested in the crate, where they are visible. +//! Every test derives its points from the geometry render placed. Ordering is forced: a test that +//! depends on an order puts the events in one frame or in two, and says which. +mod support; + +use support::*; use thing_contract::*; -use thing_core::bind::{Binder, BoundTree, Instance}; -use thing_core::command::Commands; -use thing_core::diagnostic::{Code, Diagnostic}; -use thing_core::input::{Drafts, Input, InputEvent, Modifiers, Owners, PointerButton, Seen, WheelUnit, hit_test, target}; -use thing_core::layout::{LaidTree, LayoutFrame, Metrics, Rect, layout}; -use thing_core::port::{Address, Change, Entry, Ledger, Record}; -use thing_core::render::{RenderInput, Rendered, ScrollOffsets, Session, render}; +use thing_core::bind::{Binder, Instance}; +use thing_core::input::{InputEvent, Modifiers, PointerButton, WheelUnit}; +use thing_core::layout::{LayoutFrame, Metrics, Rect, layout}; +use thing_core::port::Ledger; +use thing_core::render::{Placed, RenderInput, ScrollOffsets, Session, render}; use thing_core::resolve::{Limits, resolve}; use thing_core::theme::Theme; use thing_core::time::Timestamp; @@ -23,9 +24,6 @@ use thing_testkit::measure::FixedMeasure; use thing_testkit::mem_state::MemState; use thing_testkit::state::{self, Item, Settings}; -const PROVIDER: &str = "provider.pointer"; -const FEED: &str = "provider.feed"; - /// Pixels at two scales, and Cells: the modes the pointer must agree with the laid geometry in. const MODES: [(Metrics, f32); 3] = [(Metrics::Pixels, 1.0), (Metrics::Pixels, 1.5), (Metrics::Cells, 1.0)]; @@ -43,79 +41,10 @@ fn measure(metrics: Metrics) -> FixedMeasure { } } -// ----- surfaces ----- - -fn decl(id: &str, captures: &[&str]) -> CommandDecl { - CommandDecl { - id: CommandId::new(id), - payload_schema: SchemaId::new(format!("gamecult.thing.test.{id}.v1")), - captures: captures.iter().map(|node| nid(node)).collect(), - confirm: None, - } -} - -fn column(id: &str, size: Option<(f64, f64)>, overflow: Overflow, children: Vec) -> Node { - let size = size.map_or(size2(Dimension::Percent(Scalar { value: 100.0 }), Dimension::Content), |(w, h)| size2(px(w), px(h))); - let style = BoxStyle { - size, - overflow, - padding: edges(px(0.0)), - gap: size2(px(0.0), px(0.0)), - grow: 0.0, - justify_content: ContentAlign::Start, - ..style() - }; - Node::Box(BoxNode { common: common(id), style, paint: plain_paint(), role: Role::Group, children }) -} - -/// A box of exactly `w` x `h` authored px (a whole number of cells when both are multiples of 8 and 16). -fn fixed(id: &str, w: f64, h: f64) -> Node { - column(id, Some((w, h)), Overflow::Visible, vec![]) -} - -fn button(id: &str, cmd: &str, w: f64, h: f64) -> Node { - Node::Button(ButtonNode { common: common(id), content: vec![fixed(&format!("{id}-body"), w, h)], on_activate: command(cmd), enabled: lit_bool(true) }) -} - -fn overlay(id: &str, modal: bool, children: Vec) -> Node { - Node::Overlay(OverlayNode { common: common(id), anchor: Anchor::Viewport, modal, dismiss: command("dismiss"), children }) -} - -fn surface(root: Node, commands: Vec) -> SurfaceDocument { - SurfaceDocument { provider_id: ProviderId::new(PROVIDER), label: seg("pointer"), version: ver(1), title: "t".into(), root, commands } -} - -/// A main-tree button under a modal overlay whose dialog holds one button. -fn modal_surface() -> SurfaceDocument { - let dialog = column("dialog", Some((160.0, 96.0)), Overflow::Visible, vec![button("confirm", "confirm", 160.0, 48.0)]); - surface( - column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), overlay("modal", true, vec![dialog])]), - vec![decl("behind", &[]), decl("confirm", &[]), decl("dismiss", &[])], - ) -} - fn row_id(item: &str, node: &str) -> NodeId { NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false))) } -/// A 160 x 160 scroll pane of twenty buttons, one per feed item, with a button below it. -fn rows_surface() -> SurfaceDocument { - let rows = Node::Repeat(RepeatNode { - common: common("rows"), - collection: CollectionSource::Records(RecordsSource { - provider: Some(ProviderId::new(FEED)), - schema: SchemaId::new("gamecult.thing.test.item.v1"), - key_prefix: "item-".into(), - }), - key_member: path(&["Id"]), - template: std::boxed::Box::new(button("row", "pick", 160.0, 48.0)), - }); - surface( - column("root", None, Overflow::Visible, vec![column("pane", Some((160.0, 160.0)), Overflow::Scroll, vec![rows]), button("below", "below", 160.0, 48.0)]), - vec![decl("pick", &[]), decl("below", &[])], - ) -} - fn feed() -> MemState { let mut state = MemState::new(); for n in 0..20 { @@ -125,148 +54,6 @@ fn feed() -> MemState { state } -/// A pane inside a pane, each scrolling: the inner is 80 tall with 400 of content, the outer 160 tall -/// with the inner above 400 more. -fn nested_surface() -> SurfaceDocument { - let inner = column("inner", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("inner-fill", 160.0, 400.0)]); - surface(column("root", None, Overflow::Visible, vec![column("outer", Some((160.0, 160.0)), Overflow::Scroll, vec![inner, fixed("outer-fill", 160.0, 400.0)])]), vec![]) -} - -/// A tall button inside a clip, with room below the clip that the button's own rect also covers. -fn clip_surface() -> SurfaceDocument { - surface( - column("root", None, Overflow::Visible, vec![column("frame", Some((160.0, 64.0)), Overflow::Clip, vec![button("tall", "tall", 160.0, 320.0)])]), - vec![decl("tall", &[])], - ) -} - -/// A root with a 16px left margin, so no control's rect starts where the root's does. -fn indented(id: &str, children: Vec) -> Node { - let mut root = column(id, None, Overflow::Visible, children); - if let Node::Box(b) = &mut root { - b.style.padding.left = px(16.0); - } - root -} - -fn controls_surface() -> SurfaceDocument { - let slider = Node::Slider(SliderNode { common: common("level"), min: 0.0, max: 100.0, step: 10.0, value: lit_number(0.0), commit: command("set") }); - let toggle = Node::Toggle(ToggleNode { common: common("flag"), checked: lit_bool(false), on_change: command("flip") }); - surface( - indented("root", vec![button("a", "go", 160.0, 48.0), button("b", "go", 160.0, 48.0), toggle, slider]), - vec![decl("go", &[]), decl("flip", &["flag"]), decl("set", &["level"])], - ) -} - -// ----- the rig: the stages composed by hand, with the owners input writes through ----- - -struct Rig { - tree: BoundTree, - laid: LaidTree, - rendered: Rendered, - metrics: Metrics, - scale: f32, - surface: String, - state: MemState, - ledger: Ledger, - input: Input, - commands: Commands, - drafts: Drafts, - scroll: ScrollOffsets, - ids: SeqIds, - now: Timestamp, -} - -impl Rig { - fn new(mut state: MemState, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Self { - state.put(&document.provider_id, document); - let limits = Limits::default(); - let resolved = resolve(document, &state, &limits).tree.expect("resolves"); - let mut ledger = Ledger::new(); - let mut binder = Binder::new(limits); - binder.bind(resolved, &mut state, &mut ledger); - let tree = binder.tree(&document.record_key()).expect("bound").clone(); - let mut rig = Self { - laid: LaidTree { nodes: vec![], diagnostics: vec![] }, - rendered: Rendered { commands: vec![], placed: vec![], diagnostics: vec![] }, - tree, - metrics, - scale, - surface: document.record_key(), - state, - ledger, - input: Input::new(), - commands: Commands::new("renderer.test", 15_000), - drafts: Drafts::new(), - scroll: ScrollOffsets::default(), - ids: SeqIds::new(), - now: Timestamp(0), - }; - rig.draw(); - rig - } - - fn frame(&self) -> LayoutFrame { - LayoutFrame { viewport: viewport(self.metrics), scale: self.scale, metrics: self.metrics } - } - - /// The frame the user sees: layout, then render over the scroll offsets, drafts and node states. - fn draw(&mut self) { - self.laid = layout(&self.tree, &self.frame(), &mut measure(self.metrics)).expect("lays out"); - let states = self.commands.view(&self.surface); - let theme = Theme::std(); - let input = RenderInput { - scale: self.scale, - metrics: self.metrics, - viewport: viewport(self.metrics), - scroll: &self.scroll, - theme: &theme, - session: Session::new(&self.drafts, &states), - }; - self.rendered = render(&self.tree, &self.laid, &input, &mut measure(self.metrics)); - } - - fn rect(&self, id: &str) -> Rect { - self.rendered.placed.iter().find(|placed| placed.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect - } - - fn send(&mut self, event: InputEvent) -> Vec { - let theme = Theme::std(); - let seen = Seen { rendered: &self.rendered, laid: &self.laid, tree: &self.tree, metrics: self.metrics, scale: self.scale, line: theme.text["body"].size }; - let mut owners = Owners { - commands: &mut self.commands, - drafts: &mut self.drafts, - scroll: &mut self.scroll, - ids: &mut self.ids, - port: &mut self.state, - ledger: &mut self.ledger, - }; - self.input.event(&event, &seen, &mut owners, self.now) - } - - fn click(&mut self, at: (f32, f32)) -> Vec { - let mut said = self.send(down(at)); - said.extend(self.send(up(at))); - said - } - - fn minted(&mut self) -> Vec { - self.commands.take_outbound() - } - - fn draft(&self, node: &str) -> Option { - self.drafts.get(&self.surface, &nid(node)).cloned() - } - - fn offset(&self, node: &str) -> Option<(f32, f32)> { - self.scroll.get(&nid(node)) - } - - fn max_scroll(&self, node: &str) -> (f32, f32) { - self.laid.nodes.iter().find(|laid| laid.id.as_str() == node).and_then(|laid| laid.max_scroll).expect("scrolls") - } -} - fn mods() -> Modifiers { Modifiers::default() } @@ -296,545 +83,26 @@ fn commands_of(invocations: &[CommandInvocation]) -> Vec<&str> { invocations.iter().map(|invocation| invocation.command.as_str()).collect() } -fn index_of(rig: &Rig) -> std::collections::HashMap<&NodeId, &Node> { - rig.tree.index() +/// What render placed for `document` at rest: where the host will click, from the public stages. +struct Placement(Vec); + +fn placement(mut state: MemState, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Placement { + state.put(&document.provider_id, document); + let limits = Limits::default(); + let resolved = resolve(document, &state, &limits).tree.expect("resolves"); + let mut ledger = Ledger::new(); + let mut binder = Binder::new(limits); + binder.bind(resolved, &mut state, &mut ledger); + let tree = binder.tree(&document.record_key()).expect("bound"); + let laid = layout(tree, &LayoutFrame { viewport: viewport(metrics), scale, metrics }, &mut measure(metrics)).expect("lays out"); + let theme = Theme::std(); + let input = RenderInput { scale, metrics, viewport: viewport(metrics), scroll: &ScrollOffsets::default(), theme: &theme, session: Session::EMPTY }; + Placement(render(tree, &laid, &input, &mut measure(metrics)).placed) } -/// Device px per logical px, as input holds it. -fn device_k(rig: &Rig) -> f32 { - match rig.metrics { - Metrics::Pixels => rig.scale, - Metrics::Cells => 1.0, - } -} - -fn hit_node(rig: &Rig, at: (f32, f32)) -> Option { - hit_test(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig)).map(|hit| hit.node.as_str().to_string()) -} - -fn rig_target(rig: &Rig, at: (f32, f32)) -> Option { - target(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig)) -} - -// ----- hit-testing agrees with the laid geometry ----- - -#[test] -fn a_point_inside_the_absolute_target_hits_target_and_one_on_the_board_only_hits_board() { - for mode in MODES { - let mut state = MemState::from_fixture(Fixture::F03InputTarget); - state::script(Fixture::F03InputTarget, &mut state); - let document = Fixture::F03InputTarget.load().surfaces.remove(0); - let rig = Rig::new(state, &document, mode); - let (target, board) = (rig.rect("target"), rig.rect("board")); - // The far corner of the target, clear of its label. - let corner = (target.x + target.w - 0.5, target.y + target.h - 0.5); - assert_eq!(hit_node(&rig, corner).as_deref(), Some("target"), "{mode:?}"); - assert_eq!(hit_node(&rig, inside(board)).as_deref(), Some("board"), "{mode:?}"); - assert!(target.x > board.x && target.y > board.y, "{mode:?}: the target stands inside the board, away from its corner"); - } -} - -#[test] -fn a_rect_is_half_open_so_a_shared_edge_belongs_to_the_second_node() { - for mode in MODES { - let rig = Rig::new(MemState::new(), &surface(column("root", None, Overflow::Visible, vec![button("a", "x", 160.0, 48.0), button("b", "x", 160.0, 48.0)]), vec![decl("x", &[])]), mode); - let (a, b) = (rig.rect("a"), rig.rect("b")); - assert_eq!(a.y + a.h, b.y, "{mode:?}: the buttons touch"); - let edge = (a.x + 0.5, b.y); - assert!(rig_target(&rig, edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}"); - let last = (a.x + 0.5, b.y - 0.25); - assert!(rig_target(&rig, last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}"); - let under = (b.x + 0.5, b.y + b.h); - assert_eq!(rig_target(&rig, under), None, "{mode:?}: the bottom edge is outside"); - let beyond = (a.x + a.w, a.y + 0.5); - assert_ne!(rig_target(&rig, beyond).map(|hit| hit.node), Some(nid("a")), "{mode:?}: the right edge is outside"); - } -} - -#[test] -fn every_visible_node_is_reached_inside_its_own_visible_rect() { - let fixtures = [Fixture::F01SwarmDashboard, Fixture::F05ModalOverlay, Fixture::F06ScrollList]; - for mode in MODES { - for fixture in fixtures { - let mut state = MemState::from_fixture(fixture); - state::script(fixture, &mut state); - let document = fixture.load().surfaces.remove(0); - let rig = Rig::new(state, &document, mode); - for placed in &rig.rendered.placed { - let Some(seen) = placed.visible.filter(|r| r.w >= 1.0 && r.h >= 1.0) else { continue }; - let hit = hit_node(&rig, inside(seen)).expect("something is there"); - let reached = rig.rendered.placed.iter().find(|p| p.id.as_str() == hit).unwrap(); - let at = inside(seen); - let within = reached.visible.is_some_and(|r| at.0 >= r.x && at.0 < r.x + r.w && at.1 >= r.y && at.1 < r.y + r.h); - assert!(within, "{mode:?} {fixture:?}: {hit} reached at {at:?} is not drawn there"); - } - } - } -} - -#[test] -fn a_node_outside_its_clip_is_not_hit_where_its_rect_reaches_past_the_clip() { - for mode in MODES { - let rig = Rig::new(MemState::new(), &clip_surface(), mode); - let (frame, tall) = (rig.rect("frame"), rig.rect("tall")); - assert!(tall.y + tall.h > frame.y + frame.h, "{mode:?}: the button runs past the clip"); - let below = (tall.x + 0.5, frame.y + frame.h + 0.5); - assert!(below.1 < tall.y + tall.h); - assert_eq!(rig_target(&rig, below), None, "{mode:?}"); - assert_ne!(hit_node(&rig, below).as_deref(), Some("tall"), "{mode:?}"); - // Inside the clip it is hit. - let inside_clip = rig_target(&rig, inside(frame)); - assert_eq!(inside_clip.map(|hit| hit.node.as_str().to_string()).as_deref(), Some("tall"), "{mode:?}"); - } -} - -// ----- the edge of a node, at a scale that does not divide ----- - -/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale. -fn seam_surface() -> SurfaceDocument { - let row = |id: &str, h: f64, widths: &[f64]| { - let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect()); - if let Node::Box(b) = &mut row { - b.style.direction = Direction::Row; - b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h)); - b.style.justify_content = ContentAlign::Start; - } - row - }; - surface( - column("root", None, Overflow::Visible, vec![ - row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]), - row("r1", 13.0, &[11.0, 3.0, 17.0]), - row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]), - row("r3", 19.0, &[23.0, 29.0, 13.0]), - ]), - vec![], - ) -} - -#[test] -fn the_first_device_pixel_past_a_nodes_right_or_bottom_edge_is_not_the_node_at_every_scale() { - let scales = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0]; - let modes = scales.map(|scale| (Metrics::Pixels, scale)).into_iter().chain([(Metrics::Cells, 1.0)]); - for mode in modes { - let rig = Rig::new(MemState::new(), &seam_surface(), mode); - let k = device_k(&rig); - let mut leaves = 0; - for node in rig.laid.nodes.iter().filter(|node| node.id.as_str().contains('-')) { - leaves += 1; - let (id, r) = (node.id.as_str(), node.rect); - assert!(r.w >= 1.0 && r.h >= 1.0 && r.x.fract() == 0.0 && r.y.fract() == 0.0, "{mode:?} {id}: laid in whole device px, {r:?}"); - // Device pixels, as a host at this scale reports a pointer: the pixel's corner and its centre. - let at = |dx: f32, dy: f32, off: f32| ((dx + off) / k, (dy + off) / k); - for off in [0.0, 0.5] { - let last = at(r.x + r.w - 1.0, r.y + r.h - 1.0, off); - assert_eq!(hit_node(&rig, last).as_deref(), Some(id), "{mode:?} {id} the last pixel of the node, +{off}"); - let right = at(r.x + r.w, r.y, off); - assert_ne!(hit_node(&rig, right).as_deref(), Some(id), "{mode:?} {id} the pixel right of the node, +{off}"); - let below = at(r.x, r.y + r.h, off); - assert_ne!(hit_node(&rig, below).as_deref(), Some(id), "{mode:?} {id} the pixel below the node, +{off}"); - let first = at(r.x, r.y, off); - assert_eq!(hit_node(&rig, first).as_deref(), Some(id), "{mode:?} {id} the first pixel of the node, +{off}"); - } - } - assert_eq!(leaves, 15, "{mode:?}"); - } -} - -// ----- a non-modal overlay ----- - -fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument { - let pop = Node::Overlay(OverlayNode { common: common("pop"), anchor, modal: false, dismiss: command("dismiss"), children: vec![button("pop-button", "inside", 80.0, 48.0)] }); - surface( - column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), button("other", "other", 320.0, 48.0), pop]), - vec![decl("behind", &[]), decl("other", &[]), decl("inside", &[]), decl("dismiss", &[])], - ) -} - -#[test] -fn a_press_passes_through_a_non_modal_overlays_root_to_what_lies_beneath_and_its_own_content_still_takes_it() { - let node = Anchor::Node(AnchorNode { node: nid("behind") }); - for mode in MODES { - for anchor in [Anchor::Viewport, node.clone()] { - let mut rig = Rig::new(MemState::new(), &nonmodal_surface(anchor.clone()), mode); - let (behind, other, inner) = (rig.rect("behind"), rig.rect("other"), rig.rect("pop-button")); - let (a, b) = ((behind.x + behind.w - 0.5, behind.y + 0.5), (other.x + other.w - 0.5, other.y + 0.5)); - for at in [a, b] { - assert!(!(at.0 >= inner.x && at.0 < inner.x + inner.w && at.1 >= inner.y && at.1 < inner.y + inner.h), "{mode:?} {anchor:?}: {at:?} is clear of the overlay's content"); - assert_eq!(hit_node(&rig, at).as_deref().map(|id| id != "pop"), Some(true), "{mode:?} {anchor:?}: the overlay's root is not what is hit at {at:?}"); - } - rig.click(a); - assert_eq!(commands_of(&rig.minted()), ["behind"], "{mode:?} {anchor:?}: the press reaches the anchor or the node under the viewport overlay"); - rig.click(b); - assert_eq!(commands_of(&rig.minted()), ["other"], "{mode:?} {anchor:?}"); - // The overlay's own content is drawn over them and takes its press. - rig.click(inside(inner)); - assert_eq!(commands_of(&rig.minted()), ["inside"], "{mode:?} {anchor:?}"); - } - } -} - -#[test] -fn a_wheel_over_a_non_modal_overlays_root_reaches_the_pane_beneath() { - let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]); - let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("pop", false, vec![fixed("pop-body", 8.0, 16.0)])]), vec![decl("dismiss", &[])]); - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &document, mode); - let pane = rig.rect("pane"); - rig.send(wheel((pane.x + pane.w - 0.5, pane.y + pane.h - 0.5), (0.0, 16.0), WheelUnit::Units)); - assert!(rig.offset("pane").is_some_and(|o| o.1 > 0.0), "{mode:?}"); - } -} - -// ----- the modal ----- - -#[test] -fn a_modal_confirms_inside_the_dialog_and_dismisses_outside_it_and_never_reaches_beneath() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &modal_surface(), mode); - // Inside the dialog: the confirm button. - rig.click(inside(rig.rect("confirm"))); - assert_eq!(commands_of(&rig.minted()), ["confirm"], "{mode:?}"); - // Over a main-tree button under the scrim: the scrim's dismissal, once, and not the button's command. - let behind = rig.rect("behind"); - rig.click((behind.x + behind.w - 0.5, behind.y + 0.5)); - assert_eq!(commands_of(&rig.minted()), ["dismiss"], "{mode:?}"); - // The dialog's own body is not the scrim: nothing. - let dialog = rig.rect("dialog"); - rig.click((dialog.x + dialog.w - 0.5, dialog.y + dialog.h - 0.5)); - assert_eq!(rig.minted(), vec![], "{mode:?}"); - // The scrim is the whole viewport: a corner far from everything dismisses. - let (w, h) = viewport(mode.0); - let far = match mode.0 { - Metrics::Pixels => (w - 1.0, h - 1.0), - Metrics::Cells => (w - 0.5, h - 0.5), - }; - assert_eq!(hit_node(&rig, far).as_deref(), Some("modal"), "{mode:?}"); - // (The overlay that dismissed above still waits on its result, so it is silent: a fresh surface.) - let mut fresh = Rig::new(MemState::new(), &modal_surface(), mode); - fresh.click(far); - assert_eq!(commands_of(&fresh.minted()), ["dismiss"], "{mode:?}"); - // And the same press again, while the first waits, mints nothing more. - fresh.click(far); - assert_eq!(fresh.minted(), vec![], "{mode:?}"); - } -} - -#[test] -fn a_press_on_the_scrim_released_on_a_button_activates_nothing() { - let mut rig = Rig::new(MemState::new(), &modal_surface(), MODES[0]); - let behind = rig.rect("behind"); - let (scrim, confirm) = ((behind.x + behind.w - 0.5, behind.y + 0.5), inside(rig.rect("confirm"))); - rig.send(down(scrim)); - rig.send(up(confirm)); - assert_eq!(rig.minted(), vec![]); -} - -// ----- scroll ----- - -#[test] -fn a_click_hits_the_row_drawn_there_after_a_scroll_and_not_a_row_scrolled_out() { - for mode in MODES { - let mut rig = Rig::new(feed(), &rows_surface(), mode); - let (first, second) = (row_id("item-0000", "row"), row_id("item-0001", "row")); - let (r0, r1) = (rig.rect(first.as_str()), rig.rect(second.as_str())); - let step = r1.y - r0.y; - assert!(step > 0.0); - // At rest the click at row 0's corner is row 0, whose invocation names it in `items`. - rig.click(inside(r0)); - let minted = rig.minted(); - assert_eq!((minted[0].source.as_str(), minted[0].items.clone()), ("row", vec!["item-0000".to_string()]), "{mode:?}"); - // Scrolled by one row (offsets are device px in Pixels): row 1 is drawn where row 0 was. - let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; - rig.scroll.set(nid("pane"), (0.0, step * k)); - rig.draw(); - assert_eq!(rig.rect(second.as_str()).y, r0.y, "{mode:?}"); - rig.click(inside(r0)); - assert_eq!(rig.minted()[0].items, vec!["item-0001".to_string()], "{mode:?}"); - // Row 0 is above the pane's clip now: its rect is not hit anywhere, though a point there is drawn. - let gone = rig.rendered.placed.iter().find(|p| p.id == first).unwrap(); - let pane = rig.rect("pane"); - let over = (pane.x + 0.5, gone.rect.y + 0.5); - assert!(over.1 < pane.y, "{mode:?}: the scrolled-out row is above the pane"); - assert_ne!(hit_node(&rig, over).as_deref(), Some(first.as_str()), "{mode:?}"); - assert_eq!(rig_target(&rig, over), None, "{mode:?}"); - } -} - -#[test] -fn a_wheel_moves_the_pane_and_clamps_at_the_end_then_goes_to_the_next_pane() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &nested_surface(), mode); - let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; - let (inner, outer) = (rig.rect("inner"), rig.rect("outer")); - let over = inside(inner); - let (inner_max, _) = (rig.max_scroll("inner"), 0); - assert!(inner_max.1 > 0.0 && rig.max_scroll("outer").1 > 0.0, "{mode:?}"); - // Far past the end: the inner pane clamps at its travel, the outer stays. - rig.send(wheel(over, (0.0, 100_000.0), WheelUnit::Units)); - assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), None), "{mode:?}"); - // At the end of travel the same wheel goes to the pane around it. - rig.send(wheel(over, (0.0, 16.0), WheelUnit::Units)); - assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), Some((0.0, 16.0 * k))), "{mode:?}"); - // The other way the inner pane has room, so it takes it and the outer holds. - rig.send(wheel(over, (0.0, -8.0), WheelUnit::Units)); - assert_eq!(rig.offset("inner"), Some((0.0, inner_max.1 - 8.0 * k)), "{mode:?}"); - assert_eq!(rig.offset("outer"), Some((0.0, 16.0 * k)), "{mode:?}"); - // Back to the start, then further: clamps at zero and the outer takes the rest of the way back. - rig.send(wheel(over, (0.0, -100_000.0), WheelUnit::Units)); - assert_eq!(rig.offset("inner"), Some((0.0, 0.0)), "{mode:?}"); - rig.send(wheel(over, (0.0, -4.0), WheelUnit::Units)); - assert_eq!(rig.offset("outer"), Some((0.0, 12.0 * k)), "{mode:?}"); - // A wheel off every pane moves nothing; the horizontal axis has no travel here. - let before = (rig.offset("inner"), rig.offset("outer")); - rig.send(wheel((outer.x - 0.5, outer.y - 0.5), (0.0, 10.0), WheelUnit::Units)); - rig.send(wheel(over, (10.0, 0.0), WheelUnit::Units)); - assert_eq!((rig.offset("inner"), rig.offset("outer")), before, "{mode:?}"); - } -} - -#[test] -fn a_wheel_line_is_one_cell_in_cells_and_the_body_text_size_in_pixels() { - let mut cells = Rig::new(MemState::new(), &nested_surface(), (Metrics::Cells, 1.0)); - cells.send(wheel(inside(cells.rect("inner")), (0.0, 3.0), WheelUnit::Lines)); - assert_eq!(cells.offset("inner"), Some((0.0, 3.0))); - for scale in [1.0, 1.5] { - let mut pixels = Rig::new(MemState::new(), &nested_surface(), (Metrics::Pixels, scale)); - pixels.send(wheel(inside(pixels.rect("inner")), (0.0, 2.0), WheelUnit::Lines)); - assert_eq!(pixels.offset("inner"), Some((0.0, 2.0 * 16.0 * scale))); - } -} - -#[test] -fn a_wheel_over_a_modal_never_scrolls_the_tree_beneath() { - let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]); - let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("modal", true, vec![fixed("dialog", 80.0, 48.0)])]), vec![decl("dismiss", &[])]); - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &document, mode); - rig.send(wheel(inside(rig.rect("pane")), (0.0, 16.0), WheelUnit::Units)); - assert_eq!(rig.offset("pane"), None, "{mode:?}"); - } -} - -// ----- press semantics ----- - -#[test] -fn a_press_released_elsewhere_or_with_another_button_or_after_a_cancel_activates_nothing() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let (a, b) = (inside(rig.rect("a")), inside(rig.rect("b"))); - // Down on a, up on b. - rig.send(down(a)); - rig.send(up(b)); - // Secondary and middle buttons never press. - for button in [PointerButton::Secondary, PointerButton::Middle] { - rig.send(InputEvent::PointerDown { at: a, button, modifiers: mods() }); - rig.send(InputEvent::PointerUp { at: a, button, modifiers: mods() }); - } - // Down, the platform takes the pointer, a stray up. - rig.send(down(a)); - rig.send(InputEvent::PointerCancel); - rig.send(up(a)); - // An up with no press. - rig.send(up(a)); - assert_eq!(rig.minted(), vec![], "{mode:?}"); - // And the same button down and up mints once. - rig.click(a); - assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); - } -} - -#[test] -fn a_secondary_up_does_not_release_a_primary_press() { - let mut rig = Rig::new(MemState::new(), &controls_surface(), MODES[0]); - let a = inside(rig.rect("a")); - rig.send(down(a)); - rig.send(InputEvent::PointerUp { at: a, button: PointerButton::Secondary, modifiers: mods() }); - assert_eq!(rig.minted(), vec![]); - rig.send(up(a)); - assert_eq!(commands_of(&rig.minted()), ["go"]); -} - -#[test] -fn a_busy_button_mints_once_however_often_it_is_pressed() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let a = inside(rig.rect("a")); - assert_eq!(rig.click(a), vec![]); - assert_eq!(rig.click(a), vec![], "{mode:?}: a busy press is silent, not a refusal"); - assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); - // The user sees it: the busy button is drawn disabled. - rig.draw(); - let disabled = Theme::std().colors["thing.control.disabled"].clone(); - assert!(rig.rendered.commands.iter().any(|c| matches!(c, thing_core::render::RenderCommand::FillRect { color, .. } if *color == disabled)), "{mode:?}"); - } -} - -#[test] -fn a_toggle_flips_its_draft_and_fires_on_change_once_per_press() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let flag = inside(rig.rect("flag")); - rig.click(flag); - let first = rig.minted(); - assert_eq!(commands_of(&first), ["flip"], "{mode:?}"); - assert_eq!(first[0].captured[0].value, InputValue::Bool(BoolValue { value: true }), "{mode:?}"); - assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true }))); - // A second press is a change to a control with an invocation waiting: it is refused and says so, it - // fires nothing more, and it leaves the draft that was sent (a busy control holds no unsent value). - let said = rig.click(flag); - assert_eq!(said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect::>(), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}"); - assert_eq!(rig.minted(), vec![], "{mode:?}"); - assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true })), "{mode:?}"); - } -} - -#[test] -fn a_slider_drag_writes_snapped_drafts_and_commits_once_wherever_it_is_released() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let track = rig.rect("level"); - let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); - let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); - rig.send(down(along(0.34))); - assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: 34 snaps to the step from min"); - rig.send(mv(along(0.76))); - assert_eq!(rig.draft("level"), value(80.0), "{mode:?}"); - // The drag is shown while it is made. - rig.draw(); - let thumb = |rig: &Rig| rig.rendered.commands.iter().filter_map(|c| match c { - thing_core::render::RenderCommand::FillRect { rect, .. } if rect.w <= track.h.max(1.0) + 0.01 && rect.h > 0.0 => Some(rect.x), - _ => None, - }).last(); - assert!(thumb(&rig).is_some()); - // Released far outside the track, even outside the pane: one commit of the last draft. - rig.send(mv((track.x + track.w * 3.0, track.y + 500.0))); - assert_eq!(rig.draft("level"), value(100.0), "{mode:?}: past the end clamps"); - rig.send(up((track.x - 900.0, track.y - 900.0))); - let minted = rig.minted(); - assert_eq!(commands_of(&minted), ["set"], "{mode:?}"); - assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 100.0 }), "{mode:?}"); - // Moving after the up changes nothing. - rig.send(mv(along(0.1))); - assert_eq!(rig.draft("level"), value(100.0), "{mode:?}"); - } -} - -#[test] -fn a_cancelled_slider_press_leaves_the_draft_it_found_and_fires_nothing() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let track = rig.rect("level"); - let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); - // No draft before: a press then a cancel leaves none, and a stray up commits nothing. - rig.send(down(along(0.5))); - assert!(rig.draft("level").is_some()); - rig.send(InputEvent::PointerCancel); - rig.send(up(along(0.5))); - assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?}"); - // A draft that is already waiting on a result comes back as it was. - rig.send(down(along(0.3))); - rig.send(up(along(0.3))); - assert_eq!(commands_of(&rig.minted()), ["set"]); - let held = rig.draft("level"); - rig.send(down(along(0.9))); - rig.send(mv(along(0.2))); - rig.send(InputEvent::PointerCancel); - assert_eq!((rig.draft("level"), rig.minted()), (held, vec![]), "{mode:?}"); - } -} - -#[test] -fn a_press_on_a_select_or_a_text_input_does_nothing_yet() { - for mode in MODES { - let mut state = MemState::from_fixture(Fixture::F04Form); - state::script(Fixture::F04Form, &mut state); - let document = Fixture::F04Form.load().surfaces.remove(0); - let mut rig = Rig::new(state, &document, mode); - for id in ["theme", "port"] { - assert_eq!(rig.click(inside(rig.rect(id))), vec![], "{mode:?} {id}"); - } - assert_eq!((rig.minted(), rig.drafts.is_empty()), (vec![], true), "{mode:?}"); - } -} - -#[test] -fn a_click_while_a_command_waits_for_confirmation_is_a_refusal_the_event_returns() { - for mode in MODES { - let mut document = surface(column("root", None, Overflow::Visible, vec![button("a", "ask", 160.0, 48.0), button("b", "go", 160.0, 48.0)]), vec![decl("ask", &[]), decl("go", &[])]); - document.commands[0].confirm = Some("Sure?".into()); - let mut rig = Rig::new(MemState::new(), &document, mode); - assert_eq!(rig.click(inside(rig.rect("a"))), vec![]); - assert!(rig.commands.confirming().is_some() && rig.minted().is_empty(), "{mode:?}"); - let said = rig.click(inside(rig.rect("b"))); - assert_eq!(said.iter().map(|d| d.code).collect::>(), vec![Code::ActivationRefused], "{mode:?}"); - assert_eq!(said[0].node.as_ref().map(NodeId::as_str), Some("b")); - } -} - -// ----- a control that takes no change holds no unsent value ----- - -fn result_change(sent: &CommandInvocation, clear: bool) -> Change { - let result = CommandResult::completed(sent, seq(1), None, clear, None); - let address = Address { provider: ProviderId::new(PROVIDER), schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(result.record_key()) }; - Change::Upsert(Entry { address, record: Record::Result(result) }) -} - -fn refusals(said: &[Diagnostic]) -> Vec<(Code, Option<&str>)> { - said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect() -} - -#[test] -fn a_slider_that_waits_for_its_result_takes_no_press_or_drag_and_a_completion_leaves_no_stray_draft() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let track = rig.rect("level"); - let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); - let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); - rig.send(down(along(0.3))); - rig.send(up(along(0.3))); - let sent = rig.minted().remove(0); - assert_eq!(rig.draft("level"), value(30.0), "{mode:?}"); - // The slider waits: a second press and its drag are refused, say so, and write nothing. - assert_eq!(refusals(&rig.send(down(along(0.8)))), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}"); - assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: the press wrote nothing"); - rig.send(mv(along(0.9))); - assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: a refused press starts no drag"); - assert_eq!(rig.send(up(along(0.9))), vec![], "{mode:?}"); - assert_eq!(rig.minted(), vec![], "{mode:?}"); - // The result clears the draft that was sent, and nothing else is left drawn on the slider. - let tree = &rig.tree; - rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger); - assert_eq!(rig.draft("level"), None, "{mode:?}"); - } -} - -#[test] -fn a_toggle_pressed_while_it_waits_is_refused_and_a_completion_leaves_the_provider_true() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let flag = inside(rig.rect("flag")); - rig.click(flag); - let sent = rig.minted().remove(0); - assert_eq!(refusals(&rig.click(flag)), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}"); - let tree = &rig.tree; - rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger); - assert_eq!(rig.draft("flag"), None, "{mode:?}: nothing survives to show a checked box the provider does not hold"); - } -} - -#[test] -fn a_slider_press_while_a_command_waits_for_confirmation_writes_no_draft() { - for mode in MODES { - let mut document = controls_surface(); - document.commands.iter_mut().find(|c| c.id.as_str() == "go").unwrap().confirm = Some("Sure?".into()); - let mut rig = Rig::new(MemState::new(), &document, mode); - rig.click(inside(rig.rect("a"))); - assert!(rig.commands.confirming().is_some(), "{mode:?}"); - let track = rig.rect("level"); - let said = rig.send(down((track.x + 0.5 * track.w, track.y + 0.5))); - assert_eq!(refusals(&said), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}"); - assert_eq!((rig.draft("level"), rig.drafts.is_empty()), (None, true), "{mode:?}"); +impl Placement { + fn rect(&self, id: &str) -> Rect { + self.0.iter().find(|placed| placed.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect } } @@ -869,7 +137,7 @@ impl Host { fn core_frame_routes_a_click_to_the_one_activation_primitive() { for mode in MODES { let document = modal_surface(); - let rig = Rig::new(MemState::new(), &document, mode); + let rig = placement(MemState::new(), &document, mode); let mut host = Host::new(MemState::new(), &document, mode); let output = host.frame(vec![down(inside(rig.rect("confirm"))), up(inside(rig.rect("confirm")))]); assert_eq!(commands_of(&output.outbound), ["confirm"], "{mode:?}"); @@ -886,7 +154,7 @@ fn core_frame_routes_a_click_to_the_one_activation_primitive() { fn events_in_one_frame_act_on_the_frame_the_user_saw_and_the_next_frame_draws_their_result() { for mode in MODES { let document = rows_surface(); - let rig = Rig::new(feed(), &document, mode); + let rig = placement(feed(), &document, mode); let (r0, r1) = (rig.rect(row_id("item-0000", "row").as_str()), rig.rect(row_id("item-0001", "row").as_str())); let step = r1.y - r0.y; let mut host = Host::new(feed(), &document, mode); @@ -911,7 +179,7 @@ fn a_click_is_judged_against_the_values_the_user_saw_not_the_ones_the_provider_w let document = fixture.load().surfaces.remove(0); let mut seen = MemState::from_fixture(fixture); state::script(fixture, &mut seen); - let toggle = inside(Rig::new(seen, &document, mode).rect("enabled")); + let toggle = inside(placement(seen, &document, mode).rect("enabled")); let mut host = Host::new(state, &document, mode); // The user saw `enabled` checked. In the frame they click it the provider writes it unchecked. host.state.put_state(&ProviderId::new("provider.settings"), "current", &Settings { enabled: false, volume: 40.0, theme: "dark".into() }); @@ -926,7 +194,7 @@ fn a_surface_left_mid_press_drops_the_press_and_a_stray_up_does_nothing() { let (one, mut two) = (controls_surface(), controls_surface()); two.label = seg("other"); let mode = MODES[0]; - let rig = Rig::new(MemState::new(), &one, mode); + let rig = placement(MemState::new(), &one, mode); let mut state = MemState::new(); state.put(&one.provider_id, &one); state.put(&two.provider_id, &two); @@ -938,160 +206,3 @@ fn a_surface_left_mid_press_drops_the_press_and_a_stray_up_does_nothing() { let output = host.frame(vec![up((track.x + 0.5 * track.w, track.y + 0.5))]); assert!(output.outbound.is_empty()); } - -#[test] -fn input_other_than_the_pointer_changes_nothing() { - let mut rig = Rig::new(MemState::new(), &controls_surface(), MODES[0]); - let before = (rig.rendered.clone(), rig.drafts.len()); - for event in [ - InputEvent::Key { key: thing_core::input::Key::Enter, modifiers: mods(), repeat: false }, - InputEvent::Text("x".into()), - InputEvent::Compose { text: "か".into(), cursor: None }, - InputEvent::Focus(true), - ] { - assert_eq!(rig.send(event), vec![]); - } - assert_eq!((rig.minted(), rig.drafts.len()), (vec![], before.1)); -} - -// ----- the cases the mutants found open ----- - -fn lone_slider(min: f64, max: f64, step: f64) -> SurfaceDocument { - let slider = Node::Slider(SliderNode { common: common("level"), min, max, step, value: lit_number(min), commit: command("set") }); - surface(indented("root", vec![slider]), vec![decl("set", &["level"])]) -} - -#[test] -fn a_slider_snaps_from_its_own_minimum_and_follows_its_own_track() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &lone_slider(20.0, 120.0, 10.0), mode); - let track = rig.rect("level"); - assert!(track.x > 0.0, "{mode:?}: the track does not start at the root's edge"); - let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5); - let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); - rig.send(down(along(0.0))); - assert_eq!(rig.draft("level"), value(20.0), "{mode:?}: the track's left edge is the minimum"); - rig.send(mv(along(0.47))); - assert_eq!(rig.draft("level"), value(70.0), "{mode:?}: 20 + 47 = 67 snaps to 70 from 20"); - rig.send(mv(along(1.0))); - assert_eq!(rig.draft("level"), value(120.0), "{mode:?}"); - // A move that is not a position is not a value. - rig.send(mv((f32::NAN, track.y))); - assert_eq!(rig.draft("level"), value(120.0), "{mode:?}"); - } -} - -#[test] -fn a_track_that_shrinks_to_nothing_mid_drag_leaves_the_draft_as_it_was() { - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &controls_surface(), mode); - let track = rig.rect("level"); - let value = |v: f64| Some(InputValue::Number(NumberValue { value: v })); - rig.send(down((track.x + 0.5 * track.w, track.y + 0.5))); - assert_eq!(rig.draft("level"), value(50.0), "{mode:?}"); - // The surface shrinks under the pointer: the slider's rect is now zero wide. - for placed in rig.rendered.placed.iter_mut().filter(|placed| placed.id.as_str() == "level") { - placed.rect.w = 0.0; - } - // At the track's left edge (0 over 0) and past it (n over 0): neither is a value. - for x in [track.x, track.x + 10.0] { - rig.send(mv((x, track.y + 0.5))); - assert_eq!(rig.draft("level"), value(50.0), "{mode:?}: a move over a zero-width track at {x}"); - } - rig.send(up((track.x, track.y))); - let minted = rig.minted(); - assert_eq!(minted.len(), 1, "{mode:?}"); - assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 50.0 }), "{mode:?}"); - } -} - -#[test] -fn a_slider_with_no_range_or_a_step_of_zero_is_handled_by_what_it_declares() { - for mode in MODES { - for (min, max) in [(5.0, 5.0), (0.0, f64::INFINITY), (9.0, 3.0)] { - let mut rig = Rig::new(MemState::new(), &lone_slider(min, max, 1.0), mode); - let at = inside(rig.rect("level")); - rig.click(at); - assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?} {min}..{max}"); - } - // No step: the raw position, unsnapped. - let mut rig = Rig::new(MemState::new(), &lone_slider(0.0, 100.0, 0.0), mode); - let track = rig.rect("level"); - rig.send(down((track.x + 0.25 * track.w, track.y + 0.5))); - assert_eq!(rig.draft("level"), Some(InputValue::Number(NumberValue { value: 25.0 })), "{mode:?}"); - } -} - -#[test] -fn a_press_on_a_text_input_or_a_select_does_not_fall_through_to_the_button_around_it() { - let input = Node::TextInput(TextInputNode { - common: common("field"), - multiline: false, - input_kind: InputKind::Text, - placeholder: lit_text(""), - initial: lit_text("x"), - submit: command("go"), - }); - let select = Node::Select(SelectNode { - common: common("choice"), - options: OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "A".into() }] }), - value: record_bind(path(&["Theme"]), None), - on_change: command("go"), - }); - let card = Node::Button(ButtonNode { - common: common("card"), - content: vec![fixed("pad", 160.0, 16.0), input, select], - on_activate: command("go"), - enabled: lit_bool(true), - }); - for mode in MODES { - let document = surface(column("root", None, Overflow::Visible, vec![card.clone()]), vec![decl("go", &[])]); - let mut rig = Rig::new(MemState::new(), &document, mode); - for id in ["field", "choice"] { - let r = rig.rect(id); - assert!(r.w >= 1.0 && r.h >= 1.0, "{mode:?} {id}"); - assert_eq!(rig.click(inside(r)), vec![], "{mode:?} {id}"); - } - assert_eq!(rig.minted(), vec![], "{mode:?}: the card around them was not pressed"); - // The card itself still is. - rig.click(inside(rig.rect("pad"))); - assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); - } -} - -#[test] -fn a_wheel_that_is_not_a_number_or_runs_on_a_bad_scale_is_ignored_or_taken_at_one() { - let mut rig = Rig::new(MemState::new(), &nested_surface(), (Metrics::Pixels, 1.5)); - let over = inside(rig.rect("inner")); - // The scale the host gave is not usable: the offset is the wheel's units as they are. - for bad in [0.0, f32::INFINITY, f32::NAN, -2.0] { - rig.scroll = ScrollOffsets::default(); - rig.scale = bad; - rig.send(wheel(over, (0.0, 10.0), WheelUnit::Units)); - assert_eq!(rig.offset("inner"), Some((0.0, 10.0)), "scale {bad}"); - } - // A delta that is not a number moves nothing, and does not reset what is scrolled. - rig.scale = 1.5; - rig.scroll.set(nid("inner"), (0.0, 30.0)); - for bad in [f32::NAN, f32::INFINITY] { - rig.send(wheel(over, (0.0, bad), WheelUnit::Units)); - rig.send(wheel(over, (bad, 0.0), WheelUnit::Units)); - assert_eq!(rig.offset("inner"), Some((0.0, 30.0)), "delta {bad}"); - } -} - -#[test] -fn a_wheel_scrolls_the_horizontal_axis_by_its_own_delta() { - let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("wide", 400.0, 400.0)]); - let document = surface(column("root", None, Overflow::Visible, vec![pane]), vec![]); - for mode in MODES { - let mut rig = Rig::new(MemState::new(), &document, mode); - let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 }; - let over = inside(rig.rect("pane")); - assert!(rig.max_scroll("pane").0 > 0.0 && rig.max_scroll("pane").1 > 0.0, "{mode:?}"); - rig.send(wheel(over, (8.0, 4.0), WheelUnit::Units)); - assert_eq!(rig.offset("pane"), Some((8.0 * k, 4.0 * k)), "{mode:?}"); - rig.send(wheel(over, (-2.0, 0.0), WheelUnit::Units)); - assert_eq!(rig.offset("pane"), Some((6.0 * k, 4.0 * k)), "{mode:?}"); - } -} diff --git a/crates/thing-core/tests/support/mod.rs b/crates/thing-core/tests/support/mod.rs new file mode 100644 index 0000000..1e0effa --- /dev/null +++ b/crates/thing-core/tests/support/mod.rs @@ -0,0 +1,189 @@ +//! The surfaces the pointer tests share: contract documents only, so the same text is built into the +//! integration tests (through `thing_core`) and into the crate's own (through `crate`), whose types +//! differ though these do not. +#![allow(dead_code)] + +use thing_contract::*; +use thing_testkit::build::*; + +pub const PROVIDER: &str = "provider.pointer"; + +pub const FEED: &str = "provider.feed"; + +// ----- surfaces ----- + +pub fn decl(id: &str, captures: &[&str]) -> CommandDecl { + CommandDecl { + id: CommandId::new(id), + payload_schema: SchemaId::new(format!("gamecult.thing.test.{id}.v1")), + captures: captures.iter().map(|node| nid(node)).collect(), + confirm: None, + } +} + +pub fn column(id: &str, size: Option<(f64, f64)>, overflow: Overflow, children: Vec) -> Node { + let size = size.map_or(size2(Dimension::Percent(Scalar { value: 100.0 }), Dimension::Content), |(w, h)| size2(px(w), px(h))); + let style = BoxStyle { + size, + overflow, + padding: edges(px(0.0)), + gap: size2(px(0.0), px(0.0)), + grow: 0.0, + justify_content: ContentAlign::Start, + ..style() + }; + Node::Box(BoxNode { common: common(id), style, paint: plain_paint(), role: Role::Group, children }) +} + +/// A box of exactly `w` x `h` authored px (a whole number of cells when both are multiples of 8 and 16). +pub fn fixed(id: &str, w: f64, h: f64) -> Node { + column(id, Some((w, h)), Overflow::Visible, vec![]) +} + +pub fn button(id: &str, cmd: &str, w: f64, h: f64) -> Node { + Node::Button(ButtonNode { common: common(id), content: vec![fixed(&format!("{id}-body"), w, h)], on_activate: command(cmd), enabled: lit_bool(true) }) +} + +pub fn overlay(id: &str, modal: bool, children: Vec) -> Node { + Node::Overlay(OverlayNode { common: common(id), anchor: Anchor::Viewport, modal, dismiss: command("dismiss"), children }) +} + +pub fn surface(root: Node, commands: Vec) -> SurfaceDocument { + SurfaceDocument { provider_id: ProviderId::new(PROVIDER), label: seg("pointer"), version: ver(1), title: "t".into(), root, commands } +} + +/// A main-tree button under a modal overlay whose dialog holds one button. +pub fn modal_surface() -> SurfaceDocument { + let dialog = column("dialog", Some((160.0, 96.0)), Overflow::Visible, vec![button("confirm", "confirm", 160.0, 48.0)]); + surface( + column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), overlay("modal", true, vec![dialog])]), + vec![decl("behind", &[]), decl("confirm", &[]), decl("dismiss", &[])], + ) +} + +/// A 160 x 160 scroll pane of twenty buttons, one per feed item, with a button below it. +pub fn rows_surface() -> SurfaceDocument { + let rows = Node::Repeat(RepeatNode { + common: common("rows"), + collection: CollectionSource::Records(RecordsSource { + provider: Some(ProviderId::new(FEED)), + schema: SchemaId::new("gamecult.thing.test.item.v1"), + key_prefix: "item-".into(), + }), + key_member: path(&["Id"]), + template: std::boxed::Box::new(button("row", "pick", 160.0, 48.0)), + }); + surface( + column("root", None, Overflow::Visible, vec![column("pane", Some((160.0, 160.0)), Overflow::Scroll, vec![rows]), button("below", "below", 160.0, 48.0)]), + vec![decl("pick", &[]), decl("below", &[])], + ) +} + +/// A pane inside a pane, each scrolling: the inner is 80 tall with 400 of content, the outer 160 tall +/// with the inner above 400 more. +pub fn nested_surface() -> SurfaceDocument { + let inner = column("inner", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("inner-fill", 160.0, 400.0)]); + surface(column("root", None, Overflow::Visible, vec![column("outer", Some((160.0, 160.0)), Overflow::Scroll, vec![inner, fixed("outer-fill", 160.0, 400.0)])]), vec![]) +} + +/// A tall button inside a clip, with room below the clip that the button's own rect also covers. +pub fn clip_surface() -> SurfaceDocument { + surface( + column("root", None, Overflow::Visible, vec![column("frame", Some((160.0, 64.0)), Overflow::Clip, vec![button("tall", "tall", 160.0, 320.0)])]), + vec![decl("tall", &[])], + ) +} + +/// A root with a 16px left margin, so no control's rect starts where the root's does. +pub fn indented(id: &str, children: Vec) -> Node { + let mut root = column(id, None, Overflow::Visible, children); + if let Node::Box(b) = &mut root { + b.style.padding.left = px(16.0); + } + root +} + +pub fn controls_surface() -> SurfaceDocument { + let slider = Node::Slider(SliderNode { common: common("level"), min: 0.0, max: 100.0, step: 10.0, value: lit_number(0.0), commit: command("set") }); + let toggle = Node::Toggle(ToggleNode { common: common("flag"), checked: lit_bool(false), on_change: command("flip") }); + surface( + indented("root", vec![button("a", "go", 160.0, 48.0), button("b", "go", 160.0, 48.0), toggle, slider]), + vec![decl("go", &[]), decl("flip", &["flag"]), decl("set", &["level"])], + ) +} + +// ----- the edge of a node, at a scale that does not divide ----- + +/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale. +pub fn seam_surface() -> SurfaceDocument { + let row = |id: &str, h: f64, widths: &[f64]| { + let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect()); + if let Node::Box(b) = &mut row { + b.style.direction = Direction::Row; + b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h)); + b.style.justify_content = ContentAlign::Start; + } + row + }; + surface( + column("root", None, Overflow::Visible, vec![ + row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]), + row("r1", 13.0, &[11.0, 3.0, 17.0]), + row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]), + row("r3", 19.0, &[23.0, 29.0, 13.0]), + ]), + vec![], + ) +} + +// ----- a non-modal overlay ----- + +pub fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument { + let pop = Node::Overlay(OverlayNode { common: common("pop"), anchor, modal: false, dismiss: command("dismiss"), children: vec![button("pop-button", "inside", 80.0, 48.0)] }); + surface( + column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), button("other", "other", 320.0, 48.0), pop]), + vec![decl("behind", &[]), decl("other", &[]), decl("inside", &[]), decl("dismiss", &[])], + ) +} + +// ----- the cases the mutants found open ----- + +pub fn lone_slider(min: f64, max: f64, step: f64) -> SurfaceDocument { + let slider = Node::Slider(SliderNode { common: common("level"), min, max, step, value: lit_number(min), commit: command("set") }); + surface(indented("root", vec![slider]), vec![decl("set", &["level"])]) +} + +/// A board with an absolute target standing inside it, away from its corner. +pub fn target_surface() -> SurfaceDocument { + let mut over = style(); + over.position = Position::Absolute; + over.inset = Edges { top: px(64.0), right: Dimension::Auto, bottom: Dimension::Auto, left: px(96.0) }; + over.size = size2(px(48.0), px(48.0)); + let target = Node::Box(BoxNode { common: common("target"), style: over, paint: plain_paint(), role: Role::Group, children: vec![] }); + surface(column("root", Some((320.0, 160.0)), Overflow::Visible, vec![fixed("board", 320.0, 160.0), target]), vec![]) +} + +/// A Select and a TextInput side by side, outside any button. +pub fn fields_surface() -> SurfaceDocument { + let (field, choice) = fields(); + surface(indented("root", vec![field, choice]), vec![decl("go", &[])]) +} + +/// A TextInput and a Select, each firing `go`. +pub fn fields() -> (Node, Node) { + let input = Node::TextInput(TextInputNode { + common: common("field"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text(""), + initial: lit_text("x"), + submit: command("go"), + }); + let select = Node::Select(SelectNode { + common: common("choice"), + options: OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "A".into() }] }), + value: record_bind(path(&["Theme"]), None), + on_change: command("go"), + }); + (input, select) +}