mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 01:08:38 +00:00
Text fields: keep the text on Escape (keeps_on_escape) and report text_lost_focus
TextField::keeps_on_escape() lets a live filter keep its query: Escape commits an open typing run once, ends editing by letting focus go after the enclosing scopes ran, and leaves the same Escape to the enclosing scope. EditResponse::text_lost_focus reports that the text part lost key focus in the pass, edited or not. Defaults for plain and search fields are unchanged.
This commit is contained in:
@@ -42,6 +42,8 @@ pub(crate) trait TextResult {
|
||||
fn tab(&self) -> Option<bool>;
|
||||
/// The part's caret as a byte offset into its text after the pass; `None` while its widget has no caret.
|
||||
fn caret(&self) -> Option<usize>;
|
||||
/// Whether the part lost key focus this pass, edited or not.
|
||||
fn text_lost_focus(&self) -> bool;
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
}
|
||||
|
||||
@@ -51,6 +53,7 @@ pub(crate) struct RecordedText<V> {
|
||||
pub(crate) left_by_tab: Option<bool>,
|
||||
pub(crate) tab: Option<bool>,
|
||||
pub(crate) caret: Option<usize>,
|
||||
pub(crate) text_lost_focus: bool,
|
||||
}
|
||||
|
||||
impl<V: 'static> TextResult for RecordedText<V> {
|
||||
@@ -70,6 +73,10 @@ impl<V: 'static> TextResult for RecordedText<V> {
|
||||
self.caret
|
||||
}
|
||||
|
||||
fn text_lost_focus(&self) -> bool {
|
||||
self.text_lost_focus
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -241,6 +241,7 @@ impl<C: Component> Edit for Cx<'_, C> {
|
||||
response.submitted = self.core.submitted;
|
||||
response.submit_mods = self.core.texts.as_ref().map_or(craft_keymap::Mods::NONE, |(_, text)| text.submit_mods());
|
||||
response.left_by_tab = self.core.texts.as_ref().and_then(|(_, text)| text.left_by_tab());
|
||||
response.text_lost_focus = self.core.texts.as_ref().is_some_and(|(_, text)| text.text_lost_focus());
|
||||
response.tab = self.core.texts.as_ref().and_then(|(_, text)| text.tab());
|
||||
response.caret = self.core.texts.as_ref().and_then(|(_, text)| text.caret());
|
||||
response.unparsed = self.core.text_invalid;
|
||||
|
||||
@@ -167,6 +167,7 @@ type Resolve<V> = Box<dyn FnOnce(&mut TextState, Option<&V>, bool) -> Resolved<V
|
||||
/// while the component's value is mixed.
|
||||
fn resolver<K: Codec + Clone + 'static>(codec: K, options: &TextOptions, rect: Rect, fallback: K::Value) -> Resolve<K::Value> {
|
||||
let (live, limit, clear_on_escape) = (options.live, options.limit, options.clear_on_escape);
|
||||
let keep_on_escape = options.keep_on_escape && !clear_on_escape;
|
||||
Box::new(move |state, value, commit_now| {
|
||||
let value = value.unwrap_or(&fallback);
|
||||
let mut typing = TypingRun::new(codec).live(live);
|
||||
@@ -208,6 +209,15 @@ fn resolver<K: Codec + Clone + 'static>(codec: K, options: &TextOptions, rect: R
|
||||
events.push(TextEvent::Cancel(CancelReason::Escape));
|
||||
}
|
||||
}
|
||||
Some(End::Escape) if keep_on_escape => {
|
||||
// The text stays: an open run commits once, neither submitted nor cancelled.
|
||||
escaped = true;
|
||||
if let (Ended::Commit(committed), note) = typing.commit_tagged(&mut run) {
|
||||
committed_note = Some(note);
|
||||
state.normalised = Some(typing.codec().normalise(&draft_text, &committed));
|
||||
events.push(TextEvent::Commit(committed));
|
||||
}
|
||||
}
|
||||
Some(End::Escape) => {
|
||||
escaped = true;
|
||||
if clear_on_escape && !run.is_open() {
|
||||
@@ -535,6 +545,17 @@ pub(crate) fn run<C: Component>(
|
||||
}
|
||||
}
|
||||
let resolved = resolve(&mut state, cx.value(), commit_now);
|
||||
let keeps_escape = part.options.keep_on_escape
|
||||
&& !part.options.clear_on_escape
|
||||
&& !read_only
|
||||
&& cx.core.resolved.enabled
|
||||
&& part.options.enabled;
|
||||
if resolved.escaped && keeps_escape && !state.invalid {
|
||||
// The same Escape goes on to the enclosing scope in this pass, which still finds this focused stop; the field
|
||||
// lets focus go once the scopes have run.
|
||||
cx.core.intents.pass_on(craft_behavior::Intent::Cancel);
|
||||
crate::runtime::focus::surrender_after_scopes(&ctx, widget);
|
||||
}
|
||||
if resolved.refused {
|
||||
crate::runtime::frame::refuse(&ctx);
|
||||
}
|
||||
@@ -551,7 +572,7 @@ pub(crate) fn run<C: Component>(
|
||||
cx.core.text_invalid = state.invalid;
|
||||
cx.core.text_unparsed = part.options.unparsed.clone().filter(|_| state.invalid);
|
||||
cx.core.escape_to_list = state.completions.open || list_open;
|
||||
if state.draft.is_some() || (part.options.clear_on_escape && !out.layout.full().is_empty()) {
|
||||
if state.draft.is_some() || (part.options.clear_on_escape && !out.layout.full().is_empty()) || (keeps_escape && out.focused) {
|
||||
keys::hold_escape(&ctx, id);
|
||||
}
|
||||
let completions = state.completions.items.clone();
|
||||
@@ -566,7 +587,9 @@ pub(crate) fn run<C: Component>(
|
||||
outcome.clicked = out.clicked;
|
||||
// The focus service moved focus off the widget with Tab before this pass's widgets ran.
|
||||
let left_by_tab = if was_focused && !out.focused { crate::runtime::focus::tabbed_off(&ctx, widget) } else { None };
|
||||
cx.core.texts = Some((part.key, Box::new(RecordedText { outcome, submit_mods: resolved.submit_mods, left_by_tab, tab: out.tab, caret })));
|
||||
let text_lost_focus = was_focused && !out.focused;
|
||||
cx.core.texts =
|
||||
Some((part.key, Box::new(RecordedText { outcome, submit_mods: resolved.submit_mods, left_by_tab, tab: out.tab, caret, text_lost_focus })));
|
||||
apply_events(cx, resolved.events);
|
||||
cx.core.memory.shown::<TextState>(state_id).seen = shown_copy(cx);
|
||||
cx.core.submitted |= resolved.submitted;
|
||||
|
||||
@@ -635,6 +635,10 @@ pub struct EditResponse<T> {
|
||||
/// Tab (`Some(true)`) or Shift+Tab (`Some(false)`) moved focus off the text part in this pass, which ended its
|
||||
/// edit; a list's rename continues on the next or previous row.
|
||||
pub left_by_tab: Option<bool>,
|
||||
/// The text part lost key focus in this pass, with or without an edit: a click elsewhere, Tab, or an Escape that
|
||||
/// keeps the text (`keep_on_escape`). It decides nothing; `submitted`, `escaped` and `left_by_tab` stay their own
|
||||
/// facts. False for a component with no text part.
|
||||
pub text_lost_focus: bool,
|
||||
/// The edit was abandoned with Escape.
|
||||
pub escaped: bool,
|
||||
/// A text part holds text that does not parse: the value is the last one that did, and a form that commits the
|
||||
@@ -680,6 +684,7 @@ impl<T> EditResponse<T> {
|
||||
submitted: false,
|
||||
submit_mods: craft_keymap::Mods::NONE,
|
||||
left_by_tab: None,
|
||||
text_lost_focus: false,
|
||||
escaped: false,
|
||||
unparsed: false,
|
||||
validity,
|
||||
@@ -702,6 +707,7 @@ impl<T> EditResponse<T> {
|
||||
submitted: false,
|
||||
submit_mods: craft_keymap::Mods::NONE,
|
||||
left_by_tab: None,
|
||||
text_lost_focus: false,
|
||||
escaped: false,
|
||||
unparsed: false,
|
||||
validity: Validity::Ok,
|
||||
@@ -742,6 +748,7 @@ impl<T: Clone> EditResponse<T> {
|
||||
submitted: self.submitted,
|
||||
submit_mods: self.submit_mods,
|
||||
left_by_tab: self.left_by_tab,
|
||||
text_lost_focus: self.text_lost_focus,
|
||||
escaped: self.escaped,
|
||||
unparsed: self.unparsed,
|
||||
validity,
|
||||
|
||||
@@ -471,8 +471,11 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
|
||||
// A clearing field takes Escape while it shows text, with or without a draft, and passes it on once it is empty:
|
||||
// a list open on it (a search box's results) then gets the Escape that finds the field empty and closes.
|
||||
// A draft in a dialog whose Escape closes it does not take the Escape: the one Escape cancels the dialog and
|
||||
// the typing with it (Word, and the old apps). Outside dialogs Escape reverts the draft first.
|
||||
// the typing with it (Word, and the old apps). Outside dialogs Escape reverts the draft first. A field that keeps
|
||||
// its text on Escape takes every Escape while editable and hands it on after committing (`keep_on_escape`).
|
||||
let keep_on_escape = input.options.keep_on_escape && !input.options.clear_on_escape && input.enabled && !input.read_only;
|
||||
let dialog_escape = focused_before
|
||||
&& !keep_on_escape
|
||||
&& state.draft.is_some()
|
||||
&& state.preedit.is_none()
|
||||
&& !input.options.clear_on_escape
|
||||
@@ -483,8 +486,8 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
|
||||
state.end = Some(End::Escape);
|
||||
}
|
||||
let draft_takes = state.draft.is_some() && !dialog_escape;
|
||||
let takes_escape =
|
||||
if input.options.clear_on_escape { !base.is_empty() || state.preedit.is_some() } else { draft_takes || state.preedit.is_some() };
|
||||
let takes_escape = keep_on_escape
|
||||
|| if input.options.clear_on_escape { !base.is_empty() || state.preedit.is_some() } else { draft_takes || state.preedit.is_some() };
|
||||
let list_first = input.list_open && !input.options.clear_on_escape;
|
||||
if focused_before && takes_escape && !state.completions.open && !list_first && input.intents.take(Intent::Cancel) {
|
||||
// Escape over a composition alone ends the composition and leaves the text.
|
||||
|
||||
@@ -64,6 +64,10 @@ pub struct TextOptions {
|
||||
pub live: bool,
|
||||
/// Escape clears the text and commits the empty text while text shows, and goes on to the host once it is empty.
|
||||
pub clear_on_escape: bool,
|
||||
/// Escape keeps the text: an open typing run commits once, editing ends by leaving focus, and the same Escape
|
||||
/// goes on to the enclosing scope. A live filter keeps its query this way. Ignored with `clear_on_escape`, and on a
|
||||
/// disabled or read-only part.
|
||||
pub keep_on_escape: bool,
|
||||
/// Monospace text.
|
||||
pub mono: bool,
|
||||
/// The type role the text is set in; a monospace text takes the mono role's face and size instead.
|
||||
@@ -122,6 +126,7 @@ impl Default for TextOptions {
|
||||
mask: false,
|
||||
live: false,
|
||||
clear_on_escape: false,
|
||||
keep_on_escape: false,
|
||||
mono: false,
|
||||
role: TypeRole::Body,
|
||||
ink: None,
|
||||
|
||||
@@ -175,6 +175,8 @@ pub(crate) struct State {
|
||||
pub(super) arrived: Option<(u64, StopKey, FocusOrigin)>,
|
||||
/// The running pass's begin hook left a Tab to egui (`NavKeys::tab_to_egui`); its end hook takes it.
|
||||
pub(super) tab_to_egui: bool,
|
||||
/// A text widget that gave its Escape on to the enclosing scopes and lets focus go at the end of the pass.
|
||||
surrender_after_scopes: Option<Id>,
|
||||
}
|
||||
|
||||
fn viewport(ctx: &Context) -> ViewportId {
|
||||
@@ -950,6 +952,12 @@ pub(crate) fn begin(ctx: &Context, tab_all_controls: bool, dialog_tab: TabReach)
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases the text widget `widget` at the end of this pass, after the enclosing scopes have had its Escape: a scope
|
||||
/// deciding whether to close still finds the focused stop. No key is replayed and no other widget loses focus.
|
||||
pub(crate) fn surrender_after_scopes(ctx: &Context, widget: Id) {
|
||||
with(ctx, |state| state.surrender_after_scopes = Some(widget));
|
||||
}
|
||||
|
||||
/// The end hook: applies the press's focus move, returns focus to the opener of a scope that went away,
|
||||
/// moves it off a stop that was not registered, and records what the next input hook reads.
|
||||
pub(crate) fn end(ctx: &Context) {
|
||||
@@ -961,6 +969,9 @@ pub(crate) fn end(ctx: &Context) {
|
||||
{
|
||||
egui_focus::surrender(ctx, id);
|
||||
}
|
||||
if let Some(widget) = with(ctx, |state| state.surrender_after_scopes.take()) {
|
||||
egui_focus::surrender(ctx, widget);
|
||||
}
|
||||
let app_widget = |id: Id| {
|
||||
let made = crate::runtime::pointer::made_by_component(ctx, viewport, id);
|
||||
with(ctx, |state| state.app_widget(id, made))
|
||||
|
||||
@@ -70,6 +70,14 @@ impl Intents {
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaves an intent this pass's taker took to the enclosing scope, in the same pass: the next taker gets it. No
|
||||
/// input is queued or copied.
|
||||
pub(crate) fn pass_on(&mut self, intent: Intent) {
|
||||
if let Some((_, taken)) = self.items.iter_mut().find(|(item, taken)| *taken && item.same_kind(&intent)) {
|
||||
*taken = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes an intent equal to `intent` in every field, once per pass: `Intent::delete(false, Granularity::Grapheme)`
|
||||
/// takes Backspace and leaves Delete, which `take` would also take.
|
||||
pub fn take_exact(&mut self, intent: &Intent) -> bool {
|
||||
|
||||
@@ -86,6 +86,16 @@ pub struct TextField<'a, C: Codec + Clone + 'static = PlainText> {
|
||||
}
|
||||
|
||||
impl<'a> TextField<'a, PlainText> {
|
||||
/// Escape keeps the current text and ends editing by leaving focus: a live filter keeps its query. An open typing
|
||||
/// run commits once, without submitting or cancelling, and the same Escape goes on to the enclosing scope. Plain
|
||||
/// fields otherwise restore the run's start and search fields clear; neither default changes.
|
||||
#[must_use]
|
||||
pub fn keeps_on_escape(mut self) -> Self {
|
||||
self.options.keep_on_escape = true;
|
||||
self.options.clear_on_escape = false;
|
||||
self
|
||||
}
|
||||
|
||||
/// A plain text field named `label`.
|
||||
pub fn new(label: impl Into<Label>, value: Bind<'a, String>) -> Self {
|
||||
let mut field = TextField::with_codec(label, value, PlainText);
|
||||
|
||||
@@ -214,3 +214,93 @@ fn a_bound_caret_moves_the_caret_and_follows_it() {
|
||||
fixture.idle(2);
|
||||
assert_eq!(caret.get(), 4, "the user's caret move past the two-byte \"é\" writes its byte offset back");
|
||||
}
|
||||
|
||||
|
||||
/// A field that keeps its text on Escape (`keeps_on_escape`, a live filter's query) commits the typing, lets focus
|
||||
/// go and leaves the same Escape to its enclosing scope; it reports the focus loss as `text_lost_focus`.
|
||||
#[trial]
|
||||
fn a_field_that_keeps_its_text_on_escape_commits_leaves_focus_and_passes_the_escape_on() {
|
||||
let text = Rc::new(RefCell::new(String::new()));
|
||||
let (passed, lost, id) = (Rc::new(Cell::new(0_u32)), Rc::new(Cell::new(false)), Rc::new(Cell::new(Id::NULL)));
|
||||
let (shown, scope_saw, lost_seen, field) = (text.clone(), passed.clone(), lost.clone(), id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut held = shown.borrow_mut();
|
||||
Stack::new().show(ui, |ui, body| {
|
||||
let out = TextField::new("Filter", Bind::bound(&mut *held)).keeps_on_escape().show(ui);
|
||||
field.set(out.response.id);
|
||||
lost_seen.set(lost_seen.get() || out.text_lost_focus);
|
||||
if body.take_cancel() {
|
||||
scope_saw.set(scope_saw.get() + 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.type_text("abc");
|
||||
fixture.idle(2);
|
||||
assert!(!lost.get(), "typing loses no focus");
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.idle(3);
|
||||
assert_eq!(*text.borrow(), "abc", "Escape keeps the typed text");
|
||||
assert_eq!(passed.get(), 1, "the enclosing scope gets the one Escape");
|
||||
assert_ne!(fixture.focused(), Some(id.get()), "the field lets focus go");
|
||||
assert!(lost.get(), "and reports the focus loss");
|
||||
}
|
||||
|
||||
/// Without `keeps_on_escape` a plain field keeps its default: Escape over a typing run restores the text from before
|
||||
/// it and the field takes that Escape; a search field still clears.
|
||||
#[trial]
|
||||
fn without_keeps_on_escape_plain_and_search_fields_keep_their_escape() {
|
||||
let (plain, search) = (Rc::new(RefCell::new(String::from("old"))), Rc::new(RefCell::new(String::new())));
|
||||
let passed = Rc::new(Cell::new(0_u32));
|
||||
let (a, b, scope_saw) = (plain.clone(), search.clone(), passed.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let (mut first, mut second) = (a.borrow_mut(), b.borrow_mut());
|
||||
Stack::new().show(ui, |ui, body| {
|
||||
TextField::new("Plain", Bind::bound(&mut *first)).id_salt("plain").select_on_focus().show(ui);
|
||||
TextField::search("Search", Bind::bound(&mut *second)).id_salt("search").show(ui);
|
||||
if body.take_cancel() {
|
||||
scope_saw.set(scope_saw.get() + 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.type_text("new");
|
||||
fixture.idle(1);
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.idle(2);
|
||||
assert_eq!(*plain.borrow(), "old", "a plain field's Escape restores the text from before the run");
|
||||
assert_eq!(passed.get(), 0, "and the field takes that Escape");
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.idle(1);
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.type_text("q");
|
||||
fixture.idle(1);
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.idle(2);
|
||||
assert_eq!(*search.borrow(), "", "a search field's Escape still clears");
|
||||
}
|
||||
|
||||
/// `text_lost_focus` reports a real focus loss without an edit, and nothing while the field keeps focus.
|
||||
#[trial]
|
||||
fn text_lost_focus_reports_a_focus_loss_without_an_edit() {
|
||||
let (first, second) = (Rc::new(RefCell::new(String::from("one"))), Rc::new(RefCell::new(String::from("two"))));
|
||||
let lost = Rc::new(Cell::new(0_u32));
|
||||
let (a, b, seen) = (first.clone(), second.clone(), lost.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = TextField::new("First", Bind::bound(&mut *a.borrow_mut())).id_salt("first").show(ui);
|
||||
if out.text_lost_focus {
|
||||
seen.set(seen.get() + 1);
|
||||
}
|
||||
TextField::new("Second", Bind::bound(&mut *b.borrow_mut())).id_salt("second").show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.idle(3);
|
||||
assert_eq!(lost.get(), 0, "a focused field reports no loss");
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.idle(3);
|
||||
assert_eq!(lost.get(), 1, "Tab off the unedited field reports one loss");
|
||||
assert_eq!(*first.borrow(), "one", "and edits nothing");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user