ui-contract: a command a key fires carries its event's place, and Cx::editor_steps gives an editor its inputs and its scope's commands in one stream in arrival order

This commit is contained in:
bflatastic
2026-11-23 09:19:36 +07:00
parent 6468047eab
commit 0a33cd9217
8 changed files with 156 additions and 31 deletions
@@ -200,8 +200,9 @@ pub struct CxCore<'a> {
pub(crate) surface_slot: Option<egui::layers::ShapeIdx>,
/// The editor part as step 8b set it up.
pub(crate) editor: Option<crate::contract::editor::EditorInfo>,
/// The editor part's inputs of this pass, until `editor_input` takes them.
pub(crate) editor_inputs: Vec<craft_behavior::EditorInput>,
/// The editor part's inputs of this pass, each with its order among the pass's events, until `editor_input` or
/// `editor_steps` takes them.
pub(crate) editor_inputs: Vec<(crate::contract::editor::Order, craft_behavior::EditorInput)>,
/// The text part's draft is not a value of its codec.
pub(crate) text_invalid: bool,
/// The text part's `TextOptions::unparsed` while its draft does not parse: the refusal the pass reports when the
+36 -7
View File
@@ -7,9 +7,10 @@ use super::cx::{Cx, Edit as _, PartsCx};
use crate::primitives::{EditorPurpose, EditorState, ImeStamp, ImeSurface};
use crate::runtime::access::text::{self as text_access, Line, Run, TextFacts};
use crate::runtime::commands::{self, CommandSet, Commands as _, Fired};
use crate::runtime::egui::{editor as egui_editor, focus as egui_focus};
use crate::runtime::focus::KeyUse;
use crate::runtime::{commands, ime};
use crate::runtime::ime;
use craft_behavior::{EditCommand, EditorInput, PartKey};
use egui::{Rect, Ui};
@@ -20,6 +21,19 @@ pub(crate) struct EditorDecl {
pub purpose: EditorPurpose,
}
/// Where an editor input or a command goes among the pass's events: the event's place, then its kind (IME edits, an
/// AccessKit selection, then keys, texts and the commands keys fired). An input or command of no one event goes last.
pub(crate) type Order = (usize, u8);
/// One step of an editor's pass, in the order of the events it came from ([`Cx::editor_steps`]).
#[derive(Clone, Debug, PartialEq)]
pub enum EditorStep<S> {
/// An input of the editor part.
Input(EditorInput),
/// A command of the component's scope that a key or another source fired.
Command(S, Fired),
}
/// The editor part as step 8b set it up, for `editor_state`.
pub(crate) struct EditorInfo {
pub widget: egui::Id,
@@ -58,12 +72,12 @@ pub(crate) fn run<C: Component>(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe
let widget = ImeSurface::of(id, decl.key).widget();
let focused = egui_editor::show(ui, widget, decl.rect, egui_focus::event_filter(keys.keep, false));
let read_only = cx.core.resolved.read_only || !cx.core.resolved.enabled;
let mut inputs = Vec::new();
let mut inputs: Vec<(Order, EditorInput)> = Vec::new();
if focused {
// Each input goes where its event arrived among the frame's events: an IME edit before the press or text that
// came after it, and keys and texts in their own order. An AccessKit selection comes after the IME edits that
// came before any key, and an intent of no one event (an Escape, a queued edit command) last, as routed.
let mut placed: Vec<((usize, u8), EditorInput)> = Vec::new();
let mut placed: Vec<(Order, EditorInput)> = Vec::new();
placed.extend(ime::take_placed(&ctx, widget, read_only).into_iter().map(|(input, place)| ((place, 0), input)));
while let Some(request) = cx.core.intents.take_access_where(text_access::is_text_request) {
if let Some((anchor, focus)) = text_access::requested_selection(&ctx, id, &request) {
@@ -75,13 +89,13 @@ pub(crate) fn run<C: Component>(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe
}
// A stable sort: inputs of one place keep the order they were taken in.
placed.sort_by_key(|(order, _)| *order);
inputs.extend(placed.into_iter().map(|(_, input)| input));
inputs = placed;
}
if read_only {
inputs.retain(EditorInput::is_read_only_safe);
inputs.retain(|(_, input)| input.is_read_only_safe());
} else {
let (can_undo, can_redo) = ime::editor_history(&ctx, widget);
inputs.retain(|input| {
inputs.retain(|(_, input)| {
let EditorInput::Edit(command @ (EditCommand::Undo | EditCommand::Redo)) = input else { return true };
let can = if *command == EditCommand::Undo { can_undo } else { can_redo };
if !can {
@@ -205,7 +219,22 @@ impl<C: Component> Cx<'_, C> {
/// The editor part's inputs of this pass in the order they arrived; call it in `update`. The editor applies them
/// to its own document.
pub fn editor_input(&mut self) -> impl Iterator<Item = EditorInput> + '_ {
std::mem::take(&mut self.core.editor_inputs).into_iter()
std::mem::take(&mut self.core.editor_inputs).into_iter().map(|(_, input)| input)
}
/// The editor part's inputs of this pass and the commands of set `S` routed to this component, as one stream in the
/// order their events arrived: a command a key fired comes between the inputs typed before and after its chord, so
/// an editor that Cmd+Enter ends applies none of the frame's typing after it. A command of no one key event (a menu
/// pick, the palette) comes last. Call it in `update` in place of `editor_input` and `take_command`.
pub fn editor_steps<S: CommandSet>(&mut self) -> Vec<EditorStep<S>> {
let mut steps: Vec<(Order, EditorStep<S>)> =
std::mem::take(&mut self.core.editor_inputs).into_iter().map(|(order, input)| (order, EditorStep::Input(input))).collect();
while let Some((command, fired)) = self.take_command::<S>() {
steps.push((fired.place.map_or((usize::MAX, 3), |place| (place, 2)), EditorStep::Command(command, fired)));
}
// A stable sort: the steps of one place keep the order they were taken in.
steps.sort_by_key(|(order, _)| *order);
steps.into_iter().map(|(_, step)| step).collect()
}
/// Reports the editor's caret, visible lines, selection and undo state once per pass, from `update` or `paint`.
+1 -1
View File
@@ -5,7 +5,7 @@ mod collection;
mod container;
mod cx;
pub(crate) mod editor;
pub use editor::EditorHandle;
pub use editor::{EditorHandle, EditorStep};
mod entry;
mod faces;
pub(crate) mod footer_slot;
@@ -1875,9 +1875,9 @@ impl Returning {
}
}
/// The release of the momentary or tool command `held`, fired when its key goes up or the window loses focus (the key's
/// release then goes to another window).
fn release_fired(held: Held, mods: craft_keymap::Mods, time: f64) -> Fired {
/// The release of the momentary or tool command `held`, fired when its key goes up at `place` among the pass's events
/// or the window loses focus (the key's release then goes to another window).
fn release_fired(held: Held, mods: craft_keymap::Mods, time: f64, place: Option<usize>) -> Fired {
Fired {
command: held.command,
target: held.target,
@@ -1887,6 +1887,7 @@ fn release_fired(held: Held, mods: craft_keymap::Mods, time: f64) -> Fired {
alt_variant: false,
mods,
time,
place,
}
}
@@ -1995,7 +1996,7 @@ pub(crate) fn begin(ctx: &Context) {
}
// The fired press of `hit`, or `None` when its command is disabled now or blocked by a modal layer an earlier hit of
// the pass opened (kb.C9). A momentary or tool command is kept with its key, whose release fires it again.
let press = |hit: Hit, key: Option<craft_keymap::Key>, time: f64| -> Option<Fired> {
let press = |hit: Hit, key: Option<craft_keymap::Key>, time: f64, place: Option<usize>| -> Option<Fired> {
let (blocked, holds_key) = with(ctx, |board| {
board.def(&hit.command).map_or((false, false), |def| {
(def.modal == ModalRule::Blocked, matches!(def.kind, CommandKind::Momentary | CommandKind::Tool { .. }))
@@ -2026,20 +2027,21 @@ pub(crate) fn begin(ctx: &Context) {
alt_variant: hit.alt_variant,
mods: hit.trigger.chord.mods,
time,
place,
})
};
// Settles a wait by the time of the event that ends it: the hold when the key was down for the delay, else the tap.
let settle = |wait: Option<HoldWait>, time: f64| -> Option<Fired> {
let settle = |wait: Option<HoldWait>, time: f64, place: Option<usize>| -> Option<Fired> {
let wait = wait?;
let hit = if time - wait.since >= wait.delay { Some(wait.hold) } else { wait.tap }?;
press(hit, Some(wait.key), time)
press(hit, Some(wait.key), time, place)
};
let mut fired = Vec::new();
let mut changes = shortcuts.mods.iter().map(|(index, _)| *index).peekable();
for (index, shortcut) in shortcuts.keys.iter().enumerate() {
// A change of Cmd, Ctrl or Alt before this key settles the wait first.
while changes.next_if(|change| *change <= index).is_some() {
fired.extend(settle(wait.take(), now));
fired.extend(settle(wait.take(), now, None));
}
// When the key event arrived: a frame may run it later, and a double press and a hold read the key's own times.
let time = shortcut.at.unwrap_or(now);
@@ -2047,14 +2049,14 @@ pub(crate) fn begin(ctx: &Context) {
match shortcut.phase {
FirePhase::Release => {
if wait.as_ref().is_some_and(|wait| Some(wait.key) == key) {
fired.extend(settle(wait.take(), time));
fired.extend(settle(wait.take(), time, Some(shortcut.place)));
}
let held = with(ctx, |board| key.and_then(|key| board.held.iter().position(|held| held.key == key)).map(|at| board.held.remove(at)));
fired.extend(held.map(|held| release_fired(held, shortcut.input.mods, time)));
fired.extend(held.map(|held| release_fired(held, shortcut.input.mods, time, Some(shortcut.place))));
}
_ => {
// Another key's press settles the wait first: keys act in the order they went down.
fired.extend(settle(wait.take(), time));
fired.extend(settle(wait.take(), time, Some(shortcut.place)));
// A binding whose command is disabled where the press lands (a window command with no floating
// window, a canvas's view command it does not offer) is passed over: the press runs the next binding
// of its chord, in an outer scope, or of its next chord candidate, as if the disabled one were unbound.
@@ -2069,26 +2071,26 @@ pub(crate) fn begin(ctx: &Context) {
let tap = keys.press(&shortcuts.layout, &shortcut.input, typing, Some((&mut matcher, time, &enabled)));
match hold {
Some((key, hold)) => wait = Some(HoldWait { key, hold, since: time, delay, tap, viewport }),
None => fired.extend(tap.and_then(|hit| press(hit, key, time))),
None => fired.extend(tap.and_then(|hit| press(hit, key, time, Some(shortcut.place)))),
}
}
}
}
for _ in changes {
fired.extend(settle(wait.take(), now));
fired.extend(settle(wait.take(), now, None));
}
// The key's release goes to another window: a momentary command ends and a wait drops.
if shortcuts.focus_lost {
wait = None;
let held = with(ctx, |board| std::mem::take(&mut board.held));
fired.extend(held.into_iter().map(|held| release_fired(held, craft_keymap::Mods::NONE, now)));
fired.extend(held.into_iter().map(|held| release_fired(held, craft_keymap::Mods::NONE, now, None)));
}
// The deadline is a time event: only the first pass of a frame, which has elapsed time, fires it.
if let Some(due) = wait.as_ref().map(|wait| wait.since + wait.delay) {
if now < due {
frame::request_repaint_after(ctx, due - now);
} else if frame::running(ctx).is_some_and(|pass| pass.elapsed > 0.0) {
fired.extend(wait.take().and_then(|wait| press(wait.hold, Some(wait.key), now)));
fired.extend(wait.take().and_then(|wait| press(wait.hold, Some(wait.key), now, None)));
}
}
with(ctx, |board| {
@@ -194,13 +194,17 @@ pub struct Fired {
/// The modifiers the firing input carried: a key's chord, a component's activation, the frame's held modifiers for
/// an injected activation. Automation and the palette carry none.
pub mods: craft_keymap::Mods,
/// For a key, the place of its event among the pass's events, which the editor inputs of the pass share, so an
/// editor runs the command between the inputs typed before and after it (`Cx::editor_steps`). `None` for the other
/// sources and for a key whose hold settles by its deadline or a modifier change, or whose window lost focus.
pub place: Option<usize>,
}
impl Fired {
/// `command` fired from `source` in `phase` at the input time `time`, for the app scope (no target), without a group
/// cycle or the Alt variant.
pub fn new(command: CommandRef, source: FireSource, phase: FirePhase, time: f64) -> Fired {
Fired { command, target: None, source, phase, cycle: false, alt_variant: false, time, mods: craft_keymap::Mods::NONE }
Fired { command, target: None, source, phase, cycle: false, alt_variant: false, time, mods: craft_keymap::Mods::NONE, place: None }
}
/// The command with `mods` as the modifiers its firing input carried.
+2
View File
@@ -112,6 +112,8 @@ pub(crate) struct Shortcut {
/// The input time the event arrived at when an earlier frame held it back; `None` for the pass's own input, which
/// arrived at the pass time.
pub(crate) at: Option<f64>,
/// The event's place among the frame's events ([`Batch::place`]), which the editor inputs it comes between share.
pub(crate) place: usize,
}
/// What the intent routing did with one press.
+11 -3
View File
@@ -127,7 +127,7 @@ impl Strip<'_> {
consumed.swap_remove(at);
return false;
}
batch.shortcuts.push(Shortcut { input, phase: FirePhase::Release, press: None, canvas: false, at });
batch.shortcuts.push(Shortcut { input, phase: FirePhase::Release, press: None, canvas: false, at, place: batch.place });
true
}
KeyEvent::Text(text) => {
@@ -176,7 +176,7 @@ impl Strip<'_> {
// A component that reads every chord gets the event as the chord's press, the way the key made it.
self.press(batch, key, &input, false, at);
} else if !sent {
batch.shortcuts.push(Shortcut { input, phase: FirePhase::Press, press: None, canvas: false, at });
batch.shortcuts.push(Shortcut { input, phase: FirePhase::Press, press: None, canvas: false, at, place: batch.place });
}
// The event stands for the chord, so the shortcut path is its only reader: egui does not copy or paste
// on top of the command.
@@ -315,7 +315,14 @@ impl Strip<'_> {
held: Vec::new(),
});
if !repeat {
batch.shortcuts.push(Shortcut { input: *input, phase: FirePhase::Press, press: Some(batch.presses.len() - 1), canvas: true, at });
batch.shortcuts.push(Shortcut {
input: *input,
phase: FirePhase::Press,
press: Some(batch.presses.len() - 1),
canvas: true,
at,
place: batch.place,
});
}
false
}
@@ -380,6 +387,7 @@ impl Strip<'_> {
press: Some(batch.presses.len() - 1),
canvas: false,
at,
place: batch.place,
});
}
true
+82 -3
View File
@@ -1,14 +1,16 @@
//! The editor contract: a component with an editor part receives one ordered input stream, a read-only editor
//! receives only inputs that change no text, and its visible lines become AccessKit run nodes.
//! The editor contract: a component with an editor part receives one ordered input stream, with the commands of its
//! scope that keys fired in their place, a read-only editor receives only inputs that change no text, and its visible
//! lines become AccessKit run nodes.
use craft_behavior::{EditCommand, EditorInput, Granularity, PartKey, Sense, SurroundingUnit, TextPos};
use craft_host::target::ShellInfo;
use craft_ui::contract::{Common, Component, Cx, EditorHandle, PaintUi, PartsCx, Props as _, Role, Show as _};
use craft_ui::contract::{CommandSet, Common, Component, Cx, EditorHandle, EditorStep, PaintUi, PartsCx, Props as _, Role, Show as _};
use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp};
use craft_ui::runtime::InstallSpec;
use craft_ui::runtime::focus::KeyUse;
use craft_ui::runtime::frame::discard_pass;
use craft_ui::style::StyleCx;
use craft_ui::testing::focus::key_release;
use craft_ui::testing::input::key_press;
use craft_ui::testing::pointer::{click, moved, press, release};
use craft_ui::testing::text::ImeSeen;
@@ -878,3 +880,80 @@ fn a_pre_edit_and_a_refused_deletion_in_one_frame_interrupt_the_composition() {
assert_eq!(interrupted, marks, "marks {marks}, split {split}: the composition is interrupted only by an editor that shows marked text");
}
}
/// The commands of an editor's typing scope: Commit on Cmd+Enter, as a type tool ends editing with it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
#[command(prefix = "editorTrial", scope = "trial.editor", typing)]
#[non_exhaustive]
enum EditorCommand {
#[command(label = "Commit", default = "Cmd+Enter")]
Commit,
}
/// An editor that is the instance of `EditorCommand`'s scope and logs the steps of each pass.
#[derive(craft_ui::contract::Component)]
struct Typer<'a> {
#[common]
common: Common,
steps: &'a RefCell<Vec<EditorStep<EditorCommand>>>,
}
impl Component for Typer<'_> {
const ROLE: Role = Role::MULTILINE_TEXT_INPUT;
const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Editor;
const KEYS: KeyUse = KeyUse::CODE;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: TyperStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS
}
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
cx.editor(EDITOR, rect, EditorPurpose::Text);
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let steps = cx.editor_steps::<EditorCommand>();
self.steps.borrow_mut().extend(steps);
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// A command of the editor's scope that a chord fires reaches the editor between the inputs typed before and after
/// the chord in the same frame, so an editor that Cmd+Enter ends applies none of the typing after it. Guards against
/// the editor reading a frame's inputs and its commands as two batches.
#[trial]
fn a_command_a_chord_fires_reaches_its_editor_between_the_typing_around_it() {
let steps = RefCell::new(Vec::new());
let mut show = |ui: &mut egui::Ui| {
let _ = Typer { common: Common::new(), steps: &steps }.label("Type").command_scope(<EditorCommand as CommandSet>::SCOPE).show_at(ui, AT);
};
let mut frames = Frames::new();
frames.idle(3, &mut show);
click(&mut frames, AT.center(), &mut show);
steps.take();
let cmd_enter = [
Event::ModifiersChanged(Modifiers::COMMAND),
key_press(Key::Enter, Modifiers::COMMAND),
key_release(Key::Enter, Modifiers::COMMAND),
Event::ModifiersChanged(Modifiers::NONE),
];
frames.frame([vec![Event::Text("a".into())], cmd_enter.to_vec(), vec![Event::Text("b".into())]].concat(), &mut show);
let steps = steps.take();
assert!(
matches!(
steps.as_slice(),
[EditorStep::Input(EditorInput::Text(a)), EditorStep::Command(EditorCommand::Commit, _), EditorStep::Input(EditorInput::Text(b))]
if &**a == "a" && &**b == "b"
),
"the command sits between the texts its chord came between: {steps:?}"
);
}