From cf31ce7695f6b60df698f80239cd162181d176bc Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Wed, 18 Nov 2026 11:06:42 +0100 Subject: [PATCH] fix(cli-rs): give keys typed as a JS dialog opens to its field A JS plugin's ui.dialog.show runs in a call the host holds input for, but the call's answer only opens the dialog. Its tree and the focus of its field come with the JS host's next revisions. Input typed between the answer and that focus reached no field, so the first key was lost or went to the Home composer (big-boi ds-3). Input now also waits while a plugin's dialog surface that opened less than 500 ms ago is on top and none of its nodes took the focus. It goes on in order once a node of that dialog takes the focus, the dialog's mount ends, or the 500 ms pass. Escape never waits, so it still closes the dialog at once. --- .../plugin/examples/pipe/v2probe/tui.tsx | 7 ++ packages/cli-rs/crates/plugin/src/interact.rs | 35 ++++++++++ packages/cli-rs/crates/plugin/src/pipe/mod.rs | 68 ++++++++++++++++++- .../crates/tui/tests/all/plugin_compat.rs | 21 ++++++ 4 files changed, 129 insertions(+), 2 deletions(-) diff --git a/packages/cli-rs/crates/plugin/examples/pipe/v2probe/tui.tsx b/packages/cli-rs/crates/plugin/examples/pipe/v2probe/tui.tsx index bb240c6b398..db28cdeb002 100644 --- a/packages/cli-rs/crates/plugin/examples/pipe/v2probe/tui.tsx +++ b/packages/cli-rs/crates/plugin/examples/pipe/v2probe/tui.tsx @@ -174,6 +174,13 @@ export default Plugin.define({ run: () => context.ui.dialog.show(() => log({ draft: value })} />), }, + // A key that opens a dialog of its own with a focused field, which the user types into at once (big-boi ds-3). + { + id: "v2probe.ahead", + bind: "f2", + run: () => + context.ui.dialog.show(() => log({ ahead: value })} />), + }, { id: "v2probe.relayer", run: () => context.keymap.layer(() => ({ commands: [{ id: "v2probe.relayered", run() {} }] })) }, { id: "v2probe.color", diff --git a/packages/cli-rs/crates/plugin/src/interact.rs b/packages/cli-rs/crates/plugin/src/interact.rs index 4e9321c62ed..8afc9d84764 100644 --- a/packages/cli-rs/crates/plugin/src/interact.rs +++ b/packages/cli-rs/crates/plugin/src/interact.rs @@ -74,6 +74,11 @@ pub struct Owner { dialog: Cell, /// Brings a widget of the mount's tree into view in the scrolls of the tree that hold it. reveal: RefCell>, + /// What waits for a node of the mount to take the focus, or for the mount to end: input typed while a dialog + /// surface opened goes on then (big-boi ds-3). + focus_waiters: RefCell>>, + /// When a dialog surface's mount began: input waits for its focus only that soon after ([`OPENING`]). + born: Cell>, layers: RefCell>, mode: RefCell>, /// The ids of its tree's nodes, and of its focusable ones. @@ -113,6 +118,9 @@ struct Listener { deliver: Deliver, } +/// How long after a plugin's dialog surface opens the input waits for its field to take the focus, at most. +pub(crate) const OPENING: std::time::Duration = std::time::Duration::from_millis(500); + /// How many events a hold keeps; at the limit it is released, and what it kept goes on in order. pub const HOLD_LIMIT: usize = 256; @@ -283,6 +291,8 @@ impl Owner { composer: Cell::new(false), dialog: Cell::new(false), reveal: RefCell::default(), + focus_waiters: RefCell::default(), + born: Cell::new(None), layers: RefCell::default(), mode: RefCell::default(), ids: RefCell::default(), @@ -307,6 +317,7 @@ impl Owner { /// A dialog surface's mount, before its layers register: they hold in the host dialogs' mode. pub(crate) fn mark_dialog(&self) { self.dialog.set(true); + self.born.set(Some(std::time::Instant::now())); } /// The scope of the surface is the dialog whose body is `view`, while it is on top. @@ -336,6 +347,16 @@ impl Owner { !self.ids.borrow().is_empty() } + /// Runs `then` once a node of the mount takes the focus, or once the mount ends. + pub(crate) fn when_focused(&self, then: Box) { + self.focus_waiters.borrow_mut().push(then); + } + + fn focused_now(&self) { + let waiters = std::mem::take(&mut *self.focus_waiters.borrow_mut()); + waiters.into_iter().for_each(|then| then()); + } + /// Sets what brings a widget of the mount's tree into view ([`Owner::focus`]). pub(crate) fn set_reveal(&self, reveal: Reveal) { *self.reveal.borrow_mut() = Some(reveal); @@ -686,6 +707,7 @@ impl Owner { reveal(id, &widget); } host.reveal(&widget); + self.focused_now(); } // A node the tree does not hold yet waits for the mount's next view, which may show it; one it holds that // takes no focus (a text, a node in a hidden box) is refused. @@ -767,6 +789,7 @@ impl Owner { /// composer as it mounts the route again, and an overlay's close does too. pub(crate) fn end(self: &Rc) { self.alive.set(false); + self.focused_now(); if self.ended.replace(true) { return; } @@ -1118,6 +1141,18 @@ impl Router { self.offered(host) } + /// The mount of a plugin's dialog surface on top, opened less than [`OPENING`] ago, whose nodes have not taken the + /// focus yet: its first tree and focus may still come (the JS host's next revisions). + pub(crate) fn opening(&self, host: &dyn Host) -> Option> { + let owners: Vec> = self.owners.borrow().iter().filter_map(Weak::upgrade).collect(); + owners.into_iter().rev().find(|owner| { + owner.alive() + && owner.born.get().is_some_and(|born| born.elapsed() < OPENING) + && owner.on_top(host) + && owner.focused().node.is_none() + }) + } + /// Whether an overlay has the focus. fn overlaid(&self, host: &dyn Host) -> bool { self.overlays.borrow().iter().any(|shown| focus_within(host.app(), shown.frame.id())) diff --git a/packages/cli-rs/crates/plugin/src/pipe/mod.rs b/packages/cli-rs/crates/plugin/src/pipe/mod.rs index 758e00640a7..12b81f9b295 100644 --- a/packages/cli-rs/crates/plugin/src/pipe/mod.rs +++ b/packages/cli-rs/crates/plugin/src/pipe/mod.rs @@ -801,6 +801,11 @@ struct Hold { input: VecDeque<(Held, Past)>, /// Input put back now, which the intercepts let through. replaying: bool, + /// A plugin's dialog surface just opened and none of its nodes took the focus yet: the input waits for that focus + /// (or the mount's end, or [`crate::interact::OPENING`]), so what the user typed as it opened is its field's + /// (big-boi ds-3). The number tells this wait from an earlier one, and the timer is its deadline. + opening: Option<(u64, TimerId)>, + openings: u64, } /// A call input waits for: its sequence, the key that ran it if a key did (it goes back if the call declines it), and @@ -838,7 +843,7 @@ impl Past { impl Hold { fn holding(&self) -> bool { - !self.owners.is_empty() || self.settling > 0 + !self.owners.is_empty() || self.settling > 0 || self.opening.is_some() } /// Ends owner `seq`, if it still owns its entry, and puts its key back if `put_back`: its deadline, to cancel. @@ -2271,6 +2276,16 @@ impl Scripts { /// [`HELD`] the owners end as at their deadline, and the input goes on after the turn, none of it dropped (cg2-1). fn take(&self, input: Held) -> bool { let mut past = self.past(); + // Input while a plugin's dialog that just opened has not focused its field yet waits for that focus; escape does + // not, as it closes the dialog at once. + let escape = matches!(&input, Held::Key(key) if key.code == opentui::input::KeyCode::Escape); + let opening = { + let hold = self.hold.borrow(); + !escape && !hold.holding() && !hold.replaying + }; + if opening && let Some(host) = self.host.upgrade() { + self.await_opening(&*host, true); + } let mut hold = self.hold.borrow_mut(); if !hold.holding() || hold.replaying { return false; @@ -2310,7 +2325,8 @@ impl Scripts { let timers: Vec = { let mut hold = self.hold.borrow_mut(); hold.input.clear(); - hold.owners.drain(..).filter_map(|owner| owner.timer).collect() + let opening = hold.opening.take().map(|(_, timer)| timer); + hold.owners.drain(..).filter_map(|owner| owner.timer).chain(opening).collect() }; self.cancel(timers); } @@ -2414,6 +2430,9 @@ impl Scripts { /// Puts the held input back in order once nothing holds it. A put-back key that starts a hold keeps the rest held. fn release(&self) { let Some(host) = self.host.upgrade() else { return }; + if self.await_opening(&*host, false) { + return; + } loop { let input = { let mut hold = self.hold.borrow_mut(); @@ -2437,6 +2456,51 @@ impl Scripts { self.hold.borrow_mut().replaying = false; } } + + /// Whether the input waits for a plugin's dialog surface on top to focus its field: one that just opened, whose first + /// tree and focus come with the JS host's next revisions. It goes on once a node of that dialog takes the focus, the + /// dialog's mount ends, or [`crate::interact::OPENING`] passes. `incoming`: input comes now, which the wait takes. + fn await_opening(&self, host: &dyn Host, incoming: bool) -> bool { + { + let hold = self.hold.borrow(); + if hold.holding() || hold.replaying || (hold.input.is_empty() && !incoming) { + return false; + } + } + let Some(owner) = host.router().and_then(|router| router.opening(host)) else { return false }; + let token = { + let mut hold = self.hold.borrow_mut(); + hold.openings += 1; + hold.openings + }; + let timed = self.this.clone(); + let timer = host.app().set_timeout(crate::interact::OPENING, move |_| { + if let Some(scripts) = timed.upgrade() { + scripts.opened(token); + } + }); + self.hold.borrow_mut().opening = Some((token, timer)); + let (focused, owner_host) = (self.this.clone(), self.host.clone()); + owner.when_focused(Box::new(move || { + // After the focus applied, in the order of what the effects did. + if let Some(host) = owner_host.upgrade() { + host.app().defer(move |_| { + if let Some(scripts) = focused.upgrade() { + scripts.opened(token); + } + }); + } + })); + true + } + + /// The wait for an opening dialog `token` ended: the input goes on. + fn opened(&self, token: u64) { + let timer = self.hold.borrow_mut().opening.take_if(|(waiting, _)| *waiting == token); + let Some((_, timer)) = timer else { return }; + self.cancel([timer]); + self.release(); + } } impl InputHold for Scripts { diff --git a/packages/cli-rs/crates/tui/tests/all/plugin_compat.rs b/packages/cli-rs/crates/tui/tests/all/plugin_compat.rs index 41683bad776..0ddaf0e0935 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugin_compat.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugin_compat.rs @@ -2159,3 +2159,24 @@ fn a_dialog_field_keeps_its_draft_across_a_reload() { }); assert_eq!(drafts().last(), Some(&json!("abXcd")), "{:?}", drafts()); } + +// Expected (big-boi ds-3): keys typed right after the key that opens a JS plugin's dialog with a focused field go to that +// field once it has the focus, in order, not to the composer under it and not lost. +#[test] +fn keys_typed_as_a_dialog_opens_go_to_its_field() { + let Some(config) = config() else { return }; + let (pipe, log) = probe(config); + let ahead = || calls(&log).into_iter().filter_map(|call| call.get("ahead").cloned()).collect::>(); + pipe.harness.app.press("f2"); + pipe.harness.app.type_text("ab"); + pipe.harness.app.wait_until(Duration::from_secs(5), || { + pipe.settle(); + ahead().last() == Some(&json!("ab")) + }); + assert_eq!(ahead().last(), Some(&json!("ab")), "{:?}", ahead()); + pipe.harness.tui.dialogs.clear(); + pipe.settle(); + let screen = pipe.harness.app.text(); + let composed = screen.lines().any(|line| line.trim_start_matches([' ', '┃']).starts_with("ab")); + assert!(!composed, "the keys reached the composer:\n{screen}"); +}