thing-core, thing-tui: add keyboard focus, Tab traversal, modal trap, key activations, and focus ring
This commit is contained in:
parent
aa9f93eb42
commit
27d49ee92e
14 changed files with 1261 additions and 62 deletions
|
|
@ -264,6 +264,7 @@ impl Core {
|
|||
}
|
||||
if let Some(old) = self.shown.take() {
|
||||
self.input.cancel(old.key.as_str(), &mut self.drafts);
|
||||
self.input.clear_focus();
|
||||
self.resolver.forget(old.key.as_str(), port, &mut self.ledger);
|
||||
self.binder.forget(old.key.as_str(), port, &mut self.ledger);
|
||||
self.commands.forget(old.key.as_str(), port, &mut self.ledger);
|
||||
|
|
@ -294,8 +295,9 @@ impl Core {
|
|||
let frame = LayoutFrame { viewport, scale, metrics: self.metrics };
|
||||
match layout(tree, &frame, self.measure.as_mut()) {
|
||||
Ok(laid) => {
|
||||
self.input.reconcile(tree, &laid, &mut self.scroll);
|
||||
let states = self.commands.view(address.key.as_str());
|
||||
let session = Session::new(&self.drafts, &states);
|
||||
let session = Session::new(&self.drafts, &states).with_focus(self.input.focus_view());
|
||||
let input = RenderInput { scale, metrics: self.metrics, viewport, scroll: &self.scroll, theme: &self.theme, session };
|
||||
let rendered = render(tree, &laid, &input, self.measure.as_mut());
|
||||
diagnostics.extend(rendered.diagnostics.iter().cloned());
|
||||
|
|
|
|||
217
crates/thing-core/src/input/focus.rs
Normal file
217
crates/thing-core/src/input/focus.rs
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
//! Keyboard focus: which laid node holds focus, whether its ring shows, and the scoped Tab order.
|
||||
//! Every focus change passes through `Focus::set`. Focus is keyed by laid `NodeId`, never stored on
|
||||
//! a node, and cleared on surface switch.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use thing_contract::{Node, NodeId};
|
||||
|
||||
use super::hit::{self, Control};
|
||||
use crate::bind::{Bound, BoundTree, Field};
|
||||
use crate::layout::LaidTree;
|
||||
use crate::render::{FocusView, ScrollOffsets, clamp};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Focus {
|
||||
node: Option<NodeId>,
|
||||
visible: bool,
|
||||
window: bool,
|
||||
opener: Option<NodeId>,
|
||||
order: Vec<NodeId>,
|
||||
/// Active overlay trap root from the previous reconcile (`None` when the whole surface is in scope).
|
||||
trap: Option<NodeId>,
|
||||
/// True after a keyboard or reconcile move until the next `reconcile` brings it into view.
|
||||
reveal: bool,
|
||||
}
|
||||
|
||||
impl Default for Focus {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
node: None,
|
||||
visible: false,
|
||||
window: true,
|
||||
opener: None,
|
||||
order: Vec::new(),
|
||||
trap: None,
|
||||
reveal: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Focus {
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.node = None;
|
||||
self.visible = false;
|
||||
self.opener = None;
|
||||
self.order.clear();
|
||||
self.trap = None;
|
||||
self.reveal = false;
|
||||
}
|
||||
|
||||
pub(crate) fn set_window(&mut self, window: bool) {
|
||||
self.window = window;
|
||||
}
|
||||
|
||||
pub(super) fn node(&self) -> Option<&NodeId> {
|
||||
self.node.as_ref()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn order(&self) -> &[NodeId] {
|
||||
&self.order
|
||||
}
|
||||
|
||||
pub(crate) fn view(&self) -> Option<FocusView<'_>> {
|
||||
self.node.as_ref().map(|node| FocusView { node, visible: self.visible && self.window })
|
||||
}
|
||||
|
||||
/// The one setter every focus change passes through (pointer down, Tab, reconcile).
|
||||
pub(crate) fn set(&mut self, node: Option<NodeId>, visible: bool) {
|
||||
self.reveal = visible && node.is_some();
|
||||
self.node = node;
|
||||
self.visible = visible;
|
||||
}
|
||||
|
||||
/// Move focus one stop forward or backward in the current traversal order, wrapping at the ends.
|
||||
pub(super) fn step(&mut self, backward: bool, laid: &LaidTree) {
|
||||
if self.order.is_empty() {
|
||||
self.set(None, false);
|
||||
return;
|
||||
}
|
||||
let len = self.order.len();
|
||||
let next = match self.node.as_ref().and_then(|id| self.order.iter().position(|stop| stop == id)) {
|
||||
Some(pos) => {
|
||||
let idx = if backward { (pos + len - 1) % len } else { (pos + 1) % len };
|
||||
self.order[idx].clone()
|
||||
}
|
||||
None => {
|
||||
// Focused id is absent or a Button disabled after last draw: step from its laid position.
|
||||
let laid_pos = self.node.as_ref().and_then(|id| laid.nodes.iter().position(|n| &n.id == id));
|
||||
match laid_pos {
|
||||
Some(k) if !backward => self
|
||||
.order
|
||||
.iter()
|
||||
.find(|id| laid.nodes.iter().position(|n| &n.id == *id).is_some_and(|p| p > k))
|
||||
.unwrap_or(&self.order[0])
|
||||
.clone(),
|
||||
Some(k) => self
|
||||
.order
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|id| laid.nodes.iter().position(|n| &n.id == *id).is_some_and(|p| p < k))
|
||||
.unwrap_or(&self.order[len - 1])
|
||||
.clone(),
|
||||
None if backward => self.order[len - 1].clone(),
|
||||
None => self.order[0].clone(),
|
||||
}
|
||||
}
|
||||
};
|
||||
self.set(Some(next), true);
|
||||
}
|
||||
|
||||
/// Reconcile focus after layout and before render: rebuild the scoped traversal order, handle
|
||||
/// trap entry/exit, fall back if the focused id vanished, and reveal the focused rect.
|
||||
pub(crate) fn reconcile(&mut self, tree: &BoundTree, laid: &LaidTree, scroll: &mut ScrollOffsets) {
|
||||
let index = tree.index();
|
||||
let floor = hit::modal_floor(laid, &index);
|
||||
let trap = floor.checked_sub(1).map(|m| laid.nodes[m].id.clone());
|
||||
let order = compute_order(tree, laid, &index, floor);
|
||||
let prev_order = std::mem::replace(&mut self.order, order);
|
||||
|
||||
let in_scope = |id: &NodeId| laid.nodes[floor..].iter().any(|n| &n.id == id);
|
||||
|
||||
if trap.is_some() && trap != self.trap {
|
||||
if self.node.as_ref().is_none_or(|id| !in_scope(id)) {
|
||||
self.opener = self.node.take();
|
||||
let first = self.order.first().cloned();
|
||||
let show = first.is_some();
|
||||
self.set(first, show);
|
||||
}
|
||||
} else if trap.is_none() && self.trap.is_some()
|
||||
&& let Some(op) = self.opener.take()
|
||||
&& in_scope(&op)
|
||||
{
|
||||
self.set(Some(op), true);
|
||||
}
|
||||
self.trap = trap;
|
||||
|
||||
if let Some(current) = self.node.as_ref()
|
||||
&& !in_scope(current)
|
||||
{
|
||||
let fallback = prev_order.iter().position(|id| id == current).and_then(|pos| {
|
||||
prev_order[..pos]
|
||||
.iter()
|
||||
.rev()
|
||||
.chain(prev_order[pos + 1..].iter())
|
||||
.find(|id| self.order.contains(id))
|
||||
.cloned()
|
||||
});
|
||||
let show = fallback.is_some();
|
||||
self.set(fallback, show);
|
||||
}
|
||||
|
||||
if std::mem::take(&mut self.reveal)
|
||||
&& let Some(id) = &self.node
|
||||
{
|
||||
reveal_node(laid, floor, id, scroll);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compute_order(tree: &BoundTree, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, floor: usize) -> Vec<NodeId> {
|
||||
let mut has_focusable = vec![false; laid.nodes.len()];
|
||||
let mut stops = Vec::new();
|
||||
for i in (floor..laid.nodes.len()).rev() {
|
||||
let laid_node = &laid.nodes[i];
|
||||
let is_control = index
|
||||
.get(&laid_node.id)
|
||||
.copied()
|
||||
.and_then(hit::control_of)
|
||||
.is_some_and(|control| control != Control::Button || tree.value(&laid_node.id, Field::Enabled) != Some(&Bound::Bool(false)));
|
||||
let can_scroll = laid_node.max_scroll.is_some_and(|m| m.0 > 0.0 || m.1 > 0.0);
|
||||
let is_scroller = can_scroll && !has_focusable[i];
|
||||
let focusable = is_control || is_scroller;
|
||||
if focusable {
|
||||
stops.push(laid_node.id.clone());
|
||||
}
|
||||
if (focusable || has_focusable[i])
|
||||
&& let Some(parent) = laid_node.parent.map(|p| p as usize).filter(|&p| p >= floor)
|
||||
{
|
||||
has_focusable[parent] = true;
|
||||
}
|
||||
}
|
||||
stops.reverse();
|
||||
stops
|
||||
}
|
||||
|
||||
fn reveal_axis(start: f32, len: f32, clip_start: f32, clip_len: f32, offset: f32) -> f32 {
|
||||
let lo = (start + len) - (clip_start + clip_len);
|
||||
let hi = start - clip_start;
|
||||
offset.clamp(lo.min(hi), lo.max(hi))
|
||||
}
|
||||
|
||||
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);
|
||||
while let Some(i) = parent {
|
||||
if i < floor {
|
||||
break;
|
||||
}
|
||||
let node = &laid.nodes[i];
|
||||
if let (Some(max), Some(clip)) = (node.max_scroll, node.clip) {
|
||||
let held = scroll.of(node);
|
||||
let want = (
|
||||
reveal_axis(rect.x, rect.w, clip.x, clip.w, held.0),
|
||||
reveal_axis(rect.y, rect.h, clip.y, clip.h, held.1),
|
||||
);
|
||||
let next = clamp(want, max);
|
||||
if next != held {
|
||||
scroll.set(node.id.clone(), next);
|
||||
}
|
||||
rect.x -= next.0;
|
||||
rect.y -= next.1;
|
||||
}
|
||||
parent = node.parent.map(|p| p as usize);
|
||||
}
|
||||
}
|
||||
|
|
@ -53,14 +53,18 @@ fn covers(rect: Rect, (x, y): (f32, f32), k: f32) -> bool {
|
|||
x >= on_device(rect.x, k) && x < on_device(rect.x + rect.w, k) && y >= on_device(rect.y, k) && y < on_device(rect.y + rect.h, k)
|
||||
}
|
||||
|
||||
pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Reach> {
|
||||
// The last modal overlay root in paint order: nothing painted before it is reachable, and what
|
||||
// is painted after it (its own subtree, then any later overlay) is.
|
||||
let modal = laid
|
||||
.nodes
|
||||
/// First laid index reachable under the last modal overlay (`0` when none); `floor.checked_sub(1)`
|
||||
/// is that overlay root's own index. Pointer hit-testing and keyboard focus share this one floor.
|
||||
pub(super) fn modal_floor(laid: &LaidTree, index: &HashMap<&NodeId, &Node>) -> usize {
|
||||
laid.nodes
|
||||
.iter()
|
||||
.rposition(|node| node.parent.is_none() && matches!(index.get(&node.id), Some(Node::Overlay(overlay)) if overlay.modal));
|
||||
let floor = modal.map_or(0, |m| m + 1);
|
||||
.rposition(|node| node.parent.is_none() && matches!(index.get(&node.id), Some(Node::Overlay(overlay)) if overlay.modal))
|
||||
.map_or(0, |m| m + 1)
|
||||
}
|
||||
|
||||
pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Reach> {
|
||||
let floor = modal_floor(laid, index);
|
||||
let modal = floor.checked_sub(1);
|
||||
// A non-modal overlay's root is only where its content is anchored: it is the viewport or the
|
||||
// anchor's rect, not something drawn, so a press that misses the content goes on through it.
|
||||
let transparent = |i: usize| laid.nodes[i].parent.is_none() && matches!(index.get(&laid.nodes[i].id), Some(Node::Overlay(_)));
|
||||
|
|
@ -72,7 +76,7 @@ pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeI
|
|||
}
|
||||
}
|
||||
|
||||
fn control_of(node: &Node) -> Option<Control> {
|
||||
pub(super) fn control_of(node: &Node) -> Option<Control> {
|
||||
match node {
|
||||
Node::Button(_) => Some(Control::Button),
|
||||
Node::Toggle(_) => Some(Control::Toggle),
|
||||
|
|
|
|||
129
crates/thing-core/src/input/keys.rs
Normal file
129
crates/thing-core/src/input/keys.rs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
//! Keyboard routing against the seen frame: Tab traversal, Escape dismissal, key activation on
|
||||
//! the focused control, Slider stepping and key scrolling through `ScrollOffsets`.
|
||||
|
||||
use thing_contract::{InputValue, Node, NumberValue};
|
||||
|
||||
use super::drafts::current;
|
||||
use super::event::{Key, Modifiers};
|
||||
use super::focus::Focus;
|
||||
use super::hit;
|
||||
use super::pointer::{Owners, ScrollMove, Seen, line_px, scroll_along, snap_slider, toggle_activation};
|
||||
use crate::bind::{Bound, Field};
|
||||
use crate::command::{Activation, ActivationKind};
|
||||
use crate::diagnostic::Diagnostic;
|
||||
use crate::time::Timestamp;
|
||||
|
||||
pub(super) fn key(
|
||||
focus: &mut Focus,
|
||||
key: Key,
|
||||
modifiers: Modifiers,
|
||||
repeat: bool,
|
||||
seen: &Seen<'_>,
|
||||
owners: &mut Owners<'_>,
|
||||
now: Timestamp,
|
||||
) -> Vec<Diagnostic> {
|
||||
if modifiers.ctrl || modifiers.alt || modifiers.meta {
|
||||
return Vec::new();
|
||||
}
|
||||
let index = seen.tree.index();
|
||||
let floor = hit::modal_floor(seen.laid, &index);
|
||||
if key == Key::Escape {
|
||||
if let Some(m) = floor.checked_sub(1) {
|
||||
if repeat {
|
||||
return Vec::new();
|
||||
}
|
||||
let act = Activation { node: seen.laid.nodes[m].id.clone(), kind: ActivationKind::Press };
|
||||
return owners.commands.activate(act, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger);
|
||||
}
|
||||
return Vec::new();
|
||||
}
|
||||
if key == Key::Tab {
|
||||
focus.step(modifiers.shift, seen.laid);
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(focused) = focus.node().cloned() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(node) = index.get(&focused).copied() else {
|
||||
return Vec::new();
|
||||
};
|
||||
match node {
|
||||
Node::Button(_) if matches!(key, Key::Enter | Key::Char(' ')) => {
|
||||
if repeat {
|
||||
return Vec::new();
|
||||
}
|
||||
let act = Activation { node: focused, kind: ActivationKind::Press };
|
||||
owners.commands.activate(act, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger)
|
||||
}
|
||||
Node::Toggle(_) if matches!(key, Key::Enter | Key::Char(' ')) => {
|
||||
if repeat {
|
||||
return Vec::new();
|
||||
}
|
||||
let act = toggle_activation(seen.tree, owners.drafts, focused);
|
||||
owners.commands.activate(act, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger)
|
||||
}
|
||||
Node::Slider(slider)
|
||||
if matches!(
|
||||
key,
|
||||
Key::Left | Key::Right | Key::Up | Key::Down | Key::PageUp | Key::PageDown | Key::Home | Key::End
|
||||
) =>
|
||||
{
|
||||
if repeat {
|
||||
return Vec::new();
|
||||
}
|
||||
let step = if slider.step.is_finite() && slider.step > 0.0 {
|
||||
slider.step
|
||||
} else {
|
||||
(slider.max - slider.min) / 100.0
|
||||
};
|
||||
let base = match current(seen.tree, Some(owners.drafts), &focused, Field::Value).as_deref() {
|
||||
Some(Bound::Number(v)) if v.is_finite() => *v,
|
||||
_ => slider.min,
|
||||
};
|
||||
let raw = match key {
|
||||
Key::Left | Key::Down => base - step,
|
||||
Key::Right | Key::Up => base + step,
|
||||
Key::PageDown => base - 10.0 * step,
|
||||
Key::PageUp => base + 10.0 * step,
|
||||
Key::Home => slider.min,
|
||||
Key::End => slider.max,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let Some(value) = snap_slider(slider, raw) else {
|
||||
return Vec::new();
|
||||
};
|
||||
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::TextInput(input) if !input.multiline && key == Key::Enter => {
|
||||
if repeat {
|
||||
return Vec::new();
|
||||
}
|
||||
let act = Activation { node: focused, kind: ActivationKind::Submit };
|
||||
owners.commands.activate(act, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger)
|
||||
}
|
||||
_ => {
|
||||
let Some((axis, mv)) = scroll_move(key, line_px(seen)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if let Some(pos) = seen.laid.nodes[floor..].iter().position(|n| n.id == focused) {
|
||||
scroll_along(floor + pos, axis, mv, seen.laid, owners.scroll);
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scroll_move(key: Key, line: f32) -> Option<(usize, ScrollMove)> {
|
||||
match key {
|
||||
Key::Up => Some((1, ScrollMove::Delta(-line))),
|
||||
Key::Down => Some((1, ScrollMove::Delta(line))),
|
||||
Key::Left => Some((0, ScrollMove::Delta(-line))),
|
||||
Key::Right => Some((0, ScrollMove::Delta(line))),
|
||||
Key::PageUp => Some((1, ScrollMove::Page(-1.0))),
|
||||
Key::PageDown => Some((1, ScrollMove::Page(1.0))),
|
||||
Key::Home => Some((1, ScrollMove::Start)),
|
||||
Key::End => Some((1, ScrollMove::End)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +1,13 @@
|
|||
//! What a host tells core about its user: the closed `InputEvent` vocabulary, the `Drafts` table
|
||||
//! that owns what the user has typed or chosen and not yet sent, hit-testing against the frame the
|
||||
//! user saw, and the pointer routes that turn a press, a drag or a wheel into an activation, a draft
|
||||
//! or a scroll offset.
|
||||
//! 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 event;
|
||||
mod focus;
|
||||
mod hit;
|
||||
mod keys;
|
||||
mod pointer;
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -6,13 +6,15 @@ use thing_contract::{BoolValue, InputValue, Node, NodeId, NumberValue, SliderNod
|
|||
|
||||
use super::drafts::{Drafts, current};
|
||||
use super::event::{InputEvent, PointerButton, WheelUnit};
|
||||
use super::focus::Focus;
|
||||
use super::hit::{Control, Reach, Target, reach, target};
|
||||
use super::keys;
|
||||
use crate::bind::{Bound, BoundTree, Field};
|
||||
use crate::command::{Activation, ActivationKind, Commands};
|
||||
use crate::diagnostic::Diagnostic;
|
||||
use crate::layout::{LaidTree, Metrics, Rect};
|
||||
use crate::port::{IdSource, Ledger, StatePort};
|
||||
use crate::render::{Rendered, ScrollOffsets, clamp, device_scale};
|
||||
use crate::render::{FocusView, Rendered, ScrollOffsets, clamp, device_scale};
|
||||
use crate::time::Timestamp;
|
||||
|
||||
/// The last good frame and how it was drawn: what every event is judged against.
|
||||
|
|
@ -30,7 +32,7 @@ pub(crate) struct Seen<'a> {
|
|||
|
||||
impl Seen<'_> {
|
||||
/// Device px per logical px, which is what a pointer is multiplied by to land on laid pixels.
|
||||
fn k(&self) -> f32 {
|
||||
pub(super) fn k(&self) -> f32 {
|
||||
device_scale(self.metrics, self.scale)
|
||||
}
|
||||
}
|
||||
|
|
@ -58,22 +60,42 @@ struct Pointer {
|
|||
press: Option<Press>,
|
||||
}
|
||||
|
||||
/// The routes every pointer and wheel event takes; it owns the `Pointer`.
|
||||
/// The routes every pointer, wheel, key and window-focus event takes; it owns `Pointer` and `Focus`.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Input {
|
||||
pointer: Pointer,
|
||||
focus: Focus,
|
||||
}
|
||||
|
||||
/// Snap `raw` to `slider.step` from `slider.min`, held in `[min, max]`.
|
||||
/// None when the slider has no usable range or `raw` is not finite.
|
||||
pub(super) fn snap_slider(slider: &SliderNode, raw: f64) -> Option<f64> {
|
||||
if !(slider.min.is_finite() && slider.max.is_finite() && slider.min < slider.max && raw.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let snapped = if slider.step.is_finite() && slider.step > 0.0 {
|
||||
slider.min + ((raw - slider.min) / slider.step).round() * slider.step
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
Some(snapped.clamp(slider.min, slider.max))
|
||||
}
|
||||
|
||||
/// The value a press at `x` on a Slider's track `rect` chooses: along `[min, max]`, snapped to `step`
|
||||
/// from `min`, held in range. None when the slider has no usable range or track.
|
||||
fn slider_value(slider: &SliderNode, rect: Rect, x: f32) -> Option<f64> {
|
||||
if !(slider.min.is_finite() && slider.max.is_finite() && slider.min < slider.max && rect.w > 0.0 && x.is_finite()) {
|
||||
if !(rect.w > 0.0 && x.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let along = f64::from((x - rect.x) / rect.w);
|
||||
let raw = slider.min + along * (slider.max - slider.min);
|
||||
let snapped = if slider.step.is_finite() && slider.step > 0.0 { slider.min + ((raw - slider.min) / slider.step).round() * slider.step } else { raw };
|
||||
Some(snapped.clamp(slider.min, slider.max))
|
||||
snap_slider(slider, raw)
|
||||
}
|
||||
|
||||
pub(super) fn toggle_activation(tree: &BoundTree, drafts: &Drafts, node: NodeId) -> Activation {
|
||||
let shown = current(tree, Some(drafts), &node, Field::Checked);
|
||||
let checked = matches!(shown.as_deref(), Some(Bound::Bool(true)));
|
||||
Activation { node, kind: ActivationKind::Change(InputValue::Bool(BoolValue { value: !checked })) }
|
||||
}
|
||||
|
||||
fn placed_rect(rendered: &Rendered, node: &NodeId) -> Option<Rect> {
|
||||
|
|
@ -85,6 +107,23 @@ impl Input {
|
|||
Self::default()
|
||||
}
|
||||
|
||||
pub(crate) fn clear_focus(&mut self) {
|
||||
self.focus.clear();
|
||||
}
|
||||
|
||||
pub(crate) fn reconcile(&mut self, tree: &BoundTree, laid: &LaidTree, scroll: &mut ScrollOffsets) {
|
||||
self.focus.reconcile(tree, laid, scroll);
|
||||
}
|
||||
|
||||
pub(crate) fn focus_view(&self) -> Option<FocusView<'_>> {
|
||||
self.focus.view()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn focus(&self) -> &Focus {
|
||||
&self.focus
|
||||
}
|
||||
|
||||
/// 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(crate) fn cancel(&mut self, surface: &str, drafts: &mut Drafts) {
|
||||
|
|
@ -93,8 +132,8 @@ 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.
|
||||
/// Route one event: pointer, wheel, key and window-focus. Text and composition are not routed
|
||||
/// yet, and only the primary button presses. The diagnostics are the activations' refusals.
|
||||
pub(crate) fn event(&mut self, event: &InputEvent, seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp) -> Vec<Diagnostic> {
|
||||
let surface = seen.tree.resolved().document().record_key();
|
||||
match event {
|
||||
|
|
@ -103,7 +142,14 @@ impl Input {
|
|||
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::Key { key, modifiers, repeat } => return keys::key(&mut self.focus, *key, *modifiers, *repeat, seen, owners, now),
|
||||
InputEvent::Focus(window) => {
|
||||
self.focus.set_window(*window);
|
||||
if !window {
|
||||
self.cancel(&surface, owners.drafts);
|
||||
}
|
||||
}
|
||||
InputEvent::Text(_) | InputEvent::Compose { .. } | InputEvent::PointerDown { .. } | InputEvent::PointerUp { .. } => {}
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
|
@ -113,7 +159,13 @@ impl Input {
|
|||
self.cancel(surface, owners.drafts);
|
||||
let index = seen.tree.index();
|
||||
let mut said = Vec::new();
|
||||
self.pointer.press = target(seen.rendered, seen.laid, &index, at, seen.k()).and_then(|hit| match (hit.control, index.get(&hit.node)) {
|
||||
let hit = target(seen.rendered, seen.laid, &index, at, seen.k());
|
||||
match &hit {
|
||||
Some(t) if t.control == Control::Scrim => {}
|
||||
Some(t) => self.focus.set(Some(t.node.clone()), false),
|
||||
None => self.focus.set(None, false),
|
||||
}
|
||||
self.pointer.press = hit.and_then(|hit| match (hit.control, index.get(&hit.node)) {
|
||||
(Control::Slider, Some(Node::Slider(slider))) => {
|
||||
let value = placed_rect(seen.rendered, &hit.node).and_then(|rect| slider_value(slider, rect, at.0))?;
|
||||
// A slider that takes no change takes no press: nothing is drafted, so nothing is left unsent.
|
||||
|
|
@ -157,11 +209,7 @@ impl Input {
|
|||
}
|
||||
match pressed.control {
|
||||
Control::Button | Control::Scrim => Activation { node: pressed.node, kind: ActivationKind::Press },
|
||||
Control::Toggle => {
|
||||
let shown = current(seen.tree, Some(owners.drafts), &pressed.node, Field::Checked);
|
||||
let checked = matches!(shown.as_deref(), Some(Bound::Bool(true)));
|
||||
Activation { node: pressed.node, kind: ActivationKind::Change(InputValue::Bool(BoolValue { value: !checked })) }
|
||||
}
|
||||
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(),
|
||||
|
|
@ -172,39 +220,69 @@ impl Input {
|
|||
}
|
||||
}
|
||||
|
||||
pub(super) enum ScrollMove {
|
||||
Delta(f32),
|
||||
Page(f32),
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
pub(super) fn line_px(seen: &Seen<'_>) -> f32 {
|
||||
let line = match seen.metrics {
|
||||
Metrics::Cells => 1.0,
|
||||
Metrics::Pixels => seen.line,
|
||||
};
|
||||
line * seen.k()
|
||||
}
|
||||
|
||||
pub(super) fn scroll_along(start: usize, axis: usize, mv: ScrollMove, laid: &LaidTree, scroll: &mut ScrollOffsets) {
|
||||
if let ScrollMove::Delta(d) = mv
|
||||
&& (!d.is_finite() || d == 0.0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut over = Some(start);
|
||||
while let Some(i) = over {
|
||||
let node = &laid.nodes[i];
|
||||
if let Some(max) = node.max_scroll {
|
||||
let held = scroll.of(node);
|
||||
let cur = if axis == 0 { held.0 } else { held.1 };
|
||||
let axis_max = if axis == 0 { max.0 } else { max.1 };
|
||||
let target = match mv {
|
||||
ScrollMove::Delta(d) => cur + d,
|
||||
ScrollMove::Page(sign) => {
|
||||
let page = node.clip.map_or_else(
|
||||
|| if axis == 0 { node.rect.w } else { node.rect.h },
|
||||
|clip| if axis == 0 { clip.w } else { clip.h },
|
||||
);
|
||||
cur + sign * page
|
||||
}
|
||||
ScrollMove::Start => 0.0,
|
||||
ScrollMove::End => axis_max,
|
||||
};
|
||||
let want = if axis == 0 { (target, held.1) } else { (held.0, target) };
|
||||
let next = clamp(want, max);
|
||||
if next != held {
|
||||
scroll.set(node.id.clone(), next);
|
||||
break;
|
||||
}
|
||||
}
|
||||
over = node.parent.map(|parent| parent as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
let index = seen.tree.index();
|
||||
let Some(Reach::Node(start) | Reach::Scrim(start)) = reach(seen.rendered, seen.laid, &index, at, seen.k()) else { return };
|
||||
let to_device = seen.k();
|
||||
let line = match seen.metrics {
|
||||
Metrics::Cells => 1.0,
|
||||
Metrics::Pixels => seen.line,
|
||||
};
|
||||
let per = match unit {
|
||||
WheelUnit::Units => to_device,
|
||||
WheelUnit::Lines => line * to_device,
|
||||
WheelUnit::Units => seen.k(),
|
||||
WheelUnit::Lines => line_px(seen),
|
||||
};
|
||||
for axis in [0usize, 1] {
|
||||
let amount = [delta.0, delta.1][axis] * per;
|
||||
if !amount.is_finite() || amount == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let mut over = Some(start);
|
||||
while let Some(i) = over {
|
||||
let node = &seen.laid.nodes[i];
|
||||
if let Some(max) = node.max_scroll {
|
||||
let held = scroll.of(node);
|
||||
let want = if axis == 0 { (held.0 + amount, held.1) } else { (held.0, held.1 + amount) };
|
||||
let next = clamp(want, max);
|
||||
if next != held {
|
||||
scroll.set(node.id.clone(), next);
|
||||
break;
|
||||
}
|
||||
}
|
||||
over = node.parent.map(|parent| parent as usize);
|
||||
}
|
||||
scroll_along(start, axis, ScrollMove::Delta(amount), seen.laid, scroll);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -195,6 +195,7 @@ impl Rig {
|
|||
/// 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");
|
||||
self.input.reconcile(&self.tree, &self.laid, &mut self.scroll);
|
||||
let states = self.commands.view(&self.surface);
|
||||
let theme = Theme::std();
|
||||
let input = RenderInput {
|
||||
|
|
@ -203,7 +204,7 @@ impl Rig {
|
|||
viewport: viewport(self.metrics),
|
||||
scroll: &self.scroll,
|
||||
theme: &theme,
|
||||
session: Session::new(&self.drafts, &states),
|
||||
session: Session::new(&self.drafts, &states).with_focus(self.input.focus_view()),
|
||||
};
|
||||
self.rendered = render(&self.tree, &self.laid, &input, &mut measure(self.metrics));
|
||||
}
|
||||
|
|
@ -957,3 +958,92 @@ fn a_wheel_scrolls_the_horizontal_axis_by_its_own_delta() {
|
|||
assert_eq!(rig.offset("pane"), Some((6.0 * k, 4.0 * k)), "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn tab(shift: bool) -> InputEvent {
|
||||
InputEvent::Key {
|
||||
key: crate::input::Key::Tab,
|
||||
modifiers: Modifiers { shift, ..mods() },
|
||||
repeat: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_order_follows_laid_order_respects_modal_floor_and_includes_empty_scrollers() {
|
||||
// controls_surface: a, b, flag, level
|
||||
for mode in MODES {
|
||||
let rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||
let order: Vec<_> = rig.input.focus().order().iter().map(|id| id.as_str()).collect();
|
||||
assert_eq!(order, ["a", "b", "flag", "level"], "{mode:?}");
|
||||
}
|
||||
|
||||
// nested_surface: inner scroller has no focusables under it (stop), outer has inner (not a stop)
|
||||
let rig = Rig::new(Port::new(), &nested_surface(), MODES[0]);
|
||||
let order: Vec<_> = rig.input.focus().order().iter().map(|id| id.as_str()).collect();
|
||||
assert_eq!(order, ["inner"]);
|
||||
|
||||
// rows_surface: pane has focusable buttons under it, so pane is NOT a stop
|
||||
let rig = Rig::new(feed(), &rows_surface(), MODES[0]);
|
||||
let order: Vec<_> = rig.input.focus().order().iter().map(|id| id.as_str()).collect();
|
||||
assert_eq!(order.len(), 21);
|
||||
assert_eq!(order.first().copied(), Some(row_id("item-0000", "row").as_str()));
|
||||
assert_eq!(order.last().copied(), Some("below"));
|
||||
|
||||
// modal_surface: order only includes nodes >= hit::modal_floor
|
||||
let rig = Rig::new(Port::new(), &modal_surface(), MODES[0]);
|
||||
let order: Vec<_> = rig.input.focus().order().iter().map(|id| id.as_str()).collect();
|
||||
assert_eq!(order, ["confirm"]);
|
||||
assert_eq!(rig.input.focus().node().map(|n| n.as_str()), Some("confirm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_button_is_skipped_in_order_but_keeps_focus_until_next_traversal() {
|
||||
let mut b_disabled = button("b", "go", 160.0, 48.0);
|
||||
if let Node::Button(btn) = &mut b_disabled {
|
||||
btn.enabled = BoolSource::Record(RecordBind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: Some(ProviderId::new(PROVIDER)),
|
||||
schema: SchemaId::new("gamecult.thing.test.flag.v1"),
|
||||
key: RecordKey::new("flag"),
|
||||
}),
|
||||
member: path(&["Enabled"]),
|
||||
});
|
||||
}
|
||||
let doc = surface(
|
||||
indented("root", vec![button("a", "go", 160.0, 48.0), b_disabled, button("c", "go", 160.0, 48.0)]),
|
||||
vec![decl("go", &[])],
|
||||
);
|
||||
let mut port = Port::new();
|
||||
let flag_addr = Address {
|
||||
provider: ProviderId::new(PROVIDER),
|
||||
schema: SchemaId::new("gamecult.thing.test.flag.v1"),
|
||||
key: RecordKey::new("flag"),
|
||||
};
|
||||
let put_enabled = |port: &mut Port, enabled: bool| {
|
||||
let value = StateValue::Record(vec![("Enabled".into(), StateValue::Bool(enabled))]);
|
||||
let record = Record::State { schema: flag_addr.schema.clone(), value };
|
||||
port.records.insert(flag_addr.clone(), Entry { address: flag_addr.clone(), record });
|
||||
};
|
||||
put_enabled(&mut port, true);
|
||||
let mut rig = Rig::new(port, &doc, MODES[0]);
|
||||
assert_eq!(rig.input.focus().order().iter().map(|id| id.as_str()).collect::<Vec<_>>(), ["a", "b", "c"]);
|
||||
|
||||
// Focus b via Tab twice
|
||||
rig.send(tab(false));
|
||||
rig.send(tab(false));
|
||||
assert_eq!(rig.input.focus().node().map(|n| n.as_str()), Some("b"));
|
||||
|
||||
// Disable b and rebind: b leaves order, but keeps focus until the next traversal
|
||||
put_enabled(&mut rig.state, false);
|
||||
let limits = Limits::default();
|
||||
let resolved = resolve(&doc, &rig.state, &limits).tree.unwrap();
|
||||
let mut binder = Binder::new(limits);
|
||||
binder.bind(resolved, &mut rig.state, &mut rig.ledger);
|
||||
rig.tree = binder.tree(&rig.surface).unwrap().clone();
|
||||
rig.draw();
|
||||
assert_eq!(rig.input.focus().order().iter().map(|id| id.as_str()).collect::<Vec<_>>(), ["a", "c"]);
|
||||
assert_eq!(rig.input.focus().node().map(|n| n.as_str()), Some("b"));
|
||||
|
||||
// Next Tab steps from b's laid position forward to c; Shift+Tab from b goes to a
|
||||
rig.send(tab(false));
|
||||
assert_eq!(rig.input.focus().node().map(|n| n.as_str()), Some("c"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,22 +35,35 @@ pub struct RenderInput<'a> {
|
|||
pub session: Session<'a>,
|
||||
}
|
||||
|
||||
/// What render draws of keyboard focus: the focused laid node and whether its ring shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FocusView<'a> {
|
||||
pub node: &'a NodeId,
|
||||
pub visible: bool,
|
||||
}
|
||||
|
||||
/// What the user has done that the documents and state do not say: the drafts that draw over bound
|
||||
/// values, and the node states (busy, marked) commands derived. `Session::EMPTY` is a surface nobody
|
||||
/// has touched; a frame drawn with it is the frame the bound tree alone gives.
|
||||
/// values, the node states (busy, marked) commands derived, and the keyboard focus ring.
|
||||
/// `Session::EMPTY` is a surface nobody has touched; a frame drawn with it is the frame the bound tree alone gives.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Session<'a> {
|
||||
pub drafts: Option<&'a Drafts>,
|
||||
pub states: Option<&'a NodeStates>,
|
||||
pub focus: Option<FocusView<'a>>,
|
||||
}
|
||||
|
||||
impl Session<'static> {
|
||||
pub const EMPTY: Session<'static> = Session { drafts: None, states: None };
|
||||
pub const EMPTY: Session<'static> = Session { drafts: None, states: None, focus: None };
|
||||
}
|
||||
|
||||
impl<'a> Session<'a> {
|
||||
pub fn new(drafts: &'a Drafts, states: &'a NodeStates) -> Self {
|
||||
Self { drafts: Some(drafts), states: Some(states) }
|
||||
Self { drafts: Some(drafts), states: Some(states), focus: None }
|
||||
}
|
||||
|
||||
pub fn with_focus(mut self, focus: Option<FocusView<'a>>) -> Self {
|
||||
self.focus = focus;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -228,6 +241,15 @@ impl<'a> Painter<'a> {
|
|||
let color = self.named(&laid.id, "thing.error");
|
||||
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
||||
}
|
||||
// Focus ring: after its own paint (and mark ring), before its children and own clip.
|
||||
if self.input.session.focus.is_some_and(|focus| focus.visible && focus.node == &laid.id) {
|
||||
let ring = match (laid.max_scroll, laid.clip) {
|
||||
(Some(_), Some(padding)) => self.logical(padding, shift),
|
||||
_ => rect,
|
||||
};
|
||||
let color = self.named(&laid.id, "thing.focus");
|
||||
self.out.commands.push(RenderCommand::StrokeRect { rect: ring, radius: 0.0, width: 1.0, color });
|
||||
}
|
||||
if let (Some(padding), Node::Box(b)) = (laid.clip, node) {
|
||||
let clip = self.logical(padding, shift);
|
||||
let border = self.border(b).map_or(0.0, |(_, width)| width);
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ impl Theme {
|
|||
("thing.control.text", 0xeeeef4ff),
|
||||
("thing.control.disabled", 0x3a3a48ff),
|
||||
("thing.plot.mark", 0x7c9cffff),
|
||||
("thing.focus", 0xb4befeff),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, hex)| (name.to_string(), rgba(hex)))
|
||||
|
|
|
|||
10
crates/thing-core/tests/goldens/render-f04-form-focus.txt
Normal file
10
crates/thing-core/tests/goldens/render-f04-form-focus.txt
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
|
||||
stroke 2 2 796 20 r0 w1 #4a4a60ff
|
||||
fill 780 4 16 16 r0 #7c9cffff
|
||||
stroke 2 2 796 20 r0 w1 #b4befeff
|
||||
fill 2 37.5 796 5 r0 #4a4a60ff
|
||||
fill 778 30 20 20 r0 #7c9cffff
|
||||
stroke 2 58 796 24 r0 w1 #4a4a60ff
|
||||
text 4 60 #eeeef4ff font0 size16 [68@0,0 97@8,0 114@16,0 107@24,0]
|
||||
stroke 2 90 796 24 r0 w1 #4a4a60ff
|
||||
text 4 92 #eeeef4ff font0 size16 [56@0,0 48@8,0 56@16,0 48@24,0]
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1 pixels
|
||||
text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,0 99@48,0 104@56,0 105@64,0 118@72,0 101@80,0 32@88,0 104@96,0 111@104,0 108@112,0 100@120,0 115@128,0 32@136,0 49@144,0 50@152,0 32@160,0 105@168,0 116@176,0 101@184,0 109@192,0 115@200,0 46@208,0]
|
||||
fill 0 0 800 600 r0 #00000099
|
||||
fill 0 266 800 68 r6 #2c2c3eff
|
||||
text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0]
|
||||
fill 2 292 796 16 r0 #2c2c3eff
|
||||
stroke 2 292 796 16 r0 w1 #4a4a60ff
|
||||
stroke 2 292 796 16 r0 w1 #b4befeff
|
||||
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
|
||||
fill 2 316 796 16 r0 #2c2c3eff
|
||||
stroke 2 316 796 16 r0 w1 #4a4a60ff
|
||||
text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0]
|
||||
608
crates/thing-core/tests/keyboard.rs
Normal file
608
crates/thing-core/tests/keyboard.rs
Normal file
|
|
@ -0,0 +1,608 @@
|
|||
//! Keyboard focus, traversal, modal trap, key activations, Slider keys, key scrolling,
|
||||
//! reveal and `:focus-visible` through `Core::frame` in Pixels (at 1.0 and 1.5) and Cells.
|
||||
|
||||
mod support;
|
||||
|
||||
use support::*;
|
||||
use thing_contract::*;
|
||||
use thing_core::bind::{Binder, Instance};
|
||||
use thing_core::diagnostic::Code;
|
||||
use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
|
||||
use thing_core::layout::{LayoutFrame, Metrics, Rect, layout};
|
||||
use thing_core::port::Ledger;
|
||||
use thing_core::render::{Placed, RenderCommand, RenderInput, ScrollOffsets, Session, 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::{self, Item, Settings};
|
||||
|
||||
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 => (80.0, 24.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 shift_tab() -> InputEvent {
|
||||
InputEvent::Key { key: Key::Tab, modifiers: Modifiers { shift: true, ..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 inside(rect: Rect) -> (f32, f32) {
|
||||
(rect.x + 0.5, rect.y + 0.5)
|
||||
}
|
||||
|
||||
fn row_id(item: &str, node: &str) -> NodeId {
|
||||
NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false)))
|
||||
}
|
||||
|
||||
struct Placement(Vec<Placed>);
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
struct Host {
|
||||
core: Core,
|
||||
state: MemState,
|
||||
ids: SeqIds,
|
||||
mode: (Metrics, 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, now: 0 };
|
||||
host.frame(vec![]);
|
||||
host
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<InputEvent>) -> FrameOutput {
|
||||
self.now += 1;
|
||||
let input = FrameInput { now: Timestamp(self.now), viewport: viewport(self.mode.0), scale: self.mode.1, events };
|
||||
self.core.frame(input, Ports { state: &mut self.state, ids: &mut self.ids })
|
||||
}
|
||||
}
|
||||
|
||||
fn focus_rings(output: &FrameOutput) -> Vec<Rect> {
|
||||
let color = Theme::std().color("thing.focus").unwrap();
|
||||
output
|
||||
.commands
|
||||
.iter()
|
||||
.filter_map(|cmd| match cmd {
|
||||
RenderCommand::StrokeRect { rect, color: c, .. } if *c == color => Some(*rect),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rect_approx(a: Rect, b: Rect) -> bool {
|
||||
(a.x - b.x).abs() < 1e-3 && (a.y - b.y).abs() < 1e-3 && (a.w - b.w).abs() < 1e-3 && (a.h - b.h).abs() < 1e-3
|
||||
}
|
||||
|
||||
fn feed(n: usize) -> MemState {
|
||||
let mut state = MemState::new();
|
||||
for i in 0..n {
|
||||
let id = format!("item-{i:04}");
|
||||
state.put_state(&ProviderId::new(FEED), &id, &Item { id: id.clone(), title: id.clone() });
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
fn complete_latest(host: &mut Host, invocation: &CommandInvocation) {
|
||||
let provider = ProviderId::new(PROVIDER);
|
||||
let result = CommandResult::completed(invocation, seq(1));
|
||||
host.state.put(&provider, &result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traversal_order_f04_and_disabled_vs_busy() {
|
||||
for mode in MODES {
|
||||
let fixture = Fixture::F04Form;
|
||||
let mut state = MemState::from_fixture(fixture);
|
||||
state::script(fixture, &mut state);
|
||||
let document = fixture.load().surfaces.remove(0);
|
||||
let mut rig_state = MemState::from_fixture(fixture);
|
||||
state::script(fixture, &mut rig_state);
|
||||
let rig = placement(rig_state, &document, mode);
|
||||
let expected = [rig.rect("enabled"), rig.rect("volume"), rig.rect("theme"), rig.rect("port")];
|
||||
|
||||
let mut host = Host::new(state, &document, mode);
|
||||
// Initially no focus ring on a surface without a modal.
|
||||
assert_eq!(focus_rings(&host.frame(vec![])), vec![], "{mode:?}");
|
||||
|
||||
// Tab walks enabled -> volume -> theme -> port -> wraps to enabled.
|
||||
for rect in expected.iter().chain(std::iter::once(&expected[0])) {
|
||||
let out = host.frame(vec![key(Key::Tab)]);
|
||||
let rings = focus_rings(&out);
|
||||
assert_eq!(rings.len(), 1, "{mode:?}");
|
||||
assert!(rect_approx(rings[0], *rect), "{mode:?}: got {:?}, expected {:?}", rings[0], rect);
|
||||
}
|
||||
|
||||
// Shift+Tab reverses back to port -> theme -> volume -> enabled.
|
||||
for rect in expected.iter().rev() {
|
||||
let out = host.frame(vec![shift_tab()]);
|
||||
let rings = focus_rings(&out);
|
||||
assert_eq!(rings.len(), 1, "{mode:?}");
|
||||
assert!(rect_approx(rings[0], *rect), "{mode:?}: got {:?}, expected {:?}", rings[0], rect);
|
||||
}
|
||||
}
|
||||
|
||||
// Disabled Button is skipped; busy Button is not skipped; newly disabled focused Button stays until next Tab.
|
||||
let mut b_disabled = button("b", "go", 160.0, 48.0);
|
||||
if let Node::Button(btn) = &mut b_disabled {
|
||||
btn.enabled = BoolSource::Record(RecordBind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: Some(ProviderId::new(PROVIDER)),
|
||||
schema: SchemaId::new("gamecult.thing.test.flag.v1"),
|
||||
key: RecordKey::new("flag"),
|
||||
}),
|
||||
member: path(&["Enabled"]),
|
||||
});
|
||||
}
|
||||
let doc = surface(
|
||||
indented("root", vec![button("a", "go", 160.0, 48.0), b_disabled, button("c", "go", 160.0, 48.0)]),
|
||||
vec![decl("go", &[])],
|
||||
);
|
||||
let addr = Address {
|
||||
provider: ProviderId::new(PROVIDER),
|
||||
schema: SchemaId::new("gamecult.thing.test.flag.v1"),
|
||||
key: RecordKey::new("flag"),
|
||||
};
|
||||
let put_enabled = |state: &mut MemState, enabled: bool| {
|
||||
state.upsert(Entry {
|
||||
address: addr.clone(),
|
||||
record: Record::State {
|
||||
schema: addr.schema.clone(),
|
||||
value: StateValue::Record(vec![("Enabled".into(), StateValue::Bool(enabled))]),
|
||||
},
|
||||
});
|
||||
};
|
||||
let mut state = MemState::new();
|
||||
put_enabled(&mut state, false);
|
||||
let rig = placement(state.clone(), &doc, MODES[0]);
|
||||
let mut host = Host::new(state, &doc, MODES[0]);
|
||||
|
||||
// Focus a (and make a busy by activating it), then Tab skips disabled b and reaches c.
|
||||
let out_a = host.frame(vec![key(Key::Tab), key(Key::Enter)]);
|
||||
assert_eq!(out_a.outbound.len(), 1);
|
||||
assert!(rect_approx(focus_rings(&out_a)[0], rig.rect("a")));
|
||||
// Next Tab goes straight to c (skipping disabled b), and Tab again wraps to busy a (not skipped!).
|
||||
assert!(rect_approx(focus_rings(&host.frame(vec![key(Key::Tab)]))[0], rig.rect("c")));
|
||||
assert!(rect_approx(focus_rings(&host.frame(vec![key(Key::Tab)]))[0], rig.rect("a")));
|
||||
|
||||
// Enable b, Tab to b, then disable b: b keeps focus until next Tab, then Tab lands on c.
|
||||
put_enabled(&mut host.state, true);
|
||||
host.frame(vec![]);
|
||||
let out_b = host.frame(vec![key(Key::Tab)]);
|
||||
assert!(rect_approx(focus_rings(&out_b)[0], rig.rect("b")));
|
||||
put_enabled(&mut host.state, false);
|
||||
let still_b = host.frame(vec![]);
|
||||
assert!(rect_approx(focus_rings(&still_b)[0], rig.rect("b")));
|
||||
let next_c = host.frame(vec![key(Key::Tab)]);
|
||||
assert!(rect_approx(focus_rings(&next_c)[0], rig.rect("c")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modal_trap_f05_opener_restore_and_escape() {
|
||||
for mode in MODES {
|
||||
let fixture = Fixture::F05ModalOverlay;
|
||||
let state = MemState::from_fixture(fixture);
|
||||
let document = fixture.load().surfaces.remove(0);
|
||||
let rig = placement(MemState::from_fixture(fixture), &document, mode);
|
||||
let mut host = Host::new(state, &document, mode);
|
||||
|
||||
// Modal is open on first frame: first focusable (confirm) takes focus.
|
||||
let initial = host.frame(vec![]);
|
||||
assert_eq!(focus_rings(&initial).len(), 1, "{mode:?}");
|
||||
assert!(rect_approx(focus_rings(&initial)[0], rig.rect("confirm")), "{mode:?}");
|
||||
|
||||
// Tab cycles inside the modal only: confirm -> cancel -> confirm.
|
||||
assert!(rect_approx(focus_rings(&host.frame(vec![key(Key::Tab)]))[0], rig.rect("cancel")), "{mode:?}");
|
||||
assert!(rect_approx(focus_rings(&host.frame(vec![key(Key::Tab)]))[0], rig.rect("confirm")), "{mode:?}");
|
||||
|
||||
// Escape mints dismiss whatever has focus inside the modal.
|
||||
let esc = host.frame(vec![key(Key::Escape)]);
|
||||
assert_eq!(esc.outbound.len(), 1, "{mode:?}");
|
||||
assert_eq!(esc.outbound[0].command.as_str(), "cancel", "{mode:?}");
|
||||
}
|
||||
|
||||
// Modal opening from a focused background button saves opener, traps focus, and closing returns to opener.
|
||||
let mut modal_open = overlay("modal", true, vec![column("dialog", Some((160.0, 96.0)), Overflow::Visible, vec![button("confirm", "confirm", 160.0, 48.0)])]);
|
||||
if let Node::Overlay(o) = &mut modal_open {
|
||||
o.common.visible = Some(BoolSource::Record(RecordBind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: Some(ProviderId::new(PROVIDER)),
|
||||
schema: SchemaId::new("gamecult.thing.test.modal.v1"),
|
||||
key: RecordKey::new("open"),
|
||||
}),
|
||||
member: path(&["Open"]),
|
||||
}));
|
||||
}
|
||||
let doc = surface(
|
||||
column("root", None, Overflow::Visible, vec![button("behind", "behind", 160.0, 48.0), button("other", "other", 160.0, 48.0), modal_open]),
|
||||
vec![decl("behind", &[]), decl("other", &[]), decl("confirm", &[]), decl("dismiss", &[])],
|
||||
);
|
||||
let addr = Address {
|
||||
provider: ProviderId::new(PROVIDER),
|
||||
schema: SchemaId::new("gamecult.thing.test.modal.v1"),
|
||||
key: RecordKey::new("open"),
|
||||
};
|
||||
let set_open = |state: &mut MemState, open: bool| {
|
||||
state.upsert(Entry {
|
||||
address: addr.clone(),
|
||||
record: Record::State {
|
||||
schema: addr.schema.clone(),
|
||||
value: StateValue::Record(vec![("Open".into(), StateValue::Bool(open))]),
|
||||
},
|
||||
});
|
||||
};
|
||||
let mut open_state = MemState::new();
|
||||
set_open(&mut open_state, true);
|
||||
let rig_open = placement(open_state, &doc, MODES[0]);
|
||||
let mut state = MemState::new();
|
||||
set_open(&mut state, false);
|
||||
let rig_closed = placement(state.clone(), &doc, MODES[0]);
|
||||
|
||||
let mut host = Host::new(state, &doc, MODES[0]);
|
||||
// Focus "other" (second Tab).
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
let at_other = host.frame(vec![key(Key::Tab)]);
|
||||
assert!(rect_approx(focus_rings(&at_other)[0], rig_closed.rect("other")));
|
||||
|
||||
// Open modal: focus enters modal's confirm.
|
||||
set_open(&mut host.state, true);
|
||||
let opened = host.frame(vec![]);
|
||||
assert!(rect_approx(focus_rings(&opened)[0], rig_open.rect("confirm")));
|
||||
|
||||
// Close modal: focus returns to opener ("other").
|
||||
set_open(&mut host.state, false);
|
||||
let closed = host.frame(vec![]);
|
||||
assert!(rect_approx(focus_rings(&closed)[0], rig_closed.rect("other")));
|
||||
|
||||
// A modal with NO focusable content has no focus ring, yet Escape still mints dismiss.
|
||||
let empty_modal = surface(
|
||||
column("root", None, Overflow::Visible, vec![overlay("modal", true, vec![fixed("info", 160.0, 48.0)])]),
|
||||
vec![decl("dismiss", &[])],
|
||||
);
|
||||
let mut empty_host = Host::new(MemState::new(), &empty_modal, MODES[0]);
|
||||
assert_eq!(focus_rings(&empty_host.frame(vec![])), vec![]);
|
||||
let esc = empty_host.frame(vec![key(Key::Escape)]);
|
||||
assert_eq!(esc.outbound.len(), 1);
|
||||
assert_eq!(esc.outbound[0].command.as_str(), "dismiss");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_survives_republish_and_repeat_reorder_and_falls_back_on_removal() {
|
||||
// Keyed Repeat: focus on item-0001 survives reorder, and falls back to preceding (item-0000) then next on removal.
|
||||
let doc = rows_surface();
|
||||
let mut host = Host::new(feed(3), &doc, MODES[0]);
|
||||
// Tab to item-0000, then Tab to item-0001.
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
// Reorder by deleting item-0000 and republishing? First check republish keeping id keeps focus.
|
||||
host.state.put(&doc.provider_id, &doc);
|
||||
assert_eq!(focus_rings(&host.frame(vec![])).len(), 1);
|
||||
// Activating Enter fires on item-0001.
|
||||
let out1 = host.frame(vec![key(Key::Enter)]);
|
||||
assert_eq!(out1.outbound[0].items, vec!["item-0001"]);
|
||||
complete_latest(&mut host, &out1.outbound[0]);
|
||||
|
||||
// Remove item-0001: fallback must move to nearest preceding focusable (item-0000).
|
||||
host.state.delete(&Address {
|
||||
provider: ProviderId::new(FEED),
|
||||
schema: SchemaId::new("gamecult.thing.test.item.v1"),
|
||||
key: RecordKey::new("item-0001"),
|
||||
});
|
||||
let after_del_1 = host.frame(vec![key(Key::Enter)]);
|
||||
assert_eq!(after_del_1.outbound[0].items, vec!["item-0000"]);
|
||||
complete_latest(&mut host, &after_del_1.outbound[0]);
|
||||
|
||||
// Remove item-0000 (first in order, no preceding): fallback must move to next (item-0002).
|
||||
host.state.delete(&Address {
|
||||
provider: ProviderId::new(FEED),
|
||||
schema: SchemaId::new("gamecult.thing.test.item.v1"),
|
||||
key: RecordKey::new("item-0000"),
|
||||
});
|
||||
let after_del_0 = host.frame(vec![key(Key::Enter)]);
|
||||
assert_eq!(after_del_0.outbound[0].items, vec!["item-0002"]);
|
||||
|
||||
// Surface switch clears focus.
|
||||
let mut second = controls_surface();
|
||||
second.label = seg("second");
|
||||
host.state.put(&second.provider_id, &second);
|
||||
host.core.show(second.provider_id.clone(), RecordKey::new(second.record_key()));
|
||||
let switched = host.frame(vec![]);
|
||||
assert_eq!(focus_rings(&switched), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activation_keys_button_toggle_text_input_repeat_text_and_confirm_block() {
|
||||
// Button: Enter and Space activate once; repeat activates nothing; Key+Text Space activates once; busy is silent.
|
||||
let mut doc = controls_surface();
|
||||
let confirm_decl = CommandDecl {
|
||||
id: CommandId::new("ask"),
|
||||
payload_schema: SchemaId::new("gamecult.thing.test.ask.v1"),
|
||||
captures: vec![],
|
||||
confirm: Some("sure?".into()),
|
||||
};
|
||||
if let Node::Box(root) = &mut doc.root {
|
||||
root.children.push(button("ask-btn", "ask", 160.0, 48.0));
|
||||
}
|
||||
doc.commands.push(confirm_decl);
|
||||
|
||||
let mut host = Host::new(MemState::new(), &doc, MODES[0]);
|
||||
// Tab to "a", press Enter -> mints once.
|
||||
let enter = host.frame(vec![key(Key::Tab), key(Key::Enter)]);
|
||||
assert_eq!(enter.outbound.len(), 1);
|
||||
assert_eq!(enter.outbound[0].command.as_str(), "go");
|
||||
|
||||
// Busy Button is silent on Enter/Space.
|
||||
let busy_press = host.frame(vec![key(Key::Enter), key(Key::Char(' '))]);
|
||||
assert!(busy_press.outbound.is_empty());
|
||||
assert!(busy_press.diagnostics.is_empty());
|
||||
|
||||
// Tab to "b": repeat Space/Enter mints nothing; Key(' ') + Text(" ") mints once.
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
let rep = host.frame(vec![key_repeat(Key::Enter), key_repeat(Key::Char(' '))]);
|
||||
assert!(rep.outbound.is_empty());
|
||||
let space = host.frame(vec![key(Key::Char(' ')), InputEvent::Text(" ".into())]);
|
||||
assert_eq!(space.outbound.len(), 1);
|
||||
assert_eq!(space.outbound[0].command.as_str(), "go");
|
||||
|
||||
// Tab to Toggle "flag": Space flips false -> true and fires once; Enter flips true -> false.
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
let tog1 = host.frame(vec![key(Key::Char(' ')), InputEvent::Text(" ".into())]);
|
||||
assert_eq!(tog1.outbound.len(), 1);
|
||||
assert_eq!(tog1.outbound[0].captured[0].value, InputValue::Bool(BoolValue { value: true }));
|
||||
complete_latest(&mut host, &tog1.outbound[0]);
|
||||
let tog2 = host.frame(vec![key(Key::Enter)]);
|
||||
assert_eq!(tog2.outbound.len(), 1);
|
||||
assert_eq!(tog2.outbound[0].captured[0].value, InputValue::Bool(BoolValue { value: false }));
|
||||
complete_latest(&mut host, &tog2.outbound[0]);
|
||||
|
||||
// Tab to "level" (skip) then "ask-btn", press Enter -> waits for confirmation; Space on "a" yields ActivationBlocked.
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
let ask = host.frame(vec![key(Key::Enter)]);
|
||||
assert!(ask.outbound.is_empty());
|
||||
assert!(host.core.confirming().is_some());
|
||||
|
||||
host.frame(vec![key(Key::Tab)]); // wraps to "a"
|
||||
let blocked = host.frame(vec![key(Key::Char(' '))]);
|
||||
assert!(blocked.outbound.is_empty());
|
||||
assert_eq!(blocked.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::ActivationBlocked]);
|
||||
|
||||
// TextInput single-line submits on Enter; multiline does not.
|
||||
let fields_doc = fields_surface();
|
||||
let mut tf_host = Host::new(MemState::new(), &fields_doc, MODES[0]);
|
||||
let sub = tf_host.frame(vec![key(Key::Tab), key(Key::Enter)]);
|
||||
assert_eq!(sub.outbound.len(), 1);
|
||||
assert_eq!(sub.outbound[0].command.as_str(), "go");
|
||||
|
||||
let mut multi_doc = fields_surface();
|
||||
if let Node::Box(root) = &mut multi_doc.root
|
||||
&& let Node::TextInput(ti) = &mut root.children[0]
|
||||
{
|
||||
ti.multiline = true;
|
||||
}
|
||||
let mut m_host = Host::new(MemState::new(), &multi_doc, MODES[0]);
|
||||
let m_sub = m_host.frame(vec![key(Key::Tab), key(Key::Enter)]);
|
||||
assert!(m_sub.outbound.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slider_keys_step_page_home_end_snap_clamp_and_busy_block() {
|
||||
let doc = lone_slider(20.0, 120.0, 5.0);
|
||||
let mut host = Host::new(MemState::new(), &doc, MODES[0]);
|
||||
host.frame(vec![key(Key::Tab)]);
|
||||
|
||||
let expect_num = |out: &FrameOutput, val: f64| {
|
||||
assert_eq!(out.outbound.len(), 1);
|
||||
assert_eq!(out.outbound[0].captured[0].value, InputValue::Number(NumberValue { value: val }));
|
||||
};
|
||||
|
||||
// Right: 20 -> 25
|
||||
let o1 = host.frame(vec![key(Key::Right)]);
|
||||
expect_num(&o1, 25.0);
|
||||
|
||||
// Second key while first is busy yields ActivationBlocked and writes no new draft (still 25).
|
||||
let blocked = host.frame(vec![key(Key::Up)]);
|
||||
assert!(blocked.outbound.is_empty());
|
||||
assert_eq!(blocked.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [Code::ActivationBlocked]);
|
||||
complete_latest(&mut host, &o1.outbound[0]);
|
||||
|
||||
// PageUp (+10 steps = +50): 25 -> 75; Up: 75 -> 80; Left: 80 -> 75; Down: 75 -> 70; PageDown (-50): 70 -> 20; Left clamps at 20.
|
||||
for (k, v) in [
|
||||
(Key::PageUp, 75.0),
|
||||
(Key::Up, 80.0),
|
||||
(Key::Left, 75.0),
|
||||
(Key::Down, 70.0),
|
||||
(Key::PageDown, 20.0),
|
||||
(Key::Left, 20.0),
|
||||
(Key::End, 120.0),
|
||||
(Key::Right, 120.0),
|
||||
(Key::Home, 20.0),
|
||||
] {
|
||||
let out = host.frame(vec![key(k)]);
|
||||
expect_num(&out, v);
|
||||
complete_latest(&mut host, &out.outbound[0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_scroll_and_reveal_in_pixels_and_cells() {
|
||||
// 1. f06-scroll-list: scroller with no focusables inside is a stop and takes Down/PageDown/End/Home.
|
||||
for mode in MODES {
|
||||
let fixture = Fixture::F06ScrollList;
|
||||
let mut state = MemState::from_fixture(fixture);
|
||||
state::script(fixture, &mut state);
|
||||
let document = fixture.load().surfaces.remove(0);
|
||||
let mut host = Host::new(state, &document, mode);
|
||||
|
||||
// Before Tab: no focus, Down scrolls nothing.
|
||||
let before = host.frame(vec![]);
|
||||
let no_focus_down = host.frame(vec![key(Key::Down)]);
|
||||
assert_eq!(before.commands, no_focus_down.commands, "{mode:?}");
|
||||
|
||||
// Tab focuses root scroller (only stop), showing its clip ring.
|
||||
let tabbed = host.frame(vec![key(Key::Tab)]);
|
||||
assert_eq!(focus_rings(&tabbed).len(), 1, "{mode:?}");
|
||||
|
||||
// Down scrolls a line.
|
||||
let after_down = host.frame(vec![key(Key::Down)]);
|
||||
assert_ne!(tabbed.commands, after_down.commands, "{mode:?}");
|
||||
|
||||
// End clamps at max; another Down stays identical.
|
||||
let at_end = host.frame(vec![key(Key::End)]);
|
||||
let past_end = host.frame(vec![key(Key::Down)]);
|
||||
assert_eq!(at_end.commands, past_end.commands, "{mode:?}");
|
||||
|
||||
// Home returns to top (same commands as tabbed).
|
||||
let at_home = host.frame(vec![key(Key::Home)]);
|
||||
assert_eq!(at_home.commands, tabbed.commands, "{mode:?}");
|
||||
}
|
||||
|
||||
// 2. Tab to a row scrolled out brings it fully inside by the least offset.
|
||||
for mode in MODES {
|
||||
let document = rows_surface();
|
||||
let rig = placement(feed(20), &document, mode);
|
||||
let pane_rect = rig.rect("pane");
|
||||
let r0 = rig.rect(row_id("item-0000", "row").as_str());
|
||||
let r1 = rig.rect(row_id("item-0001", "row").as_str());
|
||||
let step = r1.y - r0.y;
|
||||
let mut host = Host::new(feed(20), &document, mode);
|
||||
|
||||
// Scroll pane down by 5 rows with wheel, then Tab to row 0 (scrolled out above!).
|
||||
// Reveal must bring row 0 inside pane at offset 0 (least offset).
|
||||
let scrolled = host.frame(vec![InputEvent::Wheel {
|
||||
at: inside(pane_rect),
|
||||
delta: (0.0, step * 5.0),
|
||||
unit: WheelUnit::Units,
|
||||
modifiers: mods(),
|
||||
}]);
|
||||
assert_ne!(scrolled.commands, host.frame(vec![]).commands);
|
||||
|
||||
let revealed = host.frame(vec![key(Key::Tab)]);
|
||||
let rings = focus_rings(&revealed);
|
||||
assert_eq!(rings.len(), 1, "{mode:?}");
|
||||
assert!(rect_approx(rings[0], r0), "{mode:?}: row 0 brought back to top of pane, got {:?}", rings[0]);
|
||||
|
||||
// Now Shift+Tab to "below", then Shift+Tab to row 19 (scrolled out below!):
|
||||
// row 19 must be revealed inside pane's clip (its bottom aligned with pane's bottom).
|
||||
host.frame(vec![shift_tab()]);
|
||||
let last_row = host.frame(vec![shift_tab()]);
|
||||
let ring = focus_rings(&last_row)[0];
|
||||
assert!(
|
||||
ring.y >= pane_rect.y - 1e-3 && ring.y + ring.h <= pane_rect.y + pane_rect.h + 1e-3,
|
||||
"{mode:?}: row 19 ring {:?} inside pane {:?}",
|
||||
ring,
|
||||
pane_rect
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_visible_pointer_tab_and_window_focus() {
|
||||
for mode in MODES {
|
||||
let document = controls_surface();
|
||||
let rig = placement(MemState::new(), &document, mode);
|
||||
let mut host = Host::new(MemState::new(), &document, mode);
|
||||
|
||||
// Pointer down on control "a" focuses it without a ring (visible=false).
|
||||
let a_pt = inside(rig.rect("a"));
|
||||
let clicked = host.frame(vec![down(a_pt), up(a_pt)]);
|
||||
assert_eq!(focus_rings(&clicked), vec![], "{mode:?}");
|
||||
|
||||
// Tab moves from "a" to "b" and shows the focus ring on "b".
|
||||
let tabbed = host.frame(vec![key(Key::Tab)]);
|
||||
let rings = focus_rings(&tabbed);
|
||||
assert_eq!(rings.len(), 1, "{mode:?}");
|
||||
assert!(rect_approx(rings[0], rig.rect("b")), "{mode:?}");
|
||||
|
||||
// Focus(false) hides the ring; Focus(true) shows it again.
|
||||
let lost = host.frame(vec![InputEvent::Focus(false)]);
|
||||
assert_eq!(focus_rings(&lost), vec![], "{mode:?}");
|
||||
let gained = host.frame(vec![InputEvent::Focus(true)]);
|
||||
assert_eq!(focus_rings(&gained).len(), 1, "{mode:?}");
|
||||
assert!(rect_approx(focus_rings(&gained)[0], rig.rect("b")), "{mode:?}");
|
||||
|
||||
// Pointer down on empty space (outside any control) blurs.
|
||||
let blurred = host.frame(vec![down((0.5, 0.5)), up((0.5, 0.5))]);
|
||||
assert_eq!(focus_rings(&blurred), vec![], "{mode:?}");
|
||||
// Next Tab starts at "a" again because focus was cleared.
|
||||
let restarted = host.frame(vec![key(Key::Tab)]);
|
||||
assert!(rect_approx(focus_rings(&restarted)[0], rig.rect("a")), "{mode:?}");
|
||||
}
|
||||
|
||||
// Pointer down on a modal scrim leaves focus intact.
|
||||
let doc = modal_surface();
|
||||
let mut host = Host::new(MemState::new(), &doc, MODES[0]);
|
||||
let before = host.frame(vec![]);
|
||||
assert_eq!(focus_rings(&before).len(), 1);
|
||||
let scrim_hit = host.frame(vec![down((790.0, 590.0)), up((790.0, 590.0))]);
|
||||
assert_eq!(focus_rings(&scrim_hit), focus_rings(&before));
|
||||
|
||||
// Focus(false) cancels an in-progress Slider drag and restores prior draft.
|
||||
let slider_doc = lone_slider(0.0, 100.0, 10.0);
|
||||
let rig = placement(MemState::new(), &slider_doc, MODES[0]);
|
||||
let track = rig.rect("level");
|
||||
let mut s_host = Host::new(MemState::new(), &slider_doc, MODES[0]);
|
||||
s_host.frame(vec![down((track.x + 0.5 * track.w, track.y + 0.5))]);
|
||||
s_host.frame(vec![InputEvent::Focus(false)]);
|
||||
let stray_up = s_host.frame(vec![up((track.x + 0.5 * track.w, track.y + 0.5))]);
|
||||
assert!(stray_up.outbound.is_empty());
|
||||
}
|
||||
|
|
@ -11,7 +11,7 @@ use thing_core::input::Drafts;
|
|||
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::{Placed, RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, balanced, clamp, render};
|
||||
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::*;
|
||||
|
|
@ -1420,6 +1420,10 @@ fn a_pixels_control_draws_its_content_in_logical_px_at_any_scale() {
|
|||
// ---- the session: drafts and node states draw over the bound tree ---------------------------
|
||||
|
||||
fn session_text(fixture: Fixture, drafts: &Drafts, states: &NodeStates) -> (String, Rendered) {
|
||||
session_text_with_focus(fixture, drafts, states, None)
|
||||
}
|
||||
|
||||
fn session_text_with_focus(fixture: Fixture, drafts: &Drafts, states: &NodeStates, focus: Option<FocusView<'_>>) -> (String, Rendered) {
|
||||
let set = fixture.load();
|
||||
let mut state = MemState::from_fixture(fixture);
|
||||
state::script(fixture, &mut state);
|
||||
|
|
@ -1428,7 +1432,7 @@ fn session_text(fixture: Fixture, drafts: &Drafts, states: &NodeStates) -> (Stri
|
|||
let laid = layout(&tree, &frame, &mut *measure(&frame)).unwrap();
|
||||
let theme = Theme::std();
|
||||
let none = ScrollOffsets::default();
|
||||
let input = RenderInput { session: Session::new(drafts, states), ..input(&frame, &none, &theme) };
|
||||
let input = RenderInput { session: Session::new(drafts, states).with_focus(focus), ..input(&frame, &none, &theme) };
|
||||
let rendered = render(&tree, &laid, &input, &mut *measure(&frame));
|
||||
(format!("surface {} viewport 800x600 scale 1 pixels\n{}", set.surfaces[0].record_key(), text_form(&rendered)), rendered)
|
||||
}
|
||||
|
|
@ -1533,3 +1537,24 @@ fn a_denied_mark_draws_one_error_stroke_over_the_marked_node() {
|
|||
});
|
||||
assert_eq!(stroke, Some(button));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_ring_draws_one_stroke_on_f04_and_f05_and_hides_when_not_visible() {
|
||||
let drafts = Drafts::new();
|
||||
let states = NodeStates::default();
|
||||
let enabled = nid("enabled");
|
||||
let (text_f04, drawn_f04) = session_text_with_focus(Fixture::F04Form, &drafts, &states, Some(FocusView { node: &enabled, visible: true }));
|
||||
golden::check(&golden_dir(), "render-f04-form-focus.txt", text_f04.as_bytes());
|
||||
let (_, hidden_f04) = session_text_with_focus(Fixture::F04Form, &drafts, &states, Some(FocusView { node: &enabled, visible: false }));
|
||||
let (_, plain_f04) = session_text(Fixture::F04Form, &drafts, &states);
|
||||
assert_eq!(hidden_f04.commands, plain_f04.commands);
|
||||
assert_ne!(drawn_f04.commands, plain_f04.commands);
|
||||
|
||||
let confirm = nid("confirm");
|
||||
let (text_f05, drawn_f05) = session_text_with_focus(Fixture::F05ModalOverlay, &drafts, &states, Some(FocusView { node: &confirm, visible: true }));
|
||||
golden::check(&golden_dir(), "render-f05-modal-overlay-focus.txt", text_f05.as_bytes());
|
||||
let (_, hidden_f05) = session_text_with_focus(Fixture::F05ModalOverlay, &drafts, &states, Some(FocusView { node: &confirm, visible: false }));
|
||||
let (_, plain_f05) = session_text(Fixture::F05ModalOverlay, &drafts, &states);
|
||||
assert_eq!(hidden_f05.commands, plain_f05.commands);
|
||||
assert_ne!(drawn_f05.commands, plain_f05.commands);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@
|
|||
//!
|
||||
//! cargo run -p thing-tui --example fixture -- f01-swarm-dashboard
|
||||
//!
|
||||
//! Quit with q or Ctrl+C. The loop is the host's, and so is the clock: the host reads the time,
|
||||
//! Quit with Ctrl+Q or Ctrl+C. The loop is the host's, and so is the clock: the host reads the time,
|
||||
//! the terminal size and the terminal's events, lends core its state port and ids, and draws what
|
||||
//! core hands back through `paint`, `diff` and `Terminal`. Core awaits nothing and reads no clock.
|
||||
//! Core routes the pointer: a click on a Button mints its command, a wheel scrolls, a drag on a
|
||||
//! Slider writes its draft. Keys are not routed yet. A resize is read as the next frame's viewport.
|
||||
//! Core routes the pointer and keyboard: a click or key on a Button mints its command, a wheel or
|
||||
//! key scrolls, a drag or key on a Slider writes its draft, Tab moves focus. A resize is read as the next frame's viewport.
|
||||
|
||||
use std::io;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
|
@ -36,8 +36,7 @@ fn now() -> Timestamp {
|
|||
/// The host's own key for leaving; core has no notion of quitting.
|
||||
fn quits(events: &[InputEvent]) -> bool {
|
||||
events.iter().any(|event| match event {
|
||||
InputEvent::Key { key: Key::Char('c'), modifiers, .. } => modifiers.ctrl,
|
||||
InputEvent::Key { key: Key::Char('q'), modifiers, .. } => !modifiers.ctrl && !modifiers.alt,
|
||||
InputEvent::Key { key: Key::Char('c' | 'q'), modifiers, .. } => modifiers.ctrl,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue