Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/hypercmd-build/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"]),
];
}
Expand Down Expand Up @@ -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",
))
}
}
Expand Down
38 changes: 30 additions & 8 deletions crates/hypercmd/src/controls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ pub struct Controller {
order: Vec<Node>,
scrolls: ScrollState,
paste_limit: usize,
edit_limit: usize,
}

impl Controller {
Expand All @@ -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<Node> {
self.focus.clone()
Expand Down Expand Up @@ -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)?,
Expand Down Expand Up @@ -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(
Expand All @@ -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(());
Expand All @@ -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(());
Expand Down Expand Up @@ -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
Expand Down
106 changes: 85 additions & 21 deletions crates/hypercmd/src/editor.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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<usize>, 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),
_ => {}
}
Expand All @@ -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(
Expand Down Expand Up @@ -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<usize> {
let start = value[..cursor].rfind('\n').map_or(0, |index| index + 1);
let end = value[cursor..]
Expand Down
1 change: 1 addition & 0 deletions crates/hypercmd/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub enum ErrorKind {
Service,
Disposed,
Limit,
Edit,
Terminal,
}

Expand Down
1 change: 1 addition & 0 deletions crates/hypercmd/src/scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub(crate) struct Scene {
pub faulted: Cell<bool>,
pub requested_focus: RefCell<std::rc::Weak<NodeData>>,
pub route_focus: RefCell<std::rc::Weak<NodeData>>,
pub edit_limit: Cell<Option<usize>>,
}

impl Scene {
Expand Down
16 changes: 13 additions & 3 deletions docs/controls.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading