From ab61ffe01ae30885e8ef5c3c1797122933dcf746 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 11:07:36 +0100 Subject: [PATCH] Implement Select chooser overlay, input routing, and tests --- crates/thing-core/src/frame.rs | 13 +- crates/thing-core/src/input/chooser.rs | 133 +++++ crates/thing-core/src/input/focus.rs | 2 +- crates/thing-core/src/input/keys.rs | 26 +- crates/thing-core/src/input/mod.rs | 3 +- crates/thing-core/src/input/pointer.rs | 37 +- crates/thing-core/src/input/session.rs | 83 +++- crates/thing-core/src/input/tests.rs | 22 +- crates/thing-core/src/theme.rs | 1 + crates/thing-core/tests/chooser.rs | 663 +++++++++++++++++++++++++ crates/thing-core/tests/render.rs | 37 +- crates/thing-tui/tests/screen.rs | 42 +- 12 files changed, 1013 insertions(+), 49 deletions(-) create mode 100644 crates/thing-core/src/input/chooser.rs create mode 100644 crates/thing-core/tests/chooser.rs diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index 4928c29..58ef629 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -11,7 +11,7 @@ use crate::bind::{Binder, BoundTree}; use crate::command::{Activation, Commands, Confirming, HostEffect, Resume}; use crate::diagnostic::{Code, Diagnostic}; use crate::input::{Drafts, Input, InputEvent, Owners, Seen}; -use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; +use crate::layout::{CELL_PX, LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort}; use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, render}; use crate::resolve::{Limits, Resolver}; @@ -299,7 +299,16 @@ impl Core { if bound.locate(&session.owner).is_none() { self.input.clear_session(); } else { - let (overlay, texts) = session.build_overlay(); + let room_below = self.last.as_ref().and_then(|(_, _, rendered)| { + rendered.placed.iter().find(|p| p.id == session.owner).map(|p| { + let units = (viewport.1 - p.rect.y.max(0.0)).max(0.0); + match self.metrics { + Metrics::Pixels => units, + Metrics::Cells => units * CELL_PX.1, + } + }) + }); + let (overlay, texts) = session.build_overlay_in(room_below, self.metrics); match bound.with_overlay(overlay, texts) { Ok(with) => spliced = Some(with), Err(colliding) => { diff --git a/crates/thing-core/src/input/chooser.rs b/crates/thing-core/src/input/chooser.rs new file mode 100644 index 0000000..d9f350e --- /dev/null +++ b/crates/thing-core/src/input/chooser.rs @@ -0,0 +1,133 @@ +//! Select chooser lifecycle: opening, keyboard highlight navigation, choosing through +//! `ActivationKind::Change(Choice)`, and revealing the highlighted row into `ScrollOffsets`. + +use thing_contract::{ChoiceValue, InputValue, NodeId}; + +use super::drafts::current; +use super::event::Key; +use super::focus; +use super::pointer::{Owners, Seen}; +use super::session::SessionOverlay; +use crate::bind::{Bound, Field}; +use crate::command::{Activation, ActivationKind}; +use crate::diagnostic::Diagnostic; +use crate::layout::LaidTree; +use crate::render::ScrollOffsets; +use crate::time::Timestamp; + +/// Open a Select chooser on `select` when not refused and `Field::Options` is non-empty. +/// Replaces any open session overlay. +pub(super) fn open( + session: &mut Option, + select: NodeId, + seen: &Seen<'_>, + owners: &mut Owners<'_>, +) -> Vec { + if owners.commands.refuses_change(seen.tree, &select).is_some() { + return Vec::new(); + } + let Some(Bound::Options(options)) = seen.tree.value(&select, Field::Options) else { + return Vec::new(); + }; + if options.is_empty() { + return Vec::new(); + } + let selected = match current(seen.tree, Some(owners.drafts), &select, Field::Selected).as_deref() { + Some(Bound::Text(value)) => options.iter().position(|option| &option.value == value), + _ => None, + }; + let rows = options.iter().map(|option| (option.value.clone(), option.label.clone())).collect(); + owners.scroll.set(SessionOverlay::list_id_for(&select), (0.0, 0.0)); + *session = Some(SessionOverlay::select_with(select, rows, selected)); + Vec::new() +} + +/// Handle a key while the Select chooser is open. Every key stays within the chooser scope. +pub(super) fn key( + session: &mut Option, + key: Key, + repeat: bool, + seen: &Seen<'_>, + owners: &mut Owners<'_>, + now: Timestamp, +) -> Vec { + let Some(active) = session.as_mut() else { + return Vec::new(); + }; + if active.rows.is_empty() { + return Vec::new(); + } + let last = active.rows.len() - 1; + match key { + Key::Up => { + active.highlight = active.highlight.saturating_sub(1); + active.reveal = true; + } + Key::Down => { + active.highlight = (active.highlight + 1).min(last); + active.reveal = true; + } + Key::Home => { + active.highlight = 0; + active.reveal = true; + } + Key::End => { + active.highlight = last; + active.reveal = true; + } + Key::PageUp => { + let page = page_rows(active, seen.laid); + active.highlight = active.highlight.saturating_sub(page); + active.reveal = true; + } + Key::PageDown => { + let page = page_rows(active, seen.laid); + active.highlight = (active.highlight + page).min(last); + active.reveal = true; + } + Key::Enter | Key::Char(' ') => { + if repeat { + return Vec::new(); + } + let Some((_, row)) = active.rows.get(active.highlight) else { + return Vec::new(); + }; + let act = Activation { + node: active.owner.clone(), + kind: ActivationKind::Change(InputValue::Choice(ChoiceValue { value: row.value.clone() })), + }; + *session = None; + return owners.commands.activate(act, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger); + } + _ => {} + } + Vec::new() +} + +/// Reveal the highlighted row inside the chooser list's `ScrollOffsets` when flagged. +pub(super) fn reveal(session: &mut SessionOverlay, laid: &LaidTree, scroll: &mut ScrollOffsets) { + if std::mem::take(&mut session.reveal) + && let Some((row_id, _)) = session.rows.get(session.highlight) + { + focus::reveal_node(laid, 0, row_id, scroll); + } +} + +fn page_rows(session: &SessionOverlay, laid: &LaidTree) -> usize { + let list_id = SessionOverlay::list_id_for(&session.owner); + let Some(list) = laid.nodes.iter().find(|n| n.id == list_id) else { + return 1; + }; + let visible_h = list.clip.map_or(list.rect.h, |clip| clip.h); + let Some((row0_id, _)) = session.rows.first() else { + return 1; + }; + let Some(row0) = laid.nodes.iter().find(|n| &n.id == row0_id) else { + return 1; + }; + if row0.rect.h > 0.0 && visible_h > 0.0 { + (visible_h / row0.rect.h).floor().max(1.0) as usize + } else { + 1 + } +} diff --git a/crates/thing-core/src/input/focus.rs b/crates/thing-core/src/input/focus.rs index 5d8375c..d9f0ce0 100644 --- a/crates/thing-core/src/input/focus.rs +++ b/crates/thing-core/src/input/focus.rs @@ -214,7 +214,7 @@ fn reveal_axis(start: f32, len: f32, clip_start: f32, clip_len: f32, offset: f32 offset.clamp(lo.min(hi), lo.max(hi)) } -fn reveal_node(laid: &LaidTree, floor: usize, id: &NodeId, scroll: &mut ScrollOffsets) { +pub(super) fn reveal_node(laid: &LaidTree, floor: usize, id: &NodeId, scroll: &mut ScrollOffsets) { let Some(pos) = laid.nodes[floor..].iter().position(|n| &n.id == id) else { return }; let mut rect = laid.nodes[floor + pos].rect; let mut parent = laid.nodes[floor + pos].parent.map(|p| p as usize); diff --git a/crates/thing-core/src/input/keys.rs b/crates/thing-core/src/input/keys.rs index a0c2dbf..09c5b10 100644 --- a/crates/thing-core/src/input/keys.rs +++ b/crates/thing-core/src/input/keys.rs @@ -3,6 +3,7 @@ use thing_contract::{InputValue, Node, NumberValue}; +use super::chooser; use super::drafts::current; use super::event::{Key, Modifiers}; use super::focus::Focus; @@ -25,12 +26,13 @@ pub(super) fn key( owners: &mut Owners<'_>, now: Timestamp, ) -> Vec { - if modifiers.ctrl || modifiers.alt || modifiers.meta { + let allow_alt_down = modifiers.alt && !modifiers.ctrl && !modifiers.meta && !modifiers.shift && key == Key::Down; + if modifiers.ctrl || modifiers.meta || (modifiers.alt && !allow_alt_down) { return Vec::new(); } let index = seen.tree.index(); let floor = hit::modal_floor(seen.laid, &index); - if key == Key::Escape { + if key == Key::Escape && !modifiers.alt { if session.is_some() { if !repeat { *session = None; @@ -46,17 +48,29 @@ pub(super) fn key( } return Vec::new(); } - if key == Key::Tab { + if key == Key::Tab && !modifiers.alt { *session = None; focus.step(modifiers.shift, seen.laid); return Vec::new(); } + if session.is_some() { + if modifiers.alt { + return Vec::new(); + } + return chooser::key(session, key, repeat, seen, owners, now); + } let Some(focused) = focus.node().cloned() else { return Vec::new(); }; let Some(node) = index.get(&focused).copied() else { return Vec::new(); }; + if modifiers.alt { + if matches!(node, Node::Select(_)) && !repeat { + return chooser::open(session, focused, seen, owners); + } + return Vec::new(); + } match node { Node::Button(_) if matches!(key, Key::Enter | Key::Char(' ')) => { if repeat { @@ -105,6 +119,12 @@ pub(super) fn key( let act = Activation { node: focused, kind: ActivationKind::Change(InputValue::Number(NumberValue { value })) }; owners.commands.activate(act, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger) } + Node::Select(_) if matches!(key, Key::Enter | Key::Char(' ') | Key::Down) => { + if repeat { + return Vec::new(); + } + chooser::open(session, focused, seen, owners) + } Node::TextInput(input) if !input.multiline && key == Key::Enter => { if repeat { return Vec::new(); diff --git a/crates/thing-core/src/input/mod.rs b/crates/thing-core/src/input/mod.rs index 1c1ec9b..b3170f0 100644 --- a/crates/thing-core/src/input/mod.rs +++ b/crates/thing-core/src/input/mod.rs @@ -3,7 +3,8 @@ //! user saw, keyboard focus, and the pointer and key routes that turn an event into an activation, //! a draft or a scroll offset. -pub mod drafts; +pub mod chooser; +mod drafts; pub mod event; mod focus; mod hit; diff --git a/crates/thing-core/src/input/pointer.rs b/crates/thing-core/src/input/pointer.rs index 999ab2b..33730ec 100644 --- a/crates/thing-core/src/input/pointer.rs +++ b/crates/thing-core/src/input/pointer.rs @@ -4,6 +4,7 @@ use thing_contract::{BoolValue, ChoiceValue, InputValue, Node, NodeId, NumberValue, SliderNode}; +use super::chooser; use super::drafts::{Drafts, current}; use super::event::{InputEvent, PointerButton, WheelUnit}; use super::focus::Focus; @@ -133,10 +134,12 @@ impl Input { pub(crate) fn reconcile(&mut self, tree: &BoundTree, laid: &LaidTree, scroll: &mut ScrollOffsets) { self.focus.reconcile(tree, laid, scroll); - if let Some(session) = &self.session - && self.focus.node() != Some(&session.owner) - { - self.session = None; + if let Some(session) = &mut self.session { + if self.focus.node() != Some(&session.owner) { + self.session = None; + } else { + chooser::reveal(session, laid, scroll); + } } } @@ -166,7 +169,7 @@ impl Input { InputEvent::PointerMove { at, .. } => return self.drag(*at, seen, owners, &surface), InputEvent::PointerUp { at, button: PointerButton::Primary, .. } => return self.up(*at, seen, owners, now, &surface), InputEvent::PointerCancel => self.cancel(&surface, owners.drafts), - InputEvent::Wheel { at, delta, unit, .. } => wheel(*at, *delta, *unit, seen, owners.scroll), + InputEvent::Wheel { at, delta, unit, .. } => wheel(*at, *delta, *unit, self.session.as_ref(), seen, owners.scroll), InputEvent::Key { key, modifiers, repeat } => return keys::key(&mut self.focus, &mut self.session, *key, *modifiers, *repeat, seen, owners, now), InputEvent::Focus(window) => { self.focus.set_window(*window); @@ -183,16 +186,20 @@ impl Input { // A press never starts over another: the one in progress ends first. self.cancel(surface, owners.drafts); let index = seen.tree.index(); - if let Some(session) = &self.session { + if let Some(session) = &mut self.session { if let Some(Reach::Node(i)) = reach(seen.rendered, seen.laid, &index, at, seen.k()) && session.contains(seen.laid, i) { - if let Some((row_id, _)) = session.target(seen.laid, i) { - self.pointer.press = Some(Press::SessionRow(row_id.clone())); + if let Some(idx) = session.row_index(seen.laid, i) { + session.highlight = idx; + session.reveal = false; + let row_id = session.rows[idx].0.clone(); + self.pointer.press = Some(Press::SessionRow(row_id)); } return Vec::new(); } self.session = None; + return Vec::new(); } let mut said = Vec::new(); let hit = target(seen.rendered, seen.laid, &index, at, seen.k()); @@ -246,9 +253,10 @@ impl Input { match pressed.control { Control::Button | Control::Scrim => Activation { node: pressed.node, kind: ActivationKind::Press }, Control::Toggle => toggle_activation(seen.tree, owners.drafts, pressed.node), - // A Select's chooser and a TextInput's editing are not here: a press on them does nothing, and - // does not fall through to a control around them. A Slider's press is a `Drag`, never a target. - Control::Slider | Control::Select | Control::TextInput => return Vec::new(), + Control::Select => return chooser::open(&mut self.session, pressed.node, seen, owners), + // A TextInput's editing is not here: a press on it does nothing, and does not + // fall through to a control around it. A Slider's press is a `Drag`, never a target. + Control::Slider | Control::TextInput => return Vec::new(), } } Some(Press::SessionRow(row_id)) => { @@ -331,9 +339,14 @@ pub(super) fn scroll_along(start: usize, axis: usize, mv: ScrollMove, laid: &Lai /// The wheel moves the nearest scroll node at or above what it is over, on the wheel's axis, that /// has room to move that way; at the end of its travel the next scroll ancestor takes it. Under a /// modal only the modal's own subtree is reachable. Offsets are held in device px (Pixels) or cells. -fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit, seen: &Seen<'_>, scroll: &mut ScrollOffsets) { +fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit, session: Option<&SessionOverlay>, seen: &Seen<'_>, scroll: &mut ScrollOffsets) { let index = seen.tree.index(); let Some(Reach::Node(start) | Reach::Scrim(start)) = reach(seen.rendered, seen.laid, &index, at, seen.k()) else { return }; + if let Some(session) = session + && !session.contains(seen.laid, start) + { + return; + } let per = match unit { WheelUnit::Units => seen.k(), WheelUnit::Lines => line_px(seen), diff --git a/crates/thing-core/src/input/session.rs b/crates/thing-core/src/input/session.rs index a863e5f..951e577 100644 --- a/crates/thing-core/src/input/session.rs +++ b/crates/thing-core/src/input/session.rs @@ -9,7 +9,7 @@ use thing_contract::{ TextSource, ThemeToken, Wrap, }; -use crate::layout::LaidTree; +use crate::layout::{CELL_PX, LaidTree, Metrics}; /// What kind of core-owned transient overlay is open. #[derive(Clone, Debug, PartialEq, Eq)] @@ -30,6 +30,9 @@ pub(crate) struct SessionOverlay { pub(crate) owner: NodeId, pub(crate) kind: SessionKind, pub(crate) rows: Vec<(NodeId, Row)>, + pub(crate) highlight: usize, + pub(crate) selected: Option, + pub(crate) reveal: bool, } fn px(value: f64) -> Dimension { @@ -74,11 +77,13 @@ fn column_style(size: Size2, min_size: Size2, position: Position, inset: Edges, } } +const ROW_HEIGHT_PX: f64 = 16.0; + impl SessionOverlay { - /// Construct a Select chooser overlay for `owner` with `(value, label)` options. - #[cfg(test)] - pub(crate) fn select(owner: NodeId, options: Vec<(String, String)>) -> Self { - let rows = options + /// Construct a Select chooser overlay for `owner` with `(value, label)` options and optional + /// pre-selected row index. + pub(crate) fn select_with(owner: NodeId, options: Vec<(String, String)>, selected: Option) -> Self { + let rows: Vec<_> = options .into_iter() .enumerate() .map(|(idx, (value, label))| { @@ -86,7 +91,16 @@ impl SessionOverlay { (row_id, Row { value, label }) }) .collect(); - Self { owner, kind: SessionKind::Select, rows } + let selected = selected.filter(|&i| i < rows.len()); + let highlight = selected.unwrap_or(0); + let reveal = !rows.is_empty(); + Self { owner, kind: SessionKind::Select, rows, highlight, selected, reveal } + } + + /// Construct a Select chooser overlay for `owner` with `(value, label)` options. + #[cfg(test)] + pub(crate) fn select(owner: NodeId, options: Vec<(String, String)>) -> Self { + Self::select_with(owner, options, None) } /// The core-minted id of this overlay's root `OverlayNode`. @@ -94,38 +108,66 @@ impl SessionOverlay { NodeId::new(format!("{}/session/0", self.owner.as_str())) } - /// Build the non-modal `OverlayNode` and `(NodeId, String)` content pairs for `BoundTree::with_overlay`. + /// The core-minted id of the list container for `owner`. + pub(crate) fn list_id_for(owner: &NodeId) -> NodeId { + NodeId::new(format!("{}/session/1", owner.as_str())) + } + + /// Build the non-modal `OverlayNode` and `(NodeId, String)` content pairs for `BoundTree::with_overlay`, + /// unconstrained by viewport room. + #[cfg(test)] pub(crate) fn build_overlay(&self) -> (OverlayNode, Vec<(NodeId, String)>) { + self.build_overlay_in(None, Metrics::Pixels) + } + + /// Build the non-modal `OverlayNode` and `(NodeId, String)` content pairs for `BoundTree::with_overlay`, + /// bounding height to `room_below` (authored logical px) with `Overflow::Scroll` when rows exceed it. + pub(crate) fn build_overlay_in(&self, room_below: Option, metrics: Metrics) -> (OverlayNode, Vec<(NodeId, String)>) { let mut children = Vec::with_capacity(self.rows.len()); let mut texts = Vec::with_capacity(self.rows.len()); for (idx, (row_id, row)) in self.rows.iter().enumerate() { let text_id = NodeId::new(format!("{}/session/{}", self.owner.as_str(), 2 + idx * 2 + 1)); - texts.push((text_id.clone(), row.label.clone())); + let display = if self.selected == Some(idx) { + format!("{} *", row.label) + } else { + row.label.clone() + }; + texts.push((text_id.clone(), display.clone())); let text = Node::Text(TextNode { common: common(text_id), - content: TextSource::Literal(TextLiteral { value: row.label.clone() }), + content: TextSource::Literal(TextLiteral { value: display }), style_token: "thing.text".into(), wrap: false, max_lines: None, selectable: false, }); + let background = (idx == self.highlight).then(|| ColorRef::Token(ThemeToken { name: "thing.selection".into() })); children.push(Node::Box(BoxNode { common: common(row_id.clone()), style: column_style( size2(Dimension::Percent(Scalar { value: 100.0 }), Dimension::Content), - size2(px(0.0), px(16.0)), + size2(px(0.0), px(ROW_HEIGHT_PX)), Position::Relative, edges(Dimension::Auto), Overflow::Visible, ), - paint: Paint { background: None, border: None, radius: 0.0 }, + paint: Paint { background, border: None, radius: 0.0 }, role: Role::ListItem, children: vec![text], })); } - let list_id = NodeId::new(format!("{}/session/1", self.owner.as_str())); + let border_h = match metrics { + Metrics::Pixels => 2.0, + Metrics::Cells => 2.0 * f64::from(CELL_PX.1), + }; + let content_h = self.rows.len() as f64 * ROW_HEIGHT_PX + border_h; + let (height, overflow) = match room_below { + Some(room) if content_h > f64::from(room) => (px(f64::from(room).max(0.0)), Overflow::Scroll), + _ => (Dimension::Content, Overflow::Visible), + }; + let list_id = Self::list_id_for(&self.owner); let inset = Edges { - top: Dimension::Percent(Scalar { value: 100.0 }), + top: px(0.0), left: px(0.0), right: Dimension::Auto, bottom: Dimension::Auto, @@ -133,11 +175,11 @@ impl SessionOverlay { let list = Node::Box(BoxNode { common: common(list_id), style: column_style( - size2(Dimension::Percent(Scalar { value: 100.0 }), Dimension::Content), + size2(Dimension::Percent(Scalar { value: 100.0 }), height), size2(px(0.0), px(0.0)), Position::Absolute, inset, - Overflow::Scroll, + overflow, ), paint: Paint { background: Some(ColorRef::Token(ThemeToken { name: "thing.surface".into() })), @@ -157,12 +199,12 @@ impl SessionOverlay { (overlay, texts) } - /// Resolve a laid node index (e.g. a row's Text child) to its enclosing session row, if any. - pub(crate) fn target(&self, laid: &LaidTree, index: usize) -> Option<&(NodeId, Row)> { + /// Resolve a laid node index (e.g. a row's Text child) to its row index in `self.rows`, if any. + pub(crate) fn row_index(&self, laid: &LaidTree, index: usize) -> Option { let mut at = Some(index); while let Some(i) = at { let laid_node = laid.nodes.get(i)?; - if let Some(found) = self.rows.iter().find(|(id, _)| id == &laid_node.id) { + if let Some(found) = self.rows.iter().position(|(id, _)| id == &laid_node.id) { return Some(found); } at = laid_node.parent.map(|p| p as usize); @@ -170,6 +212,11 @@ impl SessionOverlay { None } + /// Resolve a laid node index (e.g. a row's Text child) to its enclosing session row, if any. + pub(crate) fn target(&self, laid: &LaidTree, index: usize) -> Option<&(NodeId, Row)> { + self.row_index(laid, index).map(|idx| &self.rows[idx]) + } + /// Whether laid node `index` sits inside this session overlay. pub(crate) fn contains(&self, laid: &LaidTree, index: usize) -> bool { let root_id = self.overlay_id(); diff --git a/crates/thing-core/src/input/tests.rs b/crates/thing-core/src/input/tests.rs index 1e2ef03..13aa8c0 100644 --- a/crates/thing-core/src/input/tests.rs +++ b/crates/thing-core/src/input/tests.rs @@ -732,12 +732,11 @@ fn a_cancelled_slider_press_leaves_the_draft_it_found_and_fires_nothing() { } #[test] -fn a_press_on_a_select_or_a_text_input_does_nothing_yet() { +fn a_press_on_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.click(inside(rig.rect("field"))), vec![], "{mode:?} field"); + assert!(rig.input.session().is_none(), "{mode:?}"); assert_eq!((rig.minted(), rig.drafts.is_empty()), (vec![], true), "{mode:?}"); } } @@ -916,7 +915,10 @@ fn a_press_on_a_text_input_or_a_select_does_not_fall_through_to_the_button_aroun 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. + // Clicking "choice" opened its chooser; the first click on "pad" light-dismisses it without + // activating "card", and the second click presses "card". + rig.click(inside(rig.rect("pad"))); + assert_eq!(rig.minted(), vec![], "{mode:?}: light dismiss must not click through"); rig.click(inside(rig.rect("pad"))); assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}"); } @@ -1209,18 +1211,24 @@ fn session_overlay_skips_focus_order_hits_rows_without_blurring_and_light_dismis assert_eq!(commands_of(&rig.minted()), ["choose"], "{mode:?}"); assert_eq!(rig.draft("pick"), Some(InputValue::Choice(ChoiceValue { value: "b".into() })), "{mode:?}"); - // Re-open session: clicking outside (bottom of blank, below the overlay) light-dismisses and clears focus. + // Re-open session: clicking outside (bottom of blank, below the overlay) light-dismisses + // without clicking through; a second click outside clears focus. rig.input.open_session(select_session("pick")); let blank = rig.rect("blank"); rig.click((blank.x + 0.5, blank.y + blank.h - 0.5)); assert!(rig.input.session().is_none(), "{mode:?}"); + assert_eq!(rig.input.focus().node(), Some(&nid("pick")), "{mode:?}"); + rig.click((blank.x + 0.5, blank.y + blank.h - 0.5)); assert!(rig.input.focus().node().is_none(), "{mode:?}"); - // Re-open session: clicking outside on another button light-dismisses and activates that button. + // Re-open session: clicking outside on another button light-dismisses without activating + // that button; a second click activates it. rig.input.open_session(select_session("pick")); let other = rig.rect("other"); rig.click((other.x + 0.5, other.y + other.h - 0.5)); assert!(rig.input.session().is_none(), "{mode:?}"); + assert_eq!(rig.minted(), vec![], "{mode:?}: light dismiss must not click through"); + rig.click((other.x + 0.5, other.y + other.h - 0.5)); assert_eq!(rig.input.focus().node(), Some(&nid("other")), "{mode:?}"); assert_eq!(commands_of(&rig.minted()), ["other"], "{mode:?}"); } diff --git a/crates/thing-core/src/theme.rs b/crates/thing-core/src/theme.rs index c996abb..241b600 100644 --- a/crates/thing-core/src/theme.rs +++ b/crates/thing-core/src/theme.rs @@ -50,6 +50,7 @@ impl Theme { ("thing.control.disabled", 0x3a3a48ff), ("thing.plot.mark", 0x7c9cffff), ("thing.focus", 0xb4befeff), + ("thing.selection", 0x3b4261ff), ] .into_iter() .map(|(name, hex)| (name.to_string(), rgba(hex))) diff --git a/crates/thing-core/tests/chooser.rs b/crates/thing-core/tests/chooser.rs new file mode 100644 index 0000000..0d3605d --- /dev/null +++ b/crates/thing-core/tests/chooser.rs @@ -0,0 +1,663 @@ +//! Select chooser through `Core::frame` in Pixels (at 1.0 and 1.5) and Cells: +//! pointer open/choose, keyboard navigation and reveal, light dismiss and wheel containment, +//! disabled/busy/confirming/option refusals, surface/owner/focus close, and multi-mode rendering. + +mod support; + +use support::*; +use thing_contract::*; +use thing_core::bind::Binder; +use thing_core::command::{Activation, ActivationKind}; +use thing_core::diagnostic::Code; +use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; +use thing_core::layout::{LayoutFrame, Metrics, Rect, Run, layout}; +use thing_core::port::Ledger; +use thing_core::render::{Placed, RenderCommand, RenderInput, ScrollOffsets, Session, balanced, render}; +use thing_core::resolve::{Limits, resolve}; +use thing_core::theme::Theme; +use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, FrameOutput, Ports}; +use thing_testkit::build::*; +use thing_testkit::fixture::Fixture; +use thing_testkit::ids::SeqIds; +use thing_testkit::measure::FixedMeasure; +use thing_testkit::mem_state::MemState; +use thing_testkit::state; + +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 => (800.0, 600.0), + Metrics::Cells => (100.0, 37.0), + } +} + +fn measure(metrics: Metrics) -> FixedMeasure { + match metrics { + Metrics::Pixels => FixedMeasure::pixels(), + Metrics::Cells => FixedMeasure::cells(), + } +} + +fn mods() -> Modifiers { + Modifiers::default() +} + +fn key(k: Key) -> InputEvent { + InputEvent::Key { key: k, modifiers: mods(), repeat: false } +} + +fn key_repeat(k: Key) -> InputEvent { + InputEvent::Key { key: k, modifiers: mods(), repeat: true } +} + +fn alt_down() -> InputEvent { + InputEvent::Key { key: Key::Down, modifiers: Modifiers { alt: true, ..mods() }, repeat: false } +} + +fn tab(shift: bool) -> InputEvent { + InputEvent::Key { key: Key::Tab, modifiers: Modifiers { shift, ..mods() }, repeat: false } +} + +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 wheel(at: (f32, f32), delta: (f32, f32)) -> InputEvent { + InputEvent::Wheel { at, delta, unit: WheelUnit::Lines, modifiers: mods() } +} + +fn inside(rect: Rect) -> (f32, f32) { + (rect.x + 0.5, rect.y + 0.5) +} + +fn placement(mut state: MemState, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Vec { + state.put(&document.provider_id, document); + let limits = Limits::default(); + let resolved = resolve(document, &state, &limits).tree.expect("resolves"); + let mut binder = Binder::new(limits); + binder.bind(resolved, &mut state, &mut Ledger::new()); + let tree = binder.tree(&document.record_key()).expect("bound"); + let vp = viewport(metrics); + let laid = layout(tree, &LayoutFrame { viewport: vp, scale, metrics }, &mut measure(metrics)).expect("lays out"); + let theme = Theme::std(); + let input = RenderInput { scale, metrics, viewport: vp, scroll: &ScrollOffsets::default(), theme: &theme, session: Session::EMPTY }; + render(tree, &laid, &input, &mut measure(metrics)).placed +} + +fn placed_rect(placed: &[Placed], id: &str) -> Rect { + placed.iter().find(|p| p.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect +} + +struct Host { + core: Core, + state: MemState, + ids: SeqIds, + mode: (Metrics, f32), + vp: (f32, f32), + now: i64, +} + +impl Host { + fn new(mut state: MemState, document: &SurfaceDocument, mode: (Metrics, f32)) -> Self { + state.put(&document.provider_id, document); + let mut core = Core::new(Config::new(mode.0, "renderer.test"), Box::new(measure(mode.0))); + core.show(document.provider_id.clone(), RecordKey::new(document.record_key())); + let mut host = Self { core, state, ids: SeqIds::new(), mode, vp: viewport(mode.0), now: 0 }; + host.frame(vec![]); + host + } + + fn frame(&mut self, events: Vec) -> FrameOutput { + self.now += 1; + let input = FrameInput { now: Timestamp(self.now), viewport: self.vp, scale: self.mode.1, events }; + self.core.frame(input, Ports { state: &mut self.state, ids: &mut self.ids }) + } + + fn click(&mut self, at: (f32, f32)) -> FrameOutput { + self.frame(vec![down(at), up(at)]) + } +} + +fn drawn_texts(output: &FrameOutput) -> Vec<(f32, f32, String)> { + output + .commands + .iter() + .filter_map(|cmd| match cmd { + RenderCommand::Text { origin, run: Run::Glyphs { glyphs, .. }, .. } => { + let s: String = glyphs.iter().filter_map(|g| char::from_u32(g.id)).collect(); + Some((origin.0, origin.1, s)) + } + RenderCommand::Text { origin, run: Run::Cells { text, .. }, .. } => { + Some((origin.0, origin.1, text.as_str().to_string())) + } + _ => None, + }) + .collect() +} + +fn selection_rects(output: &FrameOutput) -> Vec { + let color = Theme::std().color("thing.selection").unwrap(); + output + .commands + .iter() + .filter_map(|cmd| match cmd { + RenderCommand::FillRect { rect, color: c, .. } if *c == color => Some(*rect), + _ => None, + }) + .collect() +} + +fn surface_fills(output: &FrameOutput) -> Vec { + let color = Theme::std().color("thing.surface").unwrap(); + output + .commands + .iter() + .filter_map(|cmd| match cmd { + RenderCommand::FillRect { rect, color: c, .. } if *c == color => Some(*rect), + _ => None, + }) + .collect() +} + +fn select_node(id: &str, options: Vec<(&str, &str)>, cmd: &str) -> Node { + Node::Select(SelectNode { + common: common(id), + options: OptionList::Literal(LiteralOptions { + options: options + .into_iter() + .map(|(value, label)| SelectOption { value: value.into(), label: label.into() }) + .collect(), + }), + value: record_bind(path(&["Choice"]), None), + on_change: command(cmd), + }) +} + +fn f04_options() -> Vec { + let doc = Fixture::F04Form.load().surfaces.remove(0); + let Node::Box(root) = doc.root else { panic!("box root") }; + root.children + .into_iter() + .find_map(|n| match n { + Node::Select(s) => match s.options { + OptionList::Literal(lit) => Some(lit.options), + _ => None, + }, + _ => None, + }) + .expect("f04 select options") +} + +// ----- 1. Open and choose by pointer ------------------------------------------------------ + +#[test] +fn open_and_choose_by_pointer_on_f04() { + let options = f04_options(); + assert!(options.len() >= 2); + for mode in MODES { + let fixture = Fixture::F04Form; + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let doc = fixture.load().surfaces.remove(0); + let select_rect = placed_rect(&placement(state.clone(), &doc, mode), "theme"); + + let mut host = Host::new(state, &doc, mode); + // Closed initially: no selection fill or surface popup. + let closed = host.frame(vec![]); + assert!(selection_rects(&closed).is_empty(), "{mode:?}"); + assert!(surface_fills(&closed).is_empty(), "{mode:?}"); + + // Press-release on Select opens its chooser over the Select. + let opened = host.click(inside(select_rect)); + assert!(opened.diagnostics.is_empty(), "{mode:?}: {:?}", opened.diagnostics); + assert!(opened.outbound.is_empty(), "{mode:?}"); + assert!(balanced(&opened.commands), "{mode:?}"); + assert_eq!(surface_fills(&opened).len(), 1, "{mode:?}: popup list surface"); + let list_rect = surface_fills(&opened)[0]; + assert!((list_rect.x - select_rect.x).abs() < 1e-3 && (list_rect.y - select_rect.y).abs() < 1e-3, "{mode:?}: list opens over Select"); + assert!((list_rect.w - select_rect.w).abs() < 1e-3, "{mode:?}: list matches Select width"); + + // All option labels are rendered; the current value ("dark" -> "Dark") has trailing " *" and highlight fill. + let sel = selection_rects(&opened); + assert_eq!(sel.len(), 1, "{mode:?}"); + let texts = drawn_texts(&opened); + assert!(texts.iter().any(|(_, _, t)| t == "Dark *"), "{mode:?}: {texts:?}"); + for opt in &options { + if opt.value != "dark" { + assert!(texts.iter().any(|(_, _, t)| t == &opt.label), "{mode:?}: missing {} in {texts:?}", opt.label); + } + } + + // Choose a different option by press-release on its row. + let target_opt = options.iter().find(|o| o.value != "dark").unwrap(); + let row_pos = texts + .iter() + .rev() + .find(|(_, _, t)| t == &target_opt.label) + .map(|(x, y, _)| (*x + 0.5, *y + 0.5)) + .expect("target row text"); + let chosen = host.click(row_pos); + assert!(chosen.diagnostics.is_empty(), "{mode:?}: {:?}", chosen.diagnostics); + assert_eq!(chosen.outbound.len(), 1, "{mode:?}"); + assert_eq!(chosen.outbound[0].captured[0].value, InputValue::Choice(ChoiceValue { value: target_opt.value.clone() }), "{mode:?}"); + assert!(surface_fills(&chosen).is_empty(), "{mode:?}: chooser closes after choice"); + assert!(selection_rects(&chosen).is_empty(), "{mode:?}"); + + // Closed Select now shows the new label through the draft. + let after_texts = drawn_texts(&chosen); + assert!(after_texts.iter().any(|(_, _, t)| t == &target_opt.label), "{mode:?}: {after_texts:?}"); + } +} + +#[test] +fn opening_another_select_replaces_any_prior_session_and_drag_off_row_does_not_choose() { + let doc = surface( + column( + "root", + None, + Overflow::Visible, + vec![ + select_node("s1", vec![("a", "Alpha"), ("b", "Beta")], "pick"), + select_node("s2", vec![("x", "Xray"), ("y", "Yankee")], "pick"), + ], + ), + vec![decl("pick", &["s1"])], + ); + let mode = MODES[0]; + let placed = placement(MemState::new(), &doc, mode); + let r1 = placed_rect(&placed, "s1"); + let r2 = placed_rect(&placed, "s2"); + let mut host = Host::new(MemState::new(), &doc, mode); + + // Open s1. + let out1 = host.click(inside(r1)); + let t1 = drawn_texts(&out1); + assert!(t1.iter().any(|(_, _, t)| t == "Alpha"), "{t1:?}"); + + // Down on row 1 ("Beta"), drag/release outside onto row 0 ("Alpha"): must not choose or close. + let beta = t1.iter().rev().find(|(_, _, t)| t == "Beta").map(|(x, y, _)| (*x + 0.5, *y + 0.5)).unwrap(); + let alpha = t1.iter().rev().find(|(_, _, t)| t == "Alpha").map(|(x, y, _)| (*x + 0.5, *y + 0.5)).unwrap(); + let drag_out = host.frame(vec![down(beta), up(alpha)]); + assert!(drag_out.outbound.is_empty()); + assert_eq!(surface_fills(&drag_out).len(), 1, "still open"); + + // Down moved highlight to row 1 ("Beta"). + let sel_y = selection_rects(&drag_out)[0].y; + assert!((sel_y - beta.1).abs() < 4.0, "highlight moved to Beta on down"); + + // Escape closes s1, Tab moves to s2, Enter opens s2. + host.frame(vec![key(Key::Escape), tab(false), key(Key::Enter)]); + let out2 = host.frame(vec![]); + let t2 = drawn_texts(&out2); + assert!(t2.iter().any(|(_, _, t)| t == "Xray")); + assert!(!t2.iter().any(|(_, _, t)| t == "Alpha")); +} + +// ----- 2. Keys: open, highlight move, reveal, choose, Escape/Tab, key scope --------------- + +#[test] +fn keys_open_move_highlight_choose_and_close_without_activating() { + let doc = surface( + column( + "root", + None, + Overflow::Visible, + vec![ + select_node("pick", vec![("a", "Alpha"), ("b", "Beta"), ("c", "Gamma")], "choose"), + button("next", "other", 160.0, 32.0), + ], + ), + vec![decl("choose", &["pick"]), decl("other", &[])], + ); + for mode in MODES { + for open_key in [key(Key::Enter), key(Key::Char(' ')), key(Key::Down), alt_down()] { + let mut host = Host::new(MemState::new(), &doc, mode); + // Focus "pick". + host.frame(vec![tab(false)]); + // Repeat must not open. + let rep = host.frame(vec![key_repeat(Key::Enter)]); + assert!(surface_fills(&rep).is_empty(), "{mode:?}"); + + // Open with each trigger key. + let opened = host.frame(vec![open_key.clone()]); + assert_eq!(surface_fills(&opened).len(), 1, "{mode:?} {open_key:?}"); + assert!(opened.outbound.is_empty(), "{mode:?}"); + + // Escape closes without choosing. + let esc = host.frame(vec![key(Key::Escape)]); + assert!(surface_fills(&esc).is_empty(), "{mode:?}"); + assert!(esc.outbound.is_empty(), "{mode:?}"); + + // Re-open, move Down, End, Home, Down, and Space to choose "Beta". + host.frame(vec![open_key.clone()]); + let moved_end = host.frame(vec![key(Key::End)]); + let end_sel = selection_rects(&moved_end)[0]; + let moved_home = host.frame(vec![key(Key::Home)]); + let home_sel = selection_rects(&moved_home)[0]; + assert!(end_sel.y > home_sel.y, "{mode:?}: End moves below Home"); + + host.frame(vec![key(Key::Down)]); + // Repeat Enter must not choose. + let rep_choose = host.frame(vec![key_repeat(Key::Enter)]); + assert_eq!(surface_fills(&rep_choose).len(), 1, "{mode:?}: repeat Enter does not choose"); + assert!(rep_choose.outbound.is_empty(), "{mode:?}"); + + let chosen = host.frame(vec![key(Key::Char(' '))]); + assert_eq!(chosen.outbound.len(), 1, "{mode:?}"); + assert_eq!(chosen.outbound[0].captured[0].value, InputValue::Choice(ChoiceValue { value: "b".into() }), "{mode:?}"); + assert!(surface_fills(&chosen).is_empty(), "{mode:?}"); + + // Re-open, highlight Gamma, then Tab closes without choosing and traverses to "next". + host.frame(vec![open_key]); + host.frame(vec![key(Key::End)]); + let tabbed = host.frame(vec![tab(false)]); + assert!(surface_fills(&tabbed).is_empty(), "{mode:?}"); + assert!(tabbed.outbound.is_empty(), "{mode:?}"); + // Pressing Enter now activates "next" (proving focus moved to "next"). + let next_act = host.frame(vec![key(Key::Enter)]); + assert_eq!(next_act.outbound[0].command, CommandId::new("other"), "{mode:?}"); + } + } +} + +#[test] +fn scrollable_chooser_reveals_highlight_on_keys_and_alt_down_does_not_leak() { + // 15 options in a small viewport so the chooser overflows and scrolls. + let opts: Vec<_> = (0..15).map(|i| (format!("v{i}"), format!("Opt {i:02}"))).collect(); + let opt_refs: Vec<_> = opts.iter().map(|(v, l)| (v.as_str(), l.as_str())).collect(); + 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 doc = surface( + column( + "root", + None, + Overflow::Visible, + vec![ + slider, + select_node("pick", opt_refs, "choose"), + ], + ), + vec![decl("set", &["level"]), decl("choose", &["pick"])], + ); + for mode in MODES { + let mut host = Host::new(MemState::new(), &doc, mode); + host.vp = match mode.0 { + Metrics::Pixels => (400.0, 120.0), + Metrics::Cells => (40.0, 8.0), + }; + host.frame(vec![]); + + // Focus slider "level": Alt+Down must NOT step the slider. + let stepped = host.frame(vec![tab(false), alt_down()]); + assert!(stepped.outbound.is_empty(), "{mode:?}: Alt+Down must not step slider"); + + // Tab to "pick" and open chooser: list overflows viewport room so it has a scrollbar thumb. + let thumb_color = Theme::std().color("thing.scrollbar.thumb").unwrap(); + let opened = host.frame(vec![tab(false), key(Key::Enter)]); + assert!(opened.commands.iter().any(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == thumb_color)), "{mode:?}: chooser scrolls"); + + // End jumps to Opt 14 and reveals it into the visible list rect. + let at_end = host.frame(vec![key(Key::End)]); + let list_rect = surface_fills(&at_end)[0]; + let texts_end = drawn_texts(&at_end); + let opt14 = texts_end.iter().find(|(_, _, t)| t == "Opt 14").expect("Opt 14 drawn"); + assert!(opt14.1 >= list_rect.y && opt14.1 < list_rect.y + list_rect.h, "{mode:?}: Opt 14 revealed in {list_rect:?}: {opt14:?}"); + + // PageUp moves back by one visible page and keeps highlight inside list_rect. + let page_up = host.frame(vec![key(Key::PageUp)]); + let sel_after_pgup = selection_rects(&page_up)[0]; + assert!(sel_after_pgup.y >= list_rect.y && sel_after_pgup.y + sel_after_pgup.h <= list_rect.y + list_rect.h, "{mode:?}"); + + // PageDown returns toward the end; Up/Down move smoothly and Enter chooses current highlight. + host.frame(vec![key(Key::PageDown), key(Key::Up)]); + let chosen = host.frame(vec![key(Key::Enter)]); + assert_eq!(chosen.outbound.len(), 1, "{mode:?}"); + assert_ne!(chosen.outbound[0].captured[0].value, InputValue::Choice(ChoiceValue { value: "v0".into() }), "{mode:?}"); + } +} + +// ----- 3. Light dismiss and wheel containment --------------------------------------------- + +#[test] +fn light_dismiss_does_not_click_through_and_wheel_never_scrolls_page() { + let opts: Vec<_> = (0..12).map(|i| (format!("v{i}"), format!("Row {i:02}"))).collect(); + let opt_refs: Vec<_> = opts.iter().map(|(v, l)| (v.as_str(), l.as_str())).collect(); + let doc = surface( + column( + "pane", + Some((300.0, 140.0)), + Overflow::Scroll, + vec![ + select_node("pick", opt_refs, "choose"), + button("below", "below", 160.0, 32.0), + fixed("spacer", 160.0, 400.0), + ], + ), + vec![decl("choose", &["pick"]), decl("below", &[])], + ); + for mode in MODES { + let placed = placement(MemState::new(), &doc, mode); + let select_rect = placed_rect(&placed, "pick"); + let below_rect = placed_rect(&placed, "below"); + + let mut host = Host::new(MemState::new(), &doc, mode); + host.vp = match mode.0 { + Metrics::Pixels => (400.0, 140.0), + Metrics::Cells => (50.0, 9.0), + }; + let baseline = host.frame(vec![]); + let below_y_before = drawn_texts(&baseline).into_iter().find(|(_, _, t)| t == "below").map(|(_, y, _)| y); + + // Open chooser. + let opened = host.click(inside(select_rect)); + let list_rect = surface_fills(&opened)[0]; + let opt0_before = drawn_texts(&opened).into_iter().find(|(_, _, t)| t == "Row 00").map(|(_, y, _)| y); + + // Wheel over the open chooser scrolls the list, never the page beneath. + let wheeled = host.frame(vec![wheel(inside(list_rect), (0.0, 3.0))]); + let opt0_after = drawn_texts(&wheeled).into_iter().find(|(_, _, t)| t == "Row 00").map(|(_, y, _)| y); + assert_ne!(opt0_before, opt0_after, "{mode:?}: chooser list scrolled"); + let below_y_after = drawn_texts(&wheeled).into_iter().find(|(_, _, t)| t == "below").map(|(_, y, _)| y); + assert_eq!(below_y_before, below_y_after, "{mode:?}: page beneath must not scroll"); + + // Wheel outside the chooser while open also must not scroll the page beneath. + let wheel_outside = host.frame(vec![wheel((below_rect.x + below_rect.w - 1.0, below_rect.y + 0.5), (0.0, 3.0))]); + let below_y_after_out = drawn_texts(&wheel_outside).into_iter().find(|(_, _, t)| t == "below").map(|(_, y, _)| y); + assert_eq!(below_y_before, below_y_after_out, "{mode:?}: wheel outside chooser must not scroll page"); + + // Click outside on "below" button (to the right of list? Make sure point is outside list_rect). + // Put the click near the bottom-right corner of the viewport, outside list_rect. + let outside_pt = (list_rect.x + list_rect.w + 5.0, list_rect.y + list_rect.h - 1.0); + let dismissed = host.click(outside_pt); + assert!(surface_fills(&dismissed).is_empty(), "{mode:?}: light dismiss closed chooser"); + assert!(dismissed.outbound.is_empty(), "{mode:?}: light dismiss activates nothing beneath"); + } +} + +// ----- 4. Refusals: busy, confirming, invalid option -------------------------------------- + +#[test] +fn busy_confirming_and_invalid_option_refusals() { + let doc = surface( + column( + "root", + None, + Overflow::Visible, + vec![ + select_node("pick", vec![("a", "Alpha"), ("b", "Beta")], "choose"), + button("ask", "ask", 160.0, 32.0), + ], + ), + vec![ + decl("choose", &["pick"]), + CommandDecl { + id: CommandId::new("ask"), + payload_schema: SchemaId::new("gamecult.thing.test.ask.v1"), + captures: vec![], + confirm: Some("Really?".into()), + }, + ], + ); + let mode = MODES[0]; + let placed = placement(MemState::new(), &doc, mode); + let select_rect = placed_rect(&placed, "pick"); + let ask_rect = placed_rect(&placed, "ask"); + + let mut host = Host::new(MemState::new(), &doc, mode); + + // 1. Choosing while busy: open, fire an invocation via Core::activate, then click a row. + let opened = host.click(inside(select_rect)); + assert_eq!(surface_fills(&opened).len(), 1); + host.core.activate( + Activation { node: nid("pick"), kind: ActivationKind::Change(InputValue::Choice(ChoiceValue { value: "a".into() })) }, + Timestamp(10), + Ports { state: &mut host.state, ids: &mut host.ids }, + ); + let busy_frame = host.frame(vec![]); + assert_eq!(busy_frame.outbound.len(), 1); + let invocation = busy_frame.outbound[0].clone(); + + // Clicking a row while busy yields ActivationBlocked and no new draft. + let texts = drawn_texts(&busy_frame); + let beta = texts.iter().rev().find(|(_, _, t)| t == "Beta").map(|(x, y, _)| (*x + 0.5, *y + 0.5)).unwrap(); + let blocked_choose = host.click(beta); + assert_eq!(blocked_choose.diagnostics.iter().map(|d| d.code).collect::>(), vec![Code::ActivationBlocked]); + assert!(blocked_choose.outbound.is_empty()); + // Closed Select still shows Alpha (draft remained "a", not "b"). + assert!(!drawn_texts(&blocked_choose).iter().any(|(_, _, t)| t == "Beta")); + + // Busy Select does not open on click or Enter. + let busy_click = host.click(inside(select_rect)); + assert!(surface_fills(&busy_click).is_empty()); + let busy_key = host.frame(vec![key(Key::Enter)]); + assert!(surface_fills(&busy_key).is_empty()); + + // Complete invocation so Select is idle again. + let res = CommandResult::completed(&invocation, seq(1), None, true, None); + host.state.put(&ProviderId::new(PROVIDER), &res); + host.frame(vec![]); + + // 2. Confirming blocks opening (pointer and key). + host.click(inside(ask_rect)); + assert!(host.core.confirming().is_some()); + let conf_click = host.click(inside(select_rect)); + assert!(surface_fills(&conf_click).is_empty()); + let conf_key = host.frame(vec![key(Key::Down)]); + assert!(surface_fills(&conf_key).is_empty()); + + // Confirming while already open: reject/clear confirm, open chooser, trigger confirm via Core::activate, then choose by key. + host.core.confirm(false, Timestamp(20), Ports { state: &mut host.state, ids: &mut host.ids }); + host.frame(vec![]); + host.click(inside(select_rect)); + host.core.activate( + Activation { node: nid("ask"), kind: ActivationKind::Press }, + Timestamp(21), + Ports { state: &mut host.state, ids: &mut host.ids }, + ); + let blocked_by_confirm = host.frame(vec![key(Key::Down), key(Key::Enter)]); + assert_eq!(blocked_by_confirm.diagnostics.iter().map(|d| d.code).collect::>(), vec![Code::ActivationBlocked]); + assert!(blocked_by_confirm.outbound.is_empty()); + host.core.confirm(false, Timestamp(22), Ports { state: &mut host.state, ids: &mut host.ids }); + + // 3. Value outside declared options is Refused. + host.core.activate( + Activation { node: nid("pick"), kind: ActivationKind::Change(InputValue::Choice(ChoiceValue { value: "bogus".into() })) }, + Timestamp(23), + Ports { state: &mut host.state, ids: &mut host.ids }, + ); + let refused = host.frame(vec![]); + assert_eq!(refused.diagnostics.iter().map(|d| d.code).collect::>(), vec![Code::ActivationRefused]); + assert!(refused.outbound.is_empty()); +} + +// ----- 5. Closing by other causes & empty options ----------------------------------------- + +#[test] +fn empty_options_never_opens_and_surface_switch_or_removal_closes_cleanly() { + let doc_empty = surface( + column("root", None, Overflow::Visible, vec![select_node("empty", vec![], "choose")]), + vec![decl("choose", &[])], + ); + let doc_a = surface( + column("root", None, Overflow::Visible, vec![select_node("pick", vec![("a", "Alpha")], "choose")]), + vec![decl("choose", &[])], + ); + let mut doc_b = surface( + column("root", None, Overflow::Visible, vec![button("other", "choose", 120.0, 32.0)]), + vec![decl("choose", &[])], + ); + doc_b.label = seg("other"); + + let mode = MODES[0]; + // Empty options never opens on pointer or key. + let empty_rect = placed_rect(&placement(MemState::new(), &doc_empty, mode), "empty"); + let mut empty_host = Host::new(MemState::new(), &doc_empty, mode); + assert!(surface_fills(&empty_host.click(inside(empty_rect))).is_empty()); + assert!(surface_fills(&empty_host.frame(vec![key(Key::Enter)])).is_empty()); + + // Open on doc_a, then switch to doc_b and back to doc_a: chooser stays closed. + let pick_rect = placed_rect(&placement(MemState::new(), &doc_a, mode), "pick"); + let mut host = Host::new(MemState::new(), &doc_a, mode); + host.state.put(&doc_b.provider_id, &doc_b); + assert_eq!(surface_fills(&host.click(inside(pick_rect))).len(), 1); + + host.core.show(doc_b.provider_id.clone(), RecordKey::new(doc_b.record_key())); + let switched = host.frame(vec![]); + assert!(switched.diagnostics.is_empty()); + assert!(surface_fills(&switched).is_empty()); + + host.core.show(doc_a.provider_id.clone(), RecordKey::new(doc_a.record_key())); + let back = host.frame(vec![]); + assert!(back.diagnostics.is_empty()); + assert!(surface_fills(&back).is_empty()); + + // Re-open on doc_a, then republish doc_a without "pick": closes cleanly without diagnostics. + assert_eq!(surface_fills(&host.click(inside(pick_rect))).len(), 1); + let mut doc_a_v2 = surface( + column("root", None, Overflow::Visible, vec![button("only", "choose", 120.0, 32.0)]), + vec![decl("choose", &[])], + ); + doc_a_v2.version = ver(2); + host.state.put(&doc_a_v2.provider_id, &doc_a_v2); + let removed = host.frame(vec![]); + assert!(removed.diagnostics.is_empty(), "{:?}", removed.diagnostics); + assert!(surface_fills(&removed).is_empty()); +} + +// ----- 6. Multi-mode visual consistency --------------------------------------------------- + +#[test] +fn chooser_open_renders_same_list_across_pixels_scales_and_cells() { + let fixture = Fixture::F04Form; + let options = f04_options(); + for mode in MODES { + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let doc = fixture.load().surfaces.remove(0); + let mut host = Host::new(state, &doc, mode); + let opened = host.frame(vec![tab(false), tab(false), tab(false), key(Key::Enter)]); + assert!(opened.diagnostics.is_empty(), "{mode:?}: {:?}", opened.diagnostics); + assert!(balanced(&opened.commands), "{mode:?}"); + assert_eq!(surface_fills(&opened).len(), 1, "{mode:?}"); + assert_eq!(selection_rects(&opened).len(), 1, "{mode:?}"); + let texts = drawn_texts(&opened); + assert!(texts.iter().any(|(_, _, t)| t == "Dark *"), "{mode:?}: {texts:?}"); + for opt in &options { + if opt.value != "dark" { + assert!(texts.iter().any(|(_, _, t)| t == &opt.label), "{mode:?}: {texts:?}"); + } + } + } +} diff --git a/crates/thing-core/tests/render.rs b/crates/thing-core/tests/render.rs index e73d7b8..04d5654 100644 --- a/crates/thing-core/tests/render.rs +++ b/crates/thing-core/tests/render.rs @@ -7,17 +7,15 @@ use thing_contract::*; use thing_core::bind::{Binder, BoundTree}; use thing_core::command::{Activation, ActivationKind, Commands, Mark, NodeStates}; use thing_core::diagnostic::Code; -use thing_core::input::Drafts; +use thing_core::input::{Drafts, InputEvent, Key, Modifiers}; use thing_core::layout::{LaidTree, LayoutFrame, Measure, Metrics, Run, layout}; use thing_core::port::{Address, Change, Entry, Ledger, Record}; use thing_core::text::CellMeasure; use thing_core::render::{FocusView, Placed, RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, balanced, clamp, render}; use thing_core::resolve::{Limits, resolve}; use thing_core::theme::Theme; -use thing_testkit::build::*; -use thing_testkit::fixture::Fixture; -use thing_testkit::golden; use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, Ports}; use thing_testkit::ids::SeqIds; use thing_testkit::mem_state::MemState; use thing_testkit::measure::FixedMeasure; @@ -1558,3 +1556,34 @@ fn focus_ring_draws_one_stroke_on_f04_and_f05_and_hides_when_not_visible() { assert_eq!(hidden_f05.commands, plain_f05.commands); assert_ne!(drawn_f05.commands, plain_f05.commands); } + +#[test] +fn f04_chooser_open_golden() { + let fixture = Fixture::F04Form; + let set = fixture.load(); + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let document = &set.surfaces[0]; + state.put(&document.provider_id, document); + + let mut core = Core::new(Config::new(Metrics::Pixels, "renderer.test"), Box::new(FixedMeasure::pixels())); + core.show(document.provider_id.clone(), RecordKey::new(document.record_key())); + let mut ids = SeqIds::new(); + core.frame(FrameInput { now: Timestamp(1), viewport: (800.0, 600.0), scale: 1.0, events: vec![] }, Ports { state: &mut state, ids: &mut ids }); + + let key = |k| InputEvent::Key { key: k, modifiers: Modifiers::default(), repeat: false }; + let out = core.frame( + FrameInput { + now: Timestamp(2), + viewport: (800.0, 600.0), + scale: 1.0, + events: vec![key(Key::Tab), key(Key::Tab), key(Key::Tab), key(Key::Enter)], + }, + Ports { state: &mut state, ids: &mut ids }, + ); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + assert!(balanced(&out.commands)); + let rendered = Rendered { commands: out.commands, placed: Vec::new(), diagnostics: out.diagnostics }; + let text = format!("surface {} viewport 800x600 scale 1 pixels\n{}", document.record_key(), text_form(&rendered)); + golden::check(&golden_dir(), "render-f04-form-chooser.txt", text.as_bytes()); +} diff --git a/crates/thing-tui/tests/screen.rs b/crates/thing-tui/tests/screen.rs index 8d4d0cf..4aae464 100644 --- a/crates/thing-tui/tests/screen.rs +++ b/crates/thing-tui/tests/screen.rs @@ -9,17 +9,21 @@ mod common; use std::path::PathBuf; use common::well_formed; -use thing_contract::SurfaceDocument; +use thing_contract::{RecordKey, SurfaceDocument}; use thing_core::bind::Binder; use thing_core::diagnostic::Code; +use thing_core::input::{InputEvent, Key, Modifiers}; use thing_core::layout::{LayoutFrame, Metrics, layout}; use thing_core::port::Ledger; use thing_core::render::{RenderInput, ScrollOffsets, Session, render}; use thing_core::resolve::{Limits, resolve}; use thing_core::text::CellMeasure; use thing_core::theme::Theme; +use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, Ports}; use thing_testkit::fixture::Fixture; use thing_testkit::golden; +use thing_testkit::ids::SeqIds; use thing_testkit::mem_state::MemState; use thing_testkit::state; use thing_tui::{Painted, Screen, paint}; @@ -92,3 +96,39 @@ fn image_and_embed_are_on_screen() { assert!(f03.contains('\u{2591}') && f03.contains("The board"), "f03 draws its Image as a shaded block with its alt"); assert!(golden_text(Fixture::F08EmbedViewport).contains("\nembed "), "f08 reports its Embed to the host"); } + +#[test] +fn f04_chooser_screen_golden() { + let fixture = Fixture::F04Form; + let set = fixture.load(); + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let document = &set.surfaces[0]; + state.put(&document.provider_id, document); + + let mut core = Core::new(Config::new(Metrics::Cells, "renderer.test"), Box::new(CellMeasure)); + core.show(document.provider_id.clone(), RecordKey::new(document.record_key())); + let mut ids = SeqIds::new(); + core.frame( + FrameInput { now: Timestamp(1), viewport: (COLS as f32, ROWS as f32), scale: 1.0, events: vec![] }, + Ports { state: &mut state, ids: &mut ids }, + ); + + let key = |k| InputEvent::Key { key: k, modifiers: Modifiers::default(), repeat: false }; + let out = core.frame( + FrameInput { + now: Timestamp(2), + viewport: (COLS as f32, ROWS as f32), + scale: 1.0, + events: vec![key(Key::Tab), key(Key::Tab), key(Key::Tab), key(Key::Enter)], + }, + Ports { state: &mut state, ids: &mut ids }, + ); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + + let mut screen = Screen::new(COLS, ROWS); + let _painted = paint(&out.commands, &mut screen); + well_formed(&screen); + let text = format!("surface {} {COLS}x{ROWS}\n{}", document.record_key(), screen.dump()); + golden::check(&golden_dir(), "screen-f04-form-chooser-cells.txt", text.as_bytes()); +}