Merge Thing 2.0 cut 9b-1: keyboard focus, Tab/modal trap, key activations, focus ring (Soul s2)
This commit is contained in:
commit
d396375f50
14 changed files with 1813 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());
|
||||
|
|
|
|||
237
crates/thing-core/src/input/focus.rs
Normal file
237
crates/thing-core/src/input/focus.rs
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
//! 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,
|
||||
order: Vec<NodeId>,
|
||||
/// Laid node ids in scope from the previous reconcile (used to locate a focused node absent from `order`).
|
||||
prev_scope: Vec<NodeId>,
|
||||
/// Active modal trap stack `(trap_root, saved_opener)` from outermost to innermost.
|
||||
traps: Vec<(NodeId, 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,
|
||||
order: Vec::new(),
|
||||
prev_scope: Vec::new(),
|
||||
traps: Vec::new(),
|
||||
reveal: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Focus {
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.node = None;
|
||||
self.visible = false;
|
||||
self.order.clear();
|
||||
self.prev_scope.clear();
|
||||
self.traps.clear();
|
||||
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);
|
||||
}
|
||||
|
||||
fn restore_or_first(&mut self, opener: Option<NodeId>, in_scope: impl Fn(&NodeId) -> bool, force_first: bool) {
|
||||
if let Some(op) = opener.as_ref().filter(|id| in_scope(id)).cloned() {
|
||||
self.set(Some(op), true);
|
||||
} else if opener.is_some() || force_first {
|
||||
let first = self.order.first().cloned();
|
||||
let show = first.is_some();
|
||||
self.set(first, show);
|
||||
} else {
|
||||
self.set(None, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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());
|
||||
self.order = compute_order(tree, laid, &index, floor);
|
||||
|
||||
let in_scope = |id: &NodeId| laid.nodes[floor..].iter().any(|n| &n.id == id);
|
||||
|
||||
match trap {
|
||||
Some(t) => {
|
||||
if let Some(pos) = self.traps.iter().position(|(root, _)| root == &t) {
|
||||
if pos + 1 < self.traps.len() {
|
||||
let opener = self.traps.drain(pos + 1..).next().and_then(|(_, op)| op);
|
||||
self.restore_or_first(opener, in_scope, true);
|
||||
}
|
||||
} else {
|
||||
self.traps.push((t, self.node.take()));
|
||||
let first = self.order.first().cloned();
|
||||
let show = first.is_some();
|
||||
self.set(first, show);
|
||||
}
|
||||
}
|
||||
None if !self.traps.is_empty() => {
|
||||
let opener = self.traps.drain(..).next().and_then(|(_, op)| op);
|
||||
self.restore_or_first(opener, in_scope, false);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
if let Some(current) = self.node.as_ref()
|
||||
&& !in_scope(current)
|
||||
{
|
||||
let fallback = self.prev_scope.iter().position(|id| id == current).and_then(|pos| {
|
||||
self.prev_scope[..pos]
|
||||
.iter()
|
||||
.rev()
|
||||
.chain(self.prev_scope[pos..].iter().skip(1))
|
||||
.find(|id| self.order.contains(id))
|
||||
.cloned()
|
||||
});
|
||||
let show = fallback.is_some();
|
||||
self.set(fallback, show);
|
||||
}
|
||||
|
||||
self.prev_scope = laid.nodes[floor..].iter().map(|n| n.id.clone()).collect();
|
||||
|
||||
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,178 @@ 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"));
|
||||
|
||||
// Non-overflowing Overflow::Scroll box (max_scroll == (0, 0)) is NOT a focus stop.
|
||||
let fit_scroll = surface(
|
||||
column("root", None, Overflow::Visible, vec![column("fit", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("small", 40.0, 20.0)])]),
|
||||
vec![],
|
||||
);
|
||||
let rig = Rig::new(Port::new(), &fit_scroll, MODES[0]);
|
||||
assert!(rig.input.focus().order().is_empty());
|
||||
|
||||
// Horizontal-only empty scroller (max_scroll.0 > 0, max_scroll.1 == 0) IS a focus stop.
|
||||
let horiz_scroll = surface(
|
||||
column("root", None, Overflow::Visible, vec![column("h", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("wide", 400.0, 40.0)])]),
|
||||
vec![],
|
||||
);
|
||||
let rig = Rig::new(Port::new(), &horiz_scroll, MODES[0]);
|
||||
assert_eq!(rig.input.focus().order().iter().map(|id| id.as_str()).collect::<Vec<_>>(), ["h"]);
|
||||
}
|
||||
|
||||
#[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::Bound(Bind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: Some(ProviderId::new(PROVIDER)),
|
||||
schema: SchemaId::new("gamecult.thing.test.flag.v1"),
|
||||
key: RecordKey::new("flag"),
|
||||
}),
|
||||
member: path(&["Enabled"]),
|
||||
format: None,
|
||||
});
|
||||
}
|
||||
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"));
|
||||
|
||||
// Shift+Tab when unfocused lands on the last stop ("c").
|
||||
let mut rig0 = Rig::new(Port::new(), &surface(indented("root", vec![button("a", "go", 160.0, 48.0), button("c", "go", 160.0, 48.0)]), vec![decl("go", &[])]), MODES[0]);
|
||||
rig0.send(tab(true));
|
||||
assert_eq!(rig0.input.focus().node().map(|n| n.as_str()), Some("c"));
|
||||
|
||||
// Next Tab steps from b's laid position forward to c; Shift+Tab from disabled b goes to a.
|
||||
rig.send(tab(false));
|
||||
assert_eq!(rig.input.focus().node().map(|n| n.as_str()), Some("c"));
|
||||
|
||||
put_enabled(&mut rig.state, true);
|
||||
let resolved = resolve(&doc, &rig.state, &Limits::default()).tree.unwrap();
|
||||
let mut binder = Binder::new(Limits::default());
|
||||
binder.bind(resolved, &mut rig.state, &mut rig.ledger);
|
||||
rig.tree = binder.tree(&rig.surface).unwrap().clone();
|
||||
rig.draw();
|
||||
rig.send(tab(true));
|
||||
assert_eq!(rig.input.focus().node().map(|n| n.as_str()), Some("b"));
|
||||
put_enabled(&mut rig.state, false);
|
||||
let resolved = resolve(&doc, &rig.state, &Limits::default()).tree.unwrap();
|
||||
let mut binder = Binder::new(Limits::default());
|
||||
binder.bind(resolved, &mut rig.state, &mut rig.ledger);
|
||||
rig.tree = binder.tree(&rig.surface).unwrap().clone();
|
||||
rig.draw();
|
||||
rig.send(tab(true));
|
||||
assert_eq!(rig.input.focus().node().map(|n| n.as_str()), Some("a"));
|
||||
|
||||
// Disabled first button ("a") wrapping backward on Shift+Tab lands on last ("c").
|
||||
let mut a_disabled = button("a", "go", 160.0, 48.0);
|
||||
if let Node::Button(btn) = &mut a_disabled {
|
||||
btn.enabled = BoolSource::Bound(Bind {
|
||||
source: StateSource::Record(StateRef {
|
||||
provider: Some(ProviderId::new(PROVIDER)),
|
||||
schema: SchemaId::new("gamecult.thing.test.flag.v1"),
|
||||
key: RecordKey::new("flag"),
|
||||
}),
|
||||
member: path(&["Enabled"]),
|
||||
format: None,
|
||||
});
|
||||
}
|
||||
let doc_a = surface(
|
||||
indented("root", vec![a_disabled, button("c", "go", 160.0, 48.0)]),
|
||||
vec![decl("go", &[])],
|
||||
);
|
||||
let mut port_a = Port::new();
|
||||
put_enabled(&mut port_a, true);
|
||||
let mut rig_a = Rig::new(port_a, &doc_a, MODES[0]);
|
||||
rig_a.send(tab(false));
|
||||
assert_eq!(rig_a.input.focus().node().map(|n| n.as_str()), Some("a"));
|
||||
put_enabled(&mut rig_a.state, false);
|
||||
let resolved = resolve(&doc_a, &rig_a.state, &Limits::default()).tree.unwrap();
|
||||
let mut binder = Binder::new(Limits::default());
|
||||
binder.bind(resolved, &mut rig_a.state, &mut rig_a.ledger);
|
||||
rig_a.tree = binder.tree(&rig_a.surface).unwrap().clone();
|
||||
rig_a.draw();
|
||||
rig_a.send(tab(true));
|
||||
assert_eq!(rig_a.input.focus().node().map(|n| n.as_str()), Some("c"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slider_press_ignores_zero_width_track_and_nan_x() {
|
||||
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 zero_doc = surface(column("root", Some((0.0, 40.0)), Overflow::Visible, vec![slider]), vec![decl("set", &["level"])]);
|
||||
let mut zero_rig = Rig::new(Port::new(), &zero_doc, MODES[0]);
|
||||
zero_rig.click((0.0, 5.0));
|
||||
assert!(zero_rig.draft("level").is_none());
|
||||
assert!(zero_rig.minted().is_empty());
|
||||
|
||||
let mut rig = Rig::new(Port::new(), &lone_slider(0.0, 100.0, 10.0), MODES[0]);
|
||||
let y = rig.rect("level").y + 0.5;
|
||||
rig.click((f32::NAN, y));
|
||||
assert!(rig.draft("level").is_none());
|
||||
assert!(rig.minted().is_empty());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
1054
crates/thing-core/tests/keyboard.rs
Normal file
1054
crates/thing-core/tests/keyboard.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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