From a910ab9e084df3e352e620b422d177fd0f6d75da Mon Sep 17 00:00:00 2001 From: Andres Pirela <60560109+andreespirela@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:43:24 -0400 Subject: [PATCH] Support completion edits in text controls --- crates/hypercmd-build/src/backend.rs | 5 +- crates/hypercmd/src/controls.rs | 38 ++++++++-- crates/hypercmd/src/editor.rs | 106 +++++++++++++++++++++------ crates/hypercmd/src/error.rs | 1 + crates/hypercmd/src/scene.rs | 1 + docs/controls.md | 16 +++- tests/consumer/src/workspace.rs | 95 +++++++++++++++++++++++- tests/consumer/ui/workspace.html | 4 +- 8 files changed, 230 insertions(+), 36 deletions(-) diff --git a/crates/hypercmd-build/src/backend.rs b/crates/hypercmd-build/src/backend.rs index e528bad..a610517 100644 --- a/crates/hypercmd-build/src/backend.rs +++ b/crates/hypercmd-build/src/backend.rs @@ -25,7 +25,7 @@ pub mod profile { pub const EVENTS: &[(&str, &[&str])] = &[ ("*", &["keydown", "scroll", "resize", "focus", "blur"]), ("button", &["click"]), - ("text", &["input"]), + ("text", &["input", "select"]), ("checkbox", &["change"]), ]; } @@ -127,7 +127,8 @@ impl Backend for HypercmdBackend { } else { Err(origin.error( "terminal-v1 rejects this binding/control pair; use click on button, \ - input on a text control, change on checkbox, or keydown/scroll/resize/focus/blur", + input/select on a text control, change on checkbox, \ + or keydown/scroll/resize/focus/blur", )) } } diff --git a/crates/hypercmd/src/controls.rs b/crates/hypercmd/src/controls.rs index 1da08c8..980be8c 100644 --- a/crates/hypercmd/src/controls.rs +++ b/crates/hypercmd/src/controls.rs @@ -75,7 +75,6 @@ pub struct Controller { order: Vec, scrolls: ScrollState, paste_limit: usize, - edit_limit: usize, } impl Controller { @@ -87,12 +86,11 @@ impl Controller { order: Vec::new(), scrolls: ScrollState::default(), paste_limit: PASTE_LIMIT, - edit_limit: EDIT_LIMIT, } } pub fn set_limits(&mut self, paste_bytes: usize, edit_bytes: usize) { self.paste_limit = paste_bytes; - self.edit_limit = edit_bytes; + self.root.0.scene.edit_limit.set(Some(edit_bytes)); } pub fn focus(&self) -> Option { self.focus.clone() @@ -326,7 +324,7 @@ impl Controller { } if let Some(node) = self.focus.as_ref().filter(|node| node.is_editor()) { let value = crate::text::sanitize(&value, node.tag() == "textarea"); - crate::editor::insert(node, &value, self.edit_limit)?; + crate::editor::insert(node, &value)?; } } Input::Click { column, row } => self.click(column, row)?, @@ -406,10 +404,10 @@ impl Controller { if kind == KeyKind::Release { return Ok(()); } - if key == Key::Tab && !modifiers.control && !modifiers.alt && !modifiers.super_key { - return self.tab(modifiers.shift); - } let Some(node) = self.focus.clone().filter(Node::is_interactive) else { + if key == Key::Tab && !modifiers.control && !modifiers.alt && !modifiers.super_key { + return self.tab(modifiers.shift); + } return Ok(()); }; if self.bubble( @@ -424,6 +422,9 @@ impl Controller { { return Ok(()); } + if key == Key::Tab && !modifiers.control && !modifiers.alt { + return self.tab(modifiers.shift); + } if matches!(key, Key::PageUp | Key::PageDown) && !modifiers.control && !modifiers.alt { self.page_viewport_containing(&node, key == Key::PageUp); return Ok(()); @@ -436,7 +437,7 @@ impl Controller { return self.vertical(key == Key::Up); } if node.is_editor() { - return crate::editor::key(&node, key, modifiers, self.edit_limit); + return crate::editor::key(&node, key, modifiers); } if modifiers.control || modifiers.alt { return Ok(()); @@ -551,11 +552,32 @@ impl Controller { if self.focus.as_ref() != Some(&target) || !self.focusable(&target) { return Ok(()); } + if target.is_editor() { + self.place_cursor(&target, column, row)?; + } activate(&target)?; } Ok(()) } + fn place_cursor(&self, node: &Node, column: u16, row: u16) -> Result<(), Error> { + if let Some(entry) = self.presentation.as_ref().and_then(|presentation| { + presentation + .entries + .iter() + .find(|entry| entry.node == *node) + }) { + crate::editor::place_cursor( + node, + ( + usize::from(column.saturating_sub(entry.content.x)), + usize::from(row.saturating_sub(entry.content.y)), + ), + )?; + } + Ok(()) + } + /// Paint the retained draft, selection and cursor into the focused text control. pub fn decorate(&self, presentation: &mut Presentation) { let Some(node) = self diff --git a/crates/hypercmd/src/editor.rs b/crates/hypercmd/src/editor.rs index d3803bc..34a99f5 100644 --- a/crates/hypercmd/src/editor.rs +++ b/crates/hypercmd/src/editor.rs @@ -1,6 +1,6 @@ -use crate::{Error, Key, Modifiers, Node, text}; +use crate::{Error, ErrorKind, Key, Modifiers, Node, text}; use ratatui::{buffer::Buffer, layout::Rect, style::Modifier}; -use std::ops::RangeBounds; +use std::ops::{Range, RangeBounds}; use unicode_segmentation::UnicodeSegmentation; /// Byte offsets refer to extended grapheme boundaries; scroll offsets are terminal cells. @@ -43,33 +43,72 @@ fn next_boundary(value: &str, cursor: usize) -> usize { .unwrap_or(value.len()) } -pub(crate) fn insert(node: &Node, inserted: &str, limit: usize) -> Result<(), Error> { - if !node.is_interactive() || node.attribute("readonly").is_some() { - return Ok(()); +impl Node { + /// Byte bounds must be extended-grapheme boundaries. The caret follows the inserted text. + /// Emits `input`; invalid bounds or exceeding the controller's edit limit + /// leave the draft unchanged. + pub fn replace_range(&self, range: Range, inserted: &str) -> Result<(), Error> { + if !self.is_editor() { + return Err(Error::new( + ErrorKind::Edit, + "text replacement requires a text control", + )); + } + if !self.is_interactive() || self.is_disabled() || self.attribute("readonly").is_some() { + return Ok(()); + } + let mut value = self.value(); + if range.start > range.end + || !boundaries(&value).any(|offset| offset == range.start) + || !boundaries(&value).any(|offset| offset == range.end) + { + return Err(Error::new( + ErrorKind::Edit, + "text replacement bounds must be ordered grapheme boundaries within the draft", + )); + } + let limit = self + .0 + .scene + .edit_limit + .get() + .unwrap_or(crate::controls::EDIT_LIMIT); + if value.len() - range.len() + inserted.len() > limit { + return Err(Error::limit("edited value exceeds configured byte limit")); + } + value.replace_range(range.clone(), inserted); + let mut editor = self.editor(); + editor.cursor = boundary(&value, ..=range.start + inserted.len()); + editor.anchor = None; + self.0.editor.replace(editor); + self.edit(value) } - let mut value = node.value(); - let mut editor = node.clamped_editor(&value); - let selection = editor.selection(); - if value.len() - selection.len() + inserted.len() > limit { - return Err(Error::limit("edited value exceeds configured byte limit")); + + fn select(&self, editor: EditorState) -> Result<(), Error> { + let previous = self.0.editor.replace(editor); + if previous.cursor != editor.cursor || previous.anchor != editor.anchor { + self.0.scene.changed(); + self.dispatch("select")?; + } + Ok(()) } - value.replace_range(selection.clone(), inserted); - editor.cursor = boundary(&value, ..=selection.start + inserted.len()); - editor.anchor = None; - node.0.editor.replace(editor); - node.edit(value) } -pub(crate) fn key(node: &Node, key: Key, modifiers: Modifiers, limit: usize) -> Result<(), Error> { +pub(crate) fn insert(node: &Node, inserted: &str) -> Result<(), Error> { + let selection = node.editor().selection(); + node.replace_range(selection, inserted) +} + +pub(crate) fn key(node: &Node, key: Key, modifiers: Modifiers) -> Result<(), Error> { if modifiers.alt { return Ok(()); } if !modifiers.control { match key { Key::Char(character) if !character.is_control() => { - return insert(node, &character.to_string(), limit); + return insert(node, &character.to_string()); } - Key::Enter if node.tag() == "textarea" => return insert(node, "\n", limit), + Key::Enter if node.tag() == "textarea" => return insert(node, "\n"), Key::Backspace | Key::Delete => return erase(node, key), _ => {} } @@ -87,9 +126,7 @@ pub(crate) fn key(node: &Node, key: Key, modifiers: Modifiers, limit: usize) -> } else { return Ok(()); } - node.0.editor.replace(editor); - node.0.scene.changed(); - Ok(()) + node.select(editor) } fn destination( @@ -139,6 +176,33 @@ fn erase(node: &Node, key: Key) -> Result<(), Error> { node.edit(value) } +pub(crate) fn place_cursor(node: &Node, position: (usize, usize)) -> Result<(), Error> { + let value = node.value(); + let mut editor = node.clamped_editor(&value); + let target = (position.0 + editor.scroll, position.1 + editor.scroll_row); + let mut column = 0; + let mut row = 0; + editor.cursor = value.len(); + editor.anchor = None; + for (index, cluster) in value.grapheme_indices(true) { + if node.tag() == "textarea" && matches!(cluster, "\n" | "\r" | "\r\n") { + if row == target.1 { + editor.cursor = index; + break; + } + row += 1; + column = 0; + continue; + } + column += cluster_width(cluster, column); + if row == target.1 && column > target.0 { + editor.cursor = index; + break; + } + } + node.select(editor) +} + fn line_range(value: &str, cursor: usize) -> std::ops::Range { let start = value[..cursor].rfind('\n').map_or(0, |index| index + 1); let end = value[cursor..] diff --git a/crates/hypercmd/src/error.rs b/crates/hypercmd/src/error.rs index 72aa1ae..25cded5 100644 --- a/crates/hypercmd/src/error.rs +++ b/crates/hypercmd/src/error.rs @@ -12,6 +12,7 @@ pub enum ErrorKind { Service, Disposed, Limit, + Edit, Terminal, } diff --git a/crates/hypercmd/src/scene.rs b/crates/hypercmd/src/scene.rs index a945f8c..066452b 100644 --- a/crates/hypercmd/src/scene.rs +++ b/crates/hypercmd/src/scene.rs @@ -16,6 +16,7 @@ pub(crate) struct Scene { pub faulted: Cell, pub requested_focus: RefCell>, pub route_focus: RefCell>, + pub edit_limit: Cell>, } impl Scene { diff --git a/docs/controls.md b/docs/controls.md index a767af3..3799326 100644 --- a/docs/controls.md +++ b/docs/controls.md @@ -43,10 +43,20 @@ Model writes do not synthesize input/change. Bindings precede authored listeners and each listener runs in one reactive batch. Handlers may return `()` or `Result<(), Error>`; returned errors enter the scene's diagnostic window. Direct events are `click` on buttons, `input` on text controls, `change` on -checkboxes, and `focus`/`blur`. `keydown` and `scroll` visit the focused or +checkboxes, and `focus`/`blur`. Text controls emit `select` when keyboard or +pointer gestures change the caret or selection without editing the draft. +`keydown` and `scroll` visit the focused or hit-tested target followed by its presented ancestors. `event.prevent_default()` -stops ancestor handlers and the default gesture. Tab retains the controller's -focus traversal; key releases do not dispatch `keydown`. +stops ancestor handlers and the default gesture, including Tab focus traversal. +Key releases do not dispatch `keydown`. + +`Node::editor()` exposes the caret and selection as UTF-8 byte offsets at extended +grapheme boundaries. `Node::replace_range(range, text)` replaces that byte range, +clears the selection, and places the caret after the insertion before emitting +`input`. Invalid boundaries and edits exceeding the controller's configured byte +limit return an error without changing the draft. Read-only and disabled controls +ignore replacements. Mouse clicks place the caret using the presented content box +and retained editor scroll offsets. `EventPayload::Input` carries the normalized `Input`, including `Modifiers` (`shift`, `control`, `alt`, `super_key`) and vertical/horizontal scroll deltas. diff --git a/tests/consumer/src/workspace.rs b/tests/consumer/src/workspace.rs index 4c76c5e..1d9d60b 100644 --- a/tests/consumer/src/workspace.rs +++ b/tests/consumer/src/workspace.rs @@ -1,5 +1,8 @@ use fusor::{FromInputs, Signal, signal}; -use hypercmd::{Controller, Event, EventPayload, Input, Key, KeyKind, Modifiers, Scope}; +use hypercmd::{ + Controller, Error, ErrorKind, Event, EventPayload, Input, Key, KeyKind, Modifiers, Scope, +}; +use std::ops::Range; #[derive(FromInputs)] struct Workspace { @@ -9,9 +12,29 @@ struct Workspace { runs: Signal, #[input] size: Signal<(u16, u16)>, + #[input] + selection: Signal, + #[input] + completion: Signal>>, } impl Workspace { + fn complete(&self, event: &Event) -> Result<(), Error> { + let EventPayload::Input(Input::Key { + key: Key::Tab, + modifiers: Modifiers { shift: false, .. }, + .. + }) = event.payload + else { + return Ok(()); + }; + if let Some(range) = self.completion.get() { + event.target.replace_range(range, "café")?; + self.completion.set(None); + event.prevent_default(); + } + Ok(()) + } fn shortcut(&self, event: &Event) { let EventPayload::Input(Input::Key { key, modifiers, .. }) = event.payload else { return; @@ -44,10 +67,14 @@ fn multiline_editor_and_scrollable_workspace_preserve_input_and_focus() { let draft = signal(String::new()); let runs = signal(0); let size = signal((0, 0)); + let selection = signal(usize::MAX); + let completion = signal(None); let scope = hypercmd::mount::(WorkspaceInputs { draft: draft.clone(), runs: runs.clone(), size: size.clone(), + selection: selection.clone(), + completion: completion.clone(), }) .unwrap(); scope.publish(); @@ -81,6 +108,7 @@ fn multiline_editor_and_scrollable_workspace_preserve_input_and_focus() { single_line_draft(&scope, &mut controls); authored_focus_replaces_reverse_video(&scope, &mut controls); link_destinations(&scope, &mut controls, &draft); + editor_completions(&scope, &mut controls, &selection, &completion); assert_eq!(hypercmd::text::ellipsize("東京👩‍💻abcdef", 7), "東京👩‍💻…"); assert_eq!(scope.take_errors().len(), 0); } @@ -272,3 +300,68 @@ fn authored_focus_replaces_reverse_video(scope: &Scope, controls: &mut Controlle assert_eq!(format!("{:?}", cell.modifier), expected); } } + +fn editor_completions( + scope: &Scope, + controls: &mut Controller, + selection: &Signal, + completion: &Signal>>, +) { + let editor = scope.root().find("multiline").unwrap(); + editor.edit("SELECT 東京").unwrap(); + controls.set_focus(&editor).unwrap(); + super::key(controls, Key::End, false); + super::key(controls, Key::Left, false); + assert_eq!(selection.get(), 10); + completion.set(Some(7..13)); + super::key(controls, Key::Tab, false); + assert_eq!(editor.value(), "SELECT café"); + assert_eq!(editor.editor().cursor, 12); + assert_eq!(editor.editor().anchor, None); + assert_eq!(controls.focus(), Some(editor.clone())); + super::key(controls, Key::Tab, false); + assert_eq!(controls.focus(), scope.root().find("viewport")); + rejected_replacements(controls, &editor); + editor_pointer(scope, controls, selection); +} + +fn rejected_replacements(controls: &mut Controller, editor: &hypercmd::Node) { + editor.edit("e\u{301}界").unwrap(); + for range in [1..3, 3..4, 7..7] { + assert_eq!( + editor.replace_range(range, "x").unwrap_err().kind, + ErrorKind::Edit + ); + assert_eq!(editor.value(), "e\u{301}界"); + } + controls.set_limits(100, 6); + assert_eq!( + editor.replace_range(0..0, "x").unwrap_err().kind, + ErrorKind::Limit + ); + assert_eq!(editor.value(), "e\u{301}界"); + editor.replace_range(3..6, "Z").unwrap(); + assert_eq!(editor.value(), "e\u{301}Z"); + assert_eq!(editor.editor().cursor, 4); +} + +fn editor_pointer(scope: &Scope, controls: &mut Controller, selection: &Signal) { + let editor = scope.root().find("multiline").unwrap(); + editor.edit("A\n東京").unwrap(); + controls.set_focus(&editor).unwrap(); + let frame = super::frame(&scope.root(), controls, (40, 16)); + let entry = frame + .entries + .iter() + .find(|entry| entry.node == editor) + .unwrap(); + let click = Input::Click { + column: entry.content.x + 2, + row: entry.content.y + 1, + }; + controls.presented(frame).unwrap(); + controls.handle(click).unwrap(); + assert_eq!(selection.get(), 5); + super::key(controls, Key::Backspace, false); + assert_eq!(editor.value(), "A\n京"); +} diff --git a/tests/consumer/ui/workspace.html b/tests/consumer/ui/workspace.html index eecf5e0..486f3dc 100644 --- a/tests/consumer/ui/workspace.html +++ b/tests/consumer/ui/workspace.html @@ -1,7 +1,9 @@