tfix4-f6: TextEditor claims Escape and reports every session end in TextEditorOutput::ended

This commit is contained in:
aiongg
2026-11-15 21:32:40 +00:00
parent 0b823cd7b0
commit e0633b2164
3 changed files with 79 additions and 23 deletions
+2 -1
View File
@@ -31,6 +31,7 @@ craft-ui = { workspace = true, optional = true }
craft-behavior = { workspace = true, optional = true }
craft-theme = { workspace = true, optional = true }
craft-host = { workspace = true, features = ["ui"], optional = true }
craft-keymap = { workspace = true, optional = true }
serde = { workspace = true }
# `find`: Word's wildcards and regular expressions compile to regex's linear-time engine.
regex = { version = "1.13", optional = true }
@@ -63,7 +64,7 @@ find = ["dep:regex", "dep:regex-syntax"]
spell = ["dep:miniz_oxide"]
# The egui parts: `ui::editor` (canvas text editor on craft-ui's IME composer), `ui::style_panel`,
# `ui::character` and `ui::spelling`.
ui = ["dep:egui", "dep:craft-behavior", "dep:craft-ui", "dep:craft-theme", "dep:craft-host", "dep:serde_json", "spell"]
ui = ["dep:egui", "dep:craft-behavior", "dep:craft-ui", "dep:craft-theme", "dep:craft-host", "dep:craft-keymap", "dep:serde_json", "spell"]
# `ui::character` shows craft-font-manager's font picker (stars, recents, previews, filters)
# instead of a plain family list. Pulls the bundled font indexes; apps that only want the panels
# leave it off.
+46 -19
View File
@@ -34,8 +34,8 @@ use craft_behavior::{
};
use craft_ui::canvas::canvas_space;
use craft_ui::contract::{
Animate as _, Bind, BindMut, CommandSet as _, Commands as _, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Outcome, PaintUi,
PartsCx, Pointer as _, Props as _, Remember as _, Role,
Animate as _, Bind, BindMut, CommandSet as _, Commands as _, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Outcome,
PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role,
};
use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, PaintShape, StrokeWidth};
use craft_ui::runtime::commands::ClipItem;
@@ -49,8 +49,11 @@ pub use commands::TextEditorCommand;
pub use edits::{click_count, click_selection, word_boundary};
use crate::quotes::QuoteStyle;
use craft_keymap::{Chord, Key};
use edits::{Edits, Session, char_slice, fingerprint};
const ESCAPE: Chord = Chord::plain(Key::Escape);
/// The selection: `anchor` stays where it started, `caret` moves. Equal: a caret with nothing selected. Char
/// offsets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
@@ -265,10 +268,20 @@ pub struct TextEditorStyle {
underline: StyleColor,
}
/// How an editing session ended ([`TextEditorOutput::ended`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EditorEnd {
/// The app keeps the text.
Commit,
/// The app undoes the session.
Cancel,
}
/// What the editor did this pass.
#[derive(Debug)]
#[non_exhaustive]
#[must_use = "end the session on the `edit` event's `Commit` and `Cancel`"]
#[must_use = "end the session on `ended`"]
pub struct TextEditorOutput {
/// The editor's response.
pub response: Response,
@@ -276,12 +289,15 @@ pub struct TextEditorOutput {
pub changed: bool,
/// The selection or caret moved.
pub selection_changed: bool,
/// The typing session as one gesture over the selection. The first text change gives `Begin`, later changes
/// `Update`. `Commit` is Cmd+Enter, a primary press on the canvas background, or Esc when Esc commits ([`TextEditor::esc_commits`], Photoshop's Use ESC
/// Key to Commit Text, on by default): the app ends the session, keeps the text and records one undo step.
/// `Cancel` is Cmd+., or Esc when it doesn't commit: the app ends the session and undoes it. A session with no
/// text change gives no `Commit` or `Cancel`. While a composition is open the keys give neither.
/// The text changes of the session as one gesture over the selection. The first text change gives `Begin`, later
/// changes `Update`; the session's end ([`ended`](Self::ended)) commits or cancels the gesture when one runs.
pub edit: EditResponse<TextSelection>,
/// The session ended this pass, whether or not its text changed. `Commit` is Cmd+Enter, a primary press on the
/// canvas background, or Esc when Esc commits ([`TextEditor::esc_commits`], Photoshop's Use ESC Key to Commit
/// Text, on by default): the app ends the session, keeps the text and records one undo step when it changed.
/// `Cancel` is Cmd+., or Esc when it doesn't commit: the app ends the session and undoes it. While a composition
/// is open the keys give neither.
pub ended: Option<EditorEnd>,
/// The Character panel command was pressed: the host shows or hides the panel. Set for the one pass.
pub character_panel: bool,
}
@@ -336,6 +352,7 @@ pub struct TextEditor<'a> {
changed: bool,
selection_changed: bool,
character_panel: bool,
ended: Option<EditorEnd>,
}
impl<'a> TextEditor<'a> {
@@ -350,6 +367,7 @@ impl<'a> TextEditor<'a> {
changed: false,
selection_changed: false,
character_panel: false,
ended: None,
}
.label(label)
.command_scope(TextEditorCommand::SCOPE)
@@ -425,7 +443,8 @@ fn char_at(lines: &[HostLine], pos: TextPos) -> usize {
impl Component for TextEditor<'_> {
const ROLE: Role = Role::MULTILINE_TEXT_INPUT;
const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Editor;
const KEYS: KeyUse = KeyUse::CODE;
/// Escape always ends the session, so the editor keeps it from its row and from the shortcuts while focused.
const KEYS: KeyUse = KeyUse::CODE.with_claims(&[ESCAPE]);
type Style = TextEditorStyle;
type Output = TextEditorOutput;
@@ -516,13 +535,6 @@ impl Component for TextEditor<'_> {
edits.end_composition();
edits.selection = TextSelection { anchor: char_at(&lines, anchor), caret: char_at(&lines, focus) };
}
EditorInput::Cancel if edits.session.preedit.is_none() => {
if edits.esc_commits {
edits.done.commit = true;
} else {
edits.done.cancel = true;
}
}
EditorInput::Edit(EditCommand::SelectAll) => edits.select_all(),
EditorInput::Edit(EditCommand::Copy) => copied = edits.selected_text(),
EditorInput::Edit(EditCommand::Cut) => {
@@ -557,9 +569,16 @@ impl Component for TextEditor<'_> {
edits.done.commit = true;
}
// Commands arrive with the pass's own input: a second pass of the frame takes none, so a commit, a cancel or
// the panel toggle is reported by one pass only. Commit and Cancel wait while a composition is open: the
// chord belongs to the input method then.
// Commands and the claimed Escape arrive with the pass's own input: a second pass of the frame takes none, so
// a commit, a cancel or the panel toggle is reported by one pass only. Commit and Cancel wait while a
// composition is open: the key belongs to the input method then.
if cx.take_claimed(ESCAPE) && edits.session.preedit.is_none() {
if edits.esc_commits {
edits.done.commit = true;
} else {
edits.done.cancel = true;
}
}
let mut character_panel = false;
for command in fired {
match command.along_flow(edits.host.vertical()) {
@@ -605,6 +624,13 @@ impl Component for TextEditor<'_> {
} else if done.cancel {
cx.cancel(CancelReason::Escape);
}
self.ended = if done.commit {
Some(EditorEnd::Commit)
} else if done.cancel {
Some(EditorEnd::Cancel)
} else {
None
};
self.changed = done.changed;
self.selection_changed = selection != before;
self.character_panel = character_panel;
@@ -694,6 +720,7 @@ impl Component for TextEditor<'_> {
selection_changed: self.selection_changed,
edit: cx.edit_response(),
character_panel: self.character_panel,
ended: self.ended,
}
}
}
+31 -3
View File
@@ -7,7 +7,7 @@ use std::rc::Rc;
use craft_behavior::CanvasView;
use craft_behavior::kurbo::Point;
use craft_text::quotes::QuoteStyle;
use craft_text::ui::editor::{CaretLine, EditKind, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection};
use craft_text::ui::editor::{CaretLine, EditKind, EditorEnd, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection};
use craft_ui::canvas::Canvas;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::testing::{Fixture, pointer, trial};
@@ -21,6 +21,8 @@ struct Host {
formats: bool,
/// The formatting keys the editor asked for.
styles: Vec<StyleKey>,
/// The editor is shown with Esc cancelling (`TextEditor::esc_commits(false)`).
esc_cancels: bool,
}
/// The chars of one line.
@@ -88,6 +90,8 @@ struct Session {
selection: Rc<RefCell<TextSelection>>,
commits: Rc<Cell<u32>>,
cancels: Rc<Cell<u32>>,
/// Every session end the editor reported (`TextEditorOutput::ended`).
ends: Rc<RefCell<Vec<EditorEnd>>>,
/// The next pass asks egui for a second pass of its frame.
discard: Rc<Cell<bool>>,
}
@@ -104,6 +108,8 @@ fn session_on(host: Host, quotes: Option<QuoteStyle>, beside: bool) -> Session {
let (commits, cancels, discard) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)), Rc::new(Cell::new(false)));
let (shown_host, shown_selection, shown_commits) = (Rc::clone(&host), Rc::clone(&selection), Rc::clone(&commits));
let (shown_cancels, shown_discard) = (Rc::clone(&cancels), Rc::clone(&discard));
let ends = Rc::new(RefCell::new(Vec::new()));
let shown_ends = Rc::clone(&ends);
let mut other = (Host { text: "xyz".to_owned(), ..Host::default() }, TextSelection::caret_at(0));
let mut fixture = Fixture::new(move |ui| {
if shown_discard.take() {
@@ -115,12 +121,14 @@ fn session_on(host: Host, quotes: Option<QuoteStyle>, beside: bool) -> Session {
let view = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0);
Canvas::new("Document").view(view).show(ui, |ui, body| {
let bounds = Rect::from_min_size(body.rect.min, vec2(200.0, 20.0));
let editor = TextEditor::new("Text", &mut *host, Bind::bound(&mut *selection));
let esc_commits = !host.esc_cancels;
let editor = TextEditor::new("Text", &mut *host, Bind::bound(&mut *selection)).esc_commits(esc_commits);
let output = if let Some(style) = quotes { editor.smart_quotes(style) } else { editor }.show_at(ui, bounds);
let commits = output.edit.events.iter().filter(|event| matches!(event, craft_behavior::EditEvent::Commit { .. })).count() as u32;
shown_commits.set(shown_commits.get() + commits);
let cancels = output.edit.events.iter().filter(|event| matches!(event, craft_behavior::EditEvent::Cancel { .. })).count() as u32;
shown_cancels.set(shown_cancels.get() + cancels);
shown_ends.borrow_mut().extend(output.ended);
if beside {
let (host, selection) = (&mut other.0, &mut other.1);
drop(TextEditor::new("Other", host, Bind::bound(selection)).show_at(ui, bounds.translate(vec2(0.0, 40.0))));
@@ -128,7 +136,7 @@ fn session_on(host: Host, quotes: Option<QuoteStyle>, beside: bool) -> Session {
});
});
fixture.settle();
Session { fixture, host, selection, commits, cancels, discard }
Session { fixture, host, selection, commits, cancels, ends, discard }
}
impl Session {
@@ -263,6 +271,26 @@ fn cmd_period_cancels_the_session_but_not_while_composing() {
assert_eq!(editor.commits.get(), 0, "Cmd+. cancels though Esc commits");
}
/// Escape ends a session with no text change (an untouched placeholder, an empty mask) on the editor itself: it
/// commits or cancels as Esc is set to, and does not first return focus to the canvas. With typed text the session's
/// gesture ends with it.
#[trial]
fn escape_ends_an_untouched_session_and_a_typed_one() {
let mut editor = session("abc", None);
editor.focus();
editor.fixture.key(Key::Escape, Modifiers::NONE).settle();
assert_eq!(*editor.ends.borrow(), [EditorEnd::Commit], "Esc commits an untouched session");
assert_eq!((editor.commits.get(), editor.cancels.get()), (0, 0), "no text changed, so no gesture ends");
let mut editor = session_on(Host { text: "abc".to_owned(), esc_cancels: true, ..Host::default() }, None, false);
editor.focus();
editor.fixture.key(Key::Escape, Modifiers::NONE).settle();
assert_eq!(*editor.ends.borrow(), [EditorEnd::Cancel], "Esc cancels an untouched session where it does not commit");
editor.fixture.type_text("d").key(Key::Escape, Modifiers::NONE).settle();
assert_eq!(*editor.ends.borrow(), [EditorEnd::Cancel, EditorEnd::Cancel], "the focus stayed on the editor");
assert_eq!(editor.cancels.get(), 1, "the typed session's gesture is cancelled");
}
/// In vertical text Alt+Down follows the flow and loosens the tracking; a host that applies no formatting leaves
/// Alt+Up to move the caret a line up.
#[trial]