diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 4446f4c658..b3323c5ad9 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -42,6 +42,8 @@ pub(crate) trait TextResult { fn tab(&self) -> Option; /// 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; + /// 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 { pub(crate) left_by_tab: Option, pub(crate) tab: Option, pub(crate) caret: Option, + pub(crate) text_lost_focus: bool, } impl TextResult for RecordedText { @@ -70,6 +73,10 @@ impl TextResult for RecordedText { self.caret } + fn text_lost_focus(&self) -> bool { + self.text_lost_focus + } + fn as_any(&self) -> &dyn Any { self } diff --git a/crates/ui-contract/src/contract/cx/edit.rs b/crates/ui-contract/src/contract/cx/edit.rs index 875ac8e818..03b8f146a6 100644 --- a/crates/ui-contract/src/contract/cx/edit.rs +++ b/crates/ui-contract/src/contract/cx/edit.rs @@ -243,6 +243,7 @@ impl Edit for Cx<'_, C> { response.activation_mods = if self.events.is_empty() { craft_keymap::Mods::NONE } else { self.activation().map_or(craft_keymap::Mods::NONE, |a| a.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; diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index 8ce1170bda..76235defe3 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -152,13 +152,15 @@ struct Renaming { draft: String, gesture: GestureId, focused: bool, + /// The field has held the focus: losing it afterwards ends the rename. + held: bool, /// The field opened with a draft the collection proposed that differs from the row's text. proposed: bool, } impl Default for Renaming { fn default() -> Self { - Renaming { key: None, draft: String::new(), gesture: GestureId::default(), focused: false, proposed: false } + Renaming { key: None, draft: String::new(), gesture: GestureId::default(), focused: false, held: false, proposed: false } } } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index f4166d548c..a274babf17 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -678,6 +678,18 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { if self.scrolls && !ui.is_sizing_pass() && !crate::runtime::measure::active(&ctx) { self.follow_anchor(comp, (&ctx, id), &layout, (rect, rtl)); } + // The renamed item left the source (removed, renamed or hidden by the app, or folded away): its editor is gone, so the + // rename ends rather than waiting for the item to return and open the old draft again. + if let Some(key) = self.renaming.key.clone() + && !self.ended_rename + && !ui.is_sizing_pass() + && !crate::runtime::measure::active(&ctx) + && self.index_of(&key).is_none() + { + let before = Rename { key, name: self.renaming.draft.clone() }; + self.events.push(CollectionEvent::Rename(EditEvent::cancel(self.renaming.gesture, CancelReason::Removed, Some(Mixed::Same(before))))); + self.ended_rename = true; + } if self.ended_rename { self.renaming = Renaming::default(); if self.refocus { @@ -956,6 +968,13 @@ impl ItemsHooks<'_, '_, C> { let shifted = editor.submitted && editor.submit_mods.shift; let before = Mixed::Same(Rename { key: key.clone(), name: name.clone() }); let (end, escaped) = rename_input(ctx, &editor, rtl, &mut self.renaming.focused, &mut self.refocus); + // A pass that only measures keeps no focus, so it neither opens nor ends the hold. + let real = !row_ui.is_sizing_pass() && !crate::runtime::measure::active(ctx); + let has_focus = focus::is_focused(ctx, editor.response.id); + // The field lost the focus with nothing typed (a click elsewhere): the text field reports no event for an + // unedited name, so the rename ends here, as it does by Tab and as a typed name does by committing. + let blurred = real && self.renaming.held && !has_focus; + self.renaming.held |= real && has_focus; match end { None if !editor.events.is_empty() => {} None if escaped => { @@ -996,6 +1015,10 @@ impl ItemsHooks<'_, '_, C> { self.events.push(CollectionEvent::Rename(EditEvent::cancel(gesture, CancelReason::Blur, Some(before)))); self.ended_rename = true; } + None if blurred => { + self.events.push(CollectionEvent::Rename(EditEvent::cancel(gesture, CancelReason::Blur, Some(before)))); + self.ended_rename = true; + } _ => {} } if let Some(forward) = editor.left_by_tab.filter(|_| self.ended_rename) { diff --git a/crates/ui-contract/src/contract/items/rename.rs b/crates/ui-contract/src/contract/items/rename.rs index 492487ba51..7ff121b6ef 100644 --- a/crates/ui-contract/src/contract/items/rename.rs +++ b/crates/ui-contract/src/contract/items/rename.rs @@ -17,7 +17,7 @@ impl ItemsHooks<'_, '_, C> { let gesture = crate::runtime::edit::next_gesture_id(&cx.core.ctx); let before = Rename { key: key.clone(), name: draft.clone() }; self.events.push(CollectionEvent::Rename(EditEvent::begin(gesture, Mixed::Same(before), cx.core.label_arc(), None))); - self.renaming = Renaming { key: Some(key), draft, gesture, focused: false, proposed }; + self.renaming = Renaming { key: Some(key), draft, gesture, focused: false, held: false, proposed }; } /// A rename requested from outside (`request_rename`): the lead moves to the item, the item is revealed and its diff --git a/crates/ui-contract/src/contract/steps/value.rs b/crates/ui-contract/src/contract/steps/value.rs index e3e265fb8a..ceb49e352a 100644 --- a/crates/ui-contract/src/contract/steps/value.rs +++ b/crates/ui-contract/src/contract/steps/value.rs @@ -102,6 +102,9 @@ fn resolve_value(comp: &mut dyn ValueSource, stage: &mut MemoryStag // ends here, the first pass it is shown again. let removed = !crate::runtime::memory::shown_last_pass(stage.ctx(), id); if stage.shown::>(slot).is_running() { + // A typing run cut short by the removal is forgotten: its text reached the binding as it was typed, and the value + // from before it may be long stale by the time the component is shown again. + let typing_cut_short = removed && crate::contract::text::run_open(stage, id); // `(given, value)` of a single-valued binding the app owns. let host = comp.binding().and_then(|bind| match bind.get() { Some(Mixed::Same(value)) if !bind.is_kept() => Some((bind.is_given(), value)), @@ -130,8 +133,8 @@ fn resolve_value(comp: &mut dyn ValueSource, stage: &mut MemoryStag gesture.last_given = Some(value.clone()); } if let Some(reason) = reason { - // The document moved under the gesture, so there is nothing to restore. - let before = gesture.before.clone().filter(|_| !reason.document_moved()); + // The document moved under the gesture, so there is nothing to restore; nor for a typing run cut short. + let before = gesture.before.clone().filter(|_| !reason.document_moved() && !typing_cut_short); cancelled = Some(EditEvent::cancel(gesture.id, reason, before)); *gesture = gesture.ended(true); } diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index beae157bcf..eb2926753f 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -36,6 +36,11 @@ pub(crate) fn held_selection(memory: &mut MemoryStage, id: egui::Id) -> Option<( memory.shown::(state_id(id)).held_selection } +/// Whether the text part of the component `id` has a typing run open, as its last pass left it. +pub(crate) fn run_open(memory: &MemoryStage, id: egui::Id) -> bool { + memory.recall::(state_id(id)).start.is_some() +} + /// The draft the text part of the component `id` holds while a typing run is open. pub(crate) fn draft(memory: &mut MemoryStage, id: egui::Id) -> Option { memory.shown::(state_id(id)).draft.clone() @@ -163,14 +168,16 @@ struct Resolved { /// The typing run over the state the adapter recorded this pass, the component's value (`None` while mixed) and /// whether a commit is due. -type Resolve = Box, bool) -> Resolved>; +type Resolve = Box, bool, bool) -> Resolved>; /// Turns what the adapter recorded this pass into the typing run's events: a parsed draft applies in the pass it /// is typed, and a commit proposes and commits in one pass. `fallback` is the value the part shows, the run's start -/// while the component's value is mixed. +/// while the component's value is mixed. The closure's last argument says whether the part keeps its text on Escape +/// this pass: the option alone is not enough, since a part that went read-only or disabled mid-run takes Escape as a +/// plain field does. fn resolver(codec: K, options: &TextOptions, rect: Rect, fallback: K::Value) -> Resolve { let (live, limit, clear_on_escape) = (options.live, options.limit, options.clear_on_escape); - Box::new(move |state, value, commit_now| { + Box::new(move |state, value, commit_now, keep_on_escape| { let value = value.unwrap_or(&fallback); let mut typing = TypingRun::new(codec).live(live); if let Some(limit) = limit { @@ -211,6 +218,15 @@ fn resolver(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() { @@ -401,6 +417,10 @@ struct PreparedText { was_focused: bool, /// The window lost focus in this pass while the text part had it. window_blur: bool, + /// The part's edit menu is open and holds its editing focus. + menu_open: bool, + /// Focus moved from the text part to another part of its component in this pass. + left_for_part: bool, } /// Run the text adapter and adjust focus before the component's typed resolver handles its value. @@ -440,6 +460,8 @@ fn prepare(core: &mut CxCore<'_>, ui: &mut Ui, decl: &TextPart, state: &mut Text let ink = decl.options.ink.map_or(ink, |own| crate::style::ink_color(&crate::runtime::env::Env::of(ui).tokens, own)); let ink = if enabled { ink } else { crate::style::rgba_color(crate::runtime::env::Env::of(ui).tokens.color.text.disabled) }; let held = core.popup(EDIT_MENU).is_open_in(core); + // The text the part shows now: its resting text while it is idle and has one, else the value's own. + let current = decl.options.resting.as_deref().filter(|_| !focused && !held && state.draft.is_none()).unwrap_or(&decl.shown); // A menu bar or a menu the keyboard goes back to the part from has the focus: their Cut and Copy act on the // selection the part keeps for them. Only a part that had the focus last pass, or keeps a selection already, can be // gone back to: asking reads the focus, which a part that never held it has not read, so its replay stays true. @@ -454,14 +476,24 @@ fn prepare(core: &mut CxCore<'_>, ui: &mut Ui, decl: &TextPart, state: &mut Text // caret. let caret_placed = state.preedit.is_none() && adapter::place_caret(&ctx, widget, state.draft.as_deref().unwrap_or(&decl.shown), decl.options.caret); - serve_access(core, state, widget, &decl.shown, read_only); + serve_access(core, state, widget, current, read_only); let select_all = (std::mem::take(&mut state.select_all) || decl.options.select_all) && !crate::runtime::ime::composing(&ctx, widget); if select_all { - let len = state.draft.as_deref().unwrap_or(&decl.shown).chars().count(); + let len = state.draft.as_deref().unwrap_or(current).chars().count(); adapter::select(&ctx, widget, 0, len); } core.surface_slot = Some(ui.painter().add(egui::Shape::Noop)); let menu_held = state.held_selection.is_some(); + // Focus that arrived between passes (a request after the field was drawn, which takes effect at the end of that + // pass) places the caret before this pass's input is applied, so the first text typed replaces a selection. Focus + // back from the edit menu is no arrival. + let arrived_before = focused && !was_focused && !held && !menu_held && core.active_part().is_none(); + // Focus that arrives while a button is down over the field came with a press on it. + let frame = crate::runtime::pointer::frame_raw(&ctx); + let by_pointer = !frame.buttons.is_empty() && frame.pos.is_some_and(|at| core.visible.contains(at)); + if arrived_before { + arrive(&ctx, widget, decl, state, by_pointer, select_all); + } let out = adapter::run( state, adapter::AdapterIn { @@ -508,22 +540,43 @@ fn prepare(core: &mut CxCore<'_>, ui: &mut Ui, decl: &TextPart, state: &mut Text crate::runtime::egui::repaint::request(&ctx); } // A select asked for in the pass that brings focus (`Cx::select_all_text`) is kept, as `select_on_focus` keeps it. - if out.focused && !left_for_part && !was_focused && !back_from_menu { - let len = decl.shown.chars().count(); - // A dialog that opens on this field selects its whole text whatever the codec's caret, so typing replaces it - // (photocraft#15540). - let opened = !decl.options.keep_caret_on_open - && crate::runtime::focus::focused_rec(&ctx) - .and_then(|rec| crate::runtime::focus::origin(&ctx, &rec)) - .is_some_and(|origin| origin == crate::runtime::focus::FocusOrigin::Open); - match if opened || select_all { Caret::All } else { decl.caret } { - Caret::All => adapter::select(&ctx, widget, 0, len), - // A bound caret is where the app put it: focus arriving keeps it. - _ if decl.options.caret.is_some() => {} - _ => adapter::select(&ctx, widget, len, len), + if out.focused && !left_for_part && !was_focused && !back_from_menu && !arrived_before { + arrive(&ctx, widget, decl, state, by_pointer, select_all); + } + if state.select_on_click { + if out.clicked && out.focused { + adapter::select(&ctx, widget, 0, decl.shown.chars().count()); + state.select_on_click = false; + } else if !out.focused || frame.buttons.is_empty() { + // A drag, or a press that ended elsewhere: the pointer's caret or range stays. + state.select_on_click = false; } } - PreparedText { widget, out, read_only, list_open, caret_visible, commit_now, was_focused, window_blur } + PreparedText { widget, out, read_only, list_open, caret_visible, commit_now, was_focused, window_blur, menu_open: held, left_for_part } +} + +/// Places the caret of the text part's widget `widget` as focus arrives on the part: where the codec puts it, or over +/// the whole text for `select_on_focus`, or when a select was asked for (`select_all`). `select_on_focus` is for focus +/// by key or request: focus a pointer press brings (`by_pointer`) keeps the caret or range the pointer makes, and a +/// plain click selects the whole text once it is released (`TextState::select_on_click`). +fn arrive(ctx: &egui::Context, widget: egui::Id, decl: &TextPart, state: &mut TextState, by_pointer: bool, select_all: bool) { + let len = decl.shown.chars().count(); + // A dialog that opens on this field selects its whole text whatever the codec's caret, so typing replaces it + // (photocraft#15540). + let opened = !decl.options.keep_caret_on_open + && crate::runtime::focus::focused_rec(ctx) + .and_then(|rec| crate::runtime::focus::origin(ctx, &rec)) + .is_some_and(|origin| origin == crate::runtime::focus::FocusOrigin::Open); + if by_pointer && decl.options.select_on_focus && !opened && !select_all { + state.select_on_click = true; + return; + } + match if opened || select_all { Caret::All } else { decl.caret } { + Caret::All => adapter::select(ctx, widget, 0, len), + // A bound caret is where the app put it: focus arriving keeps it. + _ if decl.options.caret.is_some() => {} + _ => adapter::select(ctx, widget, len, len), + } } /// Step 8b: runs the text adapter at the part's rect, then the typing run over what it recorded, and applies the @@ -547,9 +600,14 @@ pub(crate) fn run( let (ctx, id) = (cx.core.ctx.clone(), cx.core.id); let state_id = state_id(id); let mut state = std::mem::take(cx.core.memory.shown::(state_id)); + // A part that was not shown last pass lost its focus, and its typing run with it: the run is forgotten (step 4 + // ended its gesture without putting back the value from before it), and the part starts afresh from its value. + if !crate::runtime::memory::shown_last_pass(&ctx, id) { + state = TextState::default(); + } (decl.values.resync)(&mut state, shown_copy(cx).as_ref()); let text = prepare(cx.core, ui, part, &mut state, AdapterSettings { keys, rtl, ink, underline }, step.commit_now); - let PreparedText { widget, out, read_only, list_open, caret_visible, commit_now, was_focused, window_blur } = text; + let PreparedText { widget, out, read_only, list_open, caret_visible, commit_now, was_focused, window_blur, menu_open, left_for_part } = text; if part.options.complete.is_some() { drive_completions(cx, &mut state); } @@ -562,7 +620,14 @@ pub(crate) fn run( state.end = Some(End::Rewrite { refuses: false }); } } - 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; + let resolved = resolve(&mut state, cx.value(), commit_now, keeps_escape); + 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); } @@ -579,7 +644,7 @@ pub(crate) fn run( 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(); @@ -594,7 +659,11 @@ pub(crate) fn run( 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 }))); + // The edit menu holds the part's editing focus while it is open (`was_focused` stays true through it): key focus + // that is with the menu is not lost until the menu is gone and focus is not back. + let text_lost_focus = was_focused && !menu_open && (!out.focused || left_for_part); + 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::(state_id).seen = shown_copy(cx); cx.core.submitted |= resolved.submitted; diff --git a/crates/ui-contract/src/contract/values.rs b/crates/ui-contract/src/contract/values.rs index b735a85fdb..df6c71379f 100644 --- a/crates/ui-contract/src/contract/values.rs +++ b/crates/ui-contract/src/contract/values.rs @@ -646,6 +646,10 @@ pub struct EditResponse { /// 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, + /// 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 @@ -692,6 +696,7 @@ impl EditResponse { submit_mods: craft_keymap::Mods::NONE, activation_mods: craft_keymap::Mods::NONE, left_by_tab: None, + text_lost_focus: false, escaped: false, unparsed: false, validity, @@ -715,6 +720,7 @@ impl EditResponse { submit_mods: craft_keymap::Mods::NONE, activation_mods: craft_keymap::Mods::NONE, left_by_tab: None, + text_lost_focus: false, escaped: false, unparsed: false, validity: Validity::Ok, @@ -756,6 +762,7 @@ impl EditResponse { submit_mods: self.submit_mods, activation_mods: self.activation_mods, left_by_tab: self.left_by_tab, + text_lost_focus: self.text_lost_focus, escaped: self.escaped, unparsed: self.unparsed, validity, diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 92fd681222..a283417256 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -83,6 +83,9 @@ pub(crate) struct TextState { pub change: Option, /// `Cx::select_all_text` asked for the whole text to be selected at the start of the next pass. pub select_all: bool, + /// Focus arrived on a `select_on_focus` part with a pointer press that is still down: the press keeps the caret or + /// range the pointer makes, and its release as a plain click selects the whole text, as an address bar does. + pub select_on_click: bool, /// The selection, `(caret, anchor)`, the text part had when its edit menu, or a menu bar or menu the keyboard goes /// back to it from, took the focus (`AdapterIn::keeps_selection`): egui collapses the selection of a widget without /// focus, and the menu's command acts on it once the focus is back, which reaches the widget the pass after the @@ -460,7 +463,13 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut // The menu closed a pass ago and the focus went elsewhere: nothing comes back to the held selection. state.held_selection = None; } - let mut base = state.draft.clone().or_else(|| state.normalised.take()).unwrap_or_else(|| input.shown.to_owned()); + // An idle part shows its resting text, if it has one; focus (or the edit menu holding it) and any draft show the + // value's own text. A pass that edits an idle part's text (the host replacing its selection, or putting a draft in) + // edits the value's own text, not the resting text drawn in its place. + let edits_idle = input.options.replace_selection.is_some() || state.change.is_some(); + let resting = input.options.resting.as_deref().filter(|_| !input.focused && !input.held && !edits_idle); + let mut base = + state.draft.clone().or_else(|| state.normalised.take()).or_else(|| resting.map(str::to_owned)).unwrap_or_else(|| input.shown.to_owned()); let mut edited = apply(&mut input, state, &mut base, widget); if let Some((range, insert)) = state.completions.take(&base) { let chars = |byte: usize| base.get(..byte).map_or_else(|| base.chars().count(), |head| head.chars().count()); @@ -481,8 +490,11 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut // 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. In any modal dialog - // a draft leaves Escape to the dialog's Cancel, which discards it with the dialog's other edits. + // a draft leaves Escape to the dialog's Cancel, which discards it with the dialog's other edits. 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 closes_dialog = focused_before + && !keep_on_escape && state.preedit.is_none() && !input.options.clear_on_escape && input.intents.untaken(&Intent::Cancel) @@ -497,8 +509,8 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut // With `RootEnv::escape_leaves_fields` a field takes Escape with nothing to revert too, and gives up the focus; // in a dialog that Escape closes, the Escape stays the dialog's. let leaves = !input.options.clear_on_escape && !closes_dialog && crate::runtime::env::Env::of(input.ui).escape_leaves_fields; - let takes_escape = - if input.options.clear_on_escape { !base.is_empty() || state.preedit.is_some() } else { draft_takes || state.preedit.is_some() || leaves }; + 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() || leaves }; 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. diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index da22da7025..c815c535ec 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -67,6 +67,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. @@ -129,6 +133,10 @@ pub struct TextOptions { /// The key that submits a multi-line text: under `Enter`, plain, Cmd and Ctrl+Enter submit and Shift+Enter breaks /// the line. pub submit_key: SubmitKey, + /// The text shown, and exposed as the part's accessible value, instead of the value's own text while the part has + /// neither focus nor a draft (a derived number in parentheses). Focus, and any typing, start from the value's own + /// text: this changes only what an idle part shows, never what the codec formats or parses. + pub resting: Option, } /// Which Enter chord submits a multi-line text. @@ -151,6 +159,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 +184,7 @@ impl Default for TextOptions { holds_drafts: false, whole_paste: None, submit_key: SubmitKey::CommandEnter, + resting: None, } } } diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index e1064759df..6d5f12c4dd 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -115,7 +115,8 @@ pub(crate) struct OsFiles { /// The viewport facts a frame reports: the root window's inner rect when the frame is the root's (`inner`), and its /// focus: a window-focus event also sets the root viewport's focus fact, as a host reports both, and the fact stays -/// until the next such event. Before any event the focus is unknown. +/// until the next such event. Before any event the focus is unknown. The root's input +/// reports the same focus (`RawInput::focused`), a window with focus while it is unknown. fn window_facts( ctx: &Context, events: &[Event], @@ -256,6 +257,7 @@ pub(crate) fn run_frame( } Service::::run(ctx, |resets| resets.input(viewport, &mut events)); let mut viewports = window_facts(ctx, &events, native_pixels_per_point, (viewport == egui::ViewportId::ROOT).then_some(screen)); + let focused = viewport != egui::ViewportId::ROOT || viewports.get(&egui::ViewportId::ROOT).and_then(|info| info.focused).unwrap_or(true); let children = open_children(ctx, viewport); for child in &children { viewports @@ -265,6 +267,7 @@ pub(crate) fn run_frame( screen_rect: Some(screen), time: Some(time), viewport_id: viewport, + focused, events, hovered_files, dropped_files, diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 779684c381..0d543d9b81 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -246,7 +246,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) let content = placed.union(output.response.rect).union(text_rect); super::widgets::note_scroll_region(ui.ctx(), rect.intersect(ui.clip_rect()), content); } - let focused = output.response.has_focus(); + // The widget's key focus, whether or not the window has the system's: switching to another app is no focus move, + // so the typing run, caret and selection carry on (egui's `Response::has_focus` is false while the window is in + // the background). + let focused = ui.memory(|memory| memory.has_focus(id)); let caret = output.cursor_range.map(|range| { let at = output.galley.pos_from_cursor(range.primary); at.translate(output.galley_pos.to_vec2()) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index a75ce8ea63..727aacf990 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -183,6 +183,11 @@ 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, + /// A text widget in a scope that gives focus back to its opener, held one more pass: the scope the Escape closes is + /// closing by the next pass, and its restoration needs the widget to still hold the focus. + surrender_deferred: Option, } fn viewport(ctx: &Context) -> ViewportId { @@ -1019,6 +1024,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) { @@ -1030,6 +1041,34 @@ pub(crate) fn end(ctx: &Context) { { egui_focus::surrender(ctx, id); } + // A field held a pass for the scope it sits in lets go now, unless that scope is going away with focus in the field: + // nav::end below then gives the focus back to the scope's opener from where the field holds it. + if let Some(widget) = with(ctx, |state| state.surrender_deferred.take()) + && !with(ctx, |state| state.restored_focus(Some(widget)).is_some()) + { + egui_focus::surrender(ctx, widget); + } + if let Some(widget) = with(ctx, |state| state.surrender_after_scopes.take()) { + // A field in a scope that restores focus to an opener (a popover, a dialog) may be in the scope its Escape closes, + // which is only closing by the next pass: it is let go then, once the restoration has had its chance. + let restoring = with(ctx, |state| { + let key = state.focused.get(&widget).copied().unwrap_or((widget, None)); + let mut at = state.stops.iter().find(|rec| rec.stop.key() == key).and_then(|rec| rec.scope); + while let Some(id) = at { + let Some(scope) = state.scopes.get(&id).or_else(|| state.last_scopes.get(&id)) else { break }; + if scope.opener.is_some() { + return true; + } + at = scope.parent; + } + false + }); + if restoring { + with(ctx, |state| state.surrender_deferred = Some(widget)); + } else { + 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)) diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 58924165b3..50b6ab11f6 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -611,7 +611,7 @@ impl State { } /// The opener of a scope that went away, or plays its exit, while focus was inside it. - fn restored_focus(&self, focused: Option) -> Option { + pub(super) fn restored_focus(&self, focused: Option) -> Option { let root = focused?; let key = *self.focused.get(&root).unwrap_or(&(root, None)); let inside = self.last_stops.iter().find(|rec| rec.stop.key() == key)?; diff --git a/crates/ui-contract/src/runtime/keys/intents.rs b/crates/ui-contract/src/runtime/keys/intents.rs index a60d21cc5b..925c3123a5 100644 --- a/crates/ui-contract/src/runtime/keys/intents.rs +++ b/crates/ui-contract/src/runtime/keys/intents.rs @@ -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 { diff --git a/crates/ui-contract/src/testing/suite.rs b/crates/ui-contract/src/testing/suite.rs index 037d70f809..58a2b3b1f0 100644 --- a/crates/ui-contract/src/testing/suite.rs +++ b/crates/ui-contract/src/testing/suite.rs @@ -127,6 +127,7 @@ const SHAPES: &[Case] = &[ Case::new("items-click-select", ANY, collection::click_selects_one_row), Case::new("items-type-ahead", ANY, collection::type_ahead_moves_the_lead), Case::new("items-rename", ANY, collection::rename_commits_and_cancels_once), + Case::new("items-rename-blur", ANY, collection::rename_ends_when_the_editor_loses_focus), Case::new("items-reorder", ANY, collection::keyboard_reorder_ends_once), Case::new("items-empty", ANY, collection::empty_collection_shows_no_rows), Case::new("items-virtualisation", ANY, collection::long_collection_builds_rows_within_the_room_only), diff --git a/crates/ui-contract/src/testing/suite/collection.rs b/crates/ui-contract/src/testing/suite/collection.rs index 275f31cd93..e2c43420d4 100644 --- a/crates/ui-contract/src/testing/suite/collection.rs +++ b/crates/ui-contract/src/testing/suite/collection.rs @@ -251,6 +251,37 @@ pub(super) fn rename_commits_and_cancels_once(subject: &Subject) -> Result<(), S Ok(()) } +/// F2 on the first row of a collection that renames, nothing typed, then a click on the second row: the editor lost the +/// focus to the rows, so the rename ends once with a blur cancel and no commit, and the editor closes (a typed name commits +/// by the same loss; an unedited one gave the text field no event to end the rename by). +pub(super) fn rename_ends_when_the_editor_loses_focus(subject: &Subject) -> Result<(), String> { + if !is_items(subject) { + return Ok(()); + } + let rename = |kinds: &[CollectionKind], edit: EditKind| kinds.iter().filter(|kind| **kind == CollectionKind::Rename(edit)).count(); + for story in &subject.stories { + let Some((mut fixture, _, shown)) = with_rows(story, 2) else { continue }; + row_click::click(&mut fixture, &shown[0]); + fixture.take_outputs(); + fixture.key(Key::F2, Modifiers::NONE); + fixture.settle(); + if rename(&events(&mut fixture), EditKind::Begin) == 0 { + continue; + } + row_click::click(&mut fixture, &shown[1]); + fixture.settle(); + let ended = events(&mut fixture); + let name = story.name; + if rename(&ended, EditKind::Cancel) != 1 || rename(&ended, EditKind::Commit) != 0 { + return Err(format!("{name}: a click on another row gave {ended:?}, expected one rename cancel")); + } + if fixture.tree().role_of(fixture.tree().focused_key()) == Some(Role::TEXT_INPUT) { + return Err(format!("{name}: the rename ended and the editor still holds the focus")); + } + } + Ok(()) +} + /// A stacking key on the first row, for a reorderable collection: one end event and no cancel. Cmd+[ moves the row /// toward the back, the end of a vertical order; a horizontal order (a strip) moves it later with Cmd+]. pub(super) fn keyboard_reorder_ends_once(subject: &Subject) -> Result<(), String> { diff --git a/crates/ui-contract/tests/it/collection/rows.rs b/crates/ui-contract/tests/it/collection/rows.rs index 205c1f26a9..46b82811dc 100644 --- a/crates/ui-contract/tests/it/collection/rows.rs +++ b/crates/ui-contract/tests/it/collection/rows.rs @@ -3,7 +3,7 @@ use super::kit::{Count, Dismissed, List, ROW_H, RowOut, Words}; use craft_behavior::{ - CellAt, CellRange, CellSelection, ColumnKey, EditEvent, EditEvents, GestureId, ItemSource, Mixed, PartKey, ScrollPos, Selection, + CancelReason, CellAt, CellRange, CellSelection, ColumnKey, EditEvent, EditEvents, GestureId, ItemSource, Mixed, PartKey, ScrollPos, Selection, SelectionModel as _, Sense, SheetLayout, SpanLayout, keyed, }; use craft_keymap::Mods; @@ -258,6 +258,9 @@ impl Collection for Probe<'_> { None => (enter.get(), Mods::NONE), }; let mut editor = EditResponse::lifted(ui.allocate_rect(label, egui::Sense::hover()), events, None); + // The probe field is no focus stop, so it asks for the focus a real text field keeps: a field that holds the focus + // and then loses it ends the rename. + request(ui.ctx(), FocusTarget::Id(editor.response.id)); editor.submitted = submitted; editor.submit_mods = mods; Some(editor) @@ -741,3 +744,41 @@ fn a_rename_request_runs_the_settled_view_of_its_collection() { let begun = log.events.borrow().iter().any(|event| matches!(event, CollectionEvent::Rename(EditEvent::Begin { .. }))); assert!(begun, "the settled view ran and its collection opened the requested rename"); } + +/// A rename whose item leaves the source (here, the source shrinks past it) ends once with a removed cancel and writes +/// nothing: the draft is not committed, and the rename does not open again with the old draft. +#[trial] +fn a_rename_whose_item_leaves_the_source_ends_with_a_removed_cancel() { + let (log, enter, shrunk) = (Log::new(), Cell::new(false), Cell::new(false)); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + let words = if shrunk.get() { Words::flat(&["a"]) } else { Words::flat(&["a", "b", "c"]) }; + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + let list = Probe::new(SelectMode::Single).id_salt("list").renaming("proposed", &enter); + log.take(list.show_items(ui, &words, &mut |key, _| ProbeRow::new(*key, log))); + }); + }; + frames.idle(3, &mut show); + request_rename(&frames.ctx, log.id(), &1_usize); + frames.idle(3, &mut show); + let ends = |log: &Log| -> Vec<&'static str> { + log.events + .borrow() + .iter() + .filter_map(|event| match event { + CollectionEvent::Rename(EditEvent::Begin { .. }) => Some("begin"), + CollectionEvent::Rename(EditEvent::Commit { .. }) => Some("commit"), + CollectionEvent::Rename(EditEvent::Cancel { reason: CancelReason::Removed, .. }) => Some("removed"), + CollectionEvent::Rename(EditEvent::Cancel { .. }) => Some("cancel"), + _ => None, + }) + .collect() + }; + assert_eq!(ends(log), ["begin"], "the rename is open"); + shrunk.set(true); + frames.idle(3, &mut show); + assert_eq!(ends(log), ["begin", "removed"], "the rename ended once, with a removed cancel and no commit"); + enter.set(true); + frames.idle(3, &mut show); + assert_eq!(ends(log), ["begin", "removed"], "nothing more is written after the item left"); +} diff --git a/crates/ui-contract/tests/it/text/mod.rs b/crates/ui-contract/tests/it/text/mod.rs index c121edcb90..67ebf9abe0 100644 --- a/crates/ui-contract/tests/it/text/mod.rs +++ b/crates/ui-contract/tests/it/text/mod.rs @@ -2,3 +2,4 @@ pub(crate) mod band; pub(crate) mod editor; pub(crate) mod input_cap; pub(crate) mod memo; +pub(crate) mod resting; diff --git a/crates/ui-contract/tests/it/text/resting.rs b/crates/ui-contract/tests/it/text/resting.rs new file mode 100644 index 0000000000..ad2973ce60 --- /dev/null +++ b/crates/ui-contract/tests/it/text/resting.rs @@ -0,0 +1,78 @@ +//! A text part's resting text is drawn while the part is idle; an edit made to an idle part (the host replacing its +//! selection) is made to the value's own text. + +use craft_behavior::{PartKey, PlainText, Sense}; +use craft_ui::contract::{Bind, BindMut, Common, Component, Edit as _, EditResponse, Input, MeasureCx, PartsCx, Role, Show as _}; +use craft_ui::primitives::{TextKey, TextOptions}; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Id, Rect, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +const TEXT: PartKey = PartKey::new("text"); + +/// One text part over a string: it shows `resting` while idle, and `insert` replaces its selection in the pass it is set. +#[derive(craft_ui::contract::Component)] +struct Resting<'a> { + #[common] + common: Common, + value: Bind<'a, String>, + resting: &'static str, + insert: Option<&'static str>, +} + +impl Component for Resting<'_> { + const ROLE: Role = Role::TEXT_INPUT; + const INPUT: Input = Input::Text; + type Style = PlainStyle; + type Output = EditResponse; + + fn style(_: &StyleCx<'_>, _: RestingStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(120.0, 24.0) + } + + fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { + let options = + TextOptions { resting: Some(self.resting.to_owned()), replace_selection: self.insert.map(str::to_owned), ..TextOptions::default() }; + let (shown, rect) = (cx.value().cloned().unwrap_or_default(), cx.content_rect); + cx.text(TextKey::::new(TEXT), rect, &PlainText, &shown, &options); + } + + fn bind(&mut self) -> Option> { + Some(self.value.reborrow()) + } + + fn finish(self, cx: craft_ui::contract::Cx<'_, Self>) -> EditResponse { + cx.edit_response() + } +} + +/// The host replaces the selection of an idle part that shows resting text: the insert goes into the value's own text +/// ("42" and "7" make "427"), not into the resting text drawn in its place ("(42)7"). +#[trial] +fn an_edit_to_an_idle_part_is_made_to_the_value_not_to_its_resting_text() { + let value = Rc::new(RefCell::new(String::from("42"))); + let insert = Rc::new(Cell::new(None)); + let id = Rc::new(Cell::new(Id::NULL)); + let (held, once, seen) = (value.clone(), insert.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut text = held.borrow_mut(); + let out = Resting { common: Common::new(), value: Bind::bound(&mut *text), resting: "(42)", insert: once.take() }.show(ui); + seen.set(out.response.id); + }); + fixture.settle(); + assert_eq!(fixture.tree().value(id.get()), Some("(42)"), "an idle part shows its resting text"); + insert.set(Some("7")); + fixture.settle(); + assert_eq!(*value.borrow(), "427", "the insert went into the value's own text"); +} diff --git a/crates/ui-widgets/src/form/slider_field.rs b/crates/ui-widgets/src/form/slider_field.rs index 4fab8e5a46..9ee3a89690 100644 --- a/crates/ui-widgets/src/form/slider_field.rs +++ b/crates/ui-widgets/src/form/slider_field.rs @@ -105,6 +105,10 @@ pub struct SliderField<'a> { /// a short field and the number, as production's Opacity, not the room it is offered. #[prop] short: bool, + /// The number field selects its whole value when it takes focus, so typing replaces it + /// ([`NumberField::select_on_focus`]): a click on the value selects it, a drag across it keeps the range. + #[prop(flag)] + select_on_focus: bool, /// The number field's width from this pass's measure (its `Proposal::Ideal` call, which runs before `paint`). field_width: f32, /// The field's range alert of this pass, which `finish` reports. @@ -163,6 +167,7 @@ impl<'a> SliderField<'a> { field_sizing: None, marks: None, short: false, + select_on_focus: false, field_width: 0.0, out_of_range: None, } @@ -200,6 +205,7 @@ impl<'a> SliderField<'a> { field_sizing: self.field_sizing, marks: self.marks.clone(), short: self.short, + select_on_focus: self.select_on_focus, } } } @@ -230,6 +236,7 @@ struct Look { field_sizing: Option, marks: Option, short: bool, + select_on_focus: bool, } /// The composite's check, which its children check their values with. @@ -306,6 +313,7 @@ impl Look { Some(decimals) => field.max_decimals(decimals), None => field, }; + let field = if self.select_on_focus { field.select_on_focus() } else { field }; let field = match self.unit_kind { Some(kind) => field.unit_kind(kind), None => field, diff --git a/crates/ui-widgets/src/text/mod.rs b/crates/ui-widgets/src/text/mod.rs index fd6daff8c5..8565cb5da5 100644 --- a/crates/ui-widgets/src/text/mod.rs +++ b/crates/ui-widgets/src/text/mod.rs @@ -124,7 +124,8 @@ fn text_part() -> TextKey { } /// The text field every collection's `rename_editor` and the canvas `Pasteboard`'s page-name rename show over a label: -/// it selects the name on focus, so typing replaces it. +/// it selects the name on focus, so typing replaces it. It caps nothing: the item's name is the app's, and a rename shows +/// and edits all of it. pub fn rename_field<'a>(draft: Bind<'a, String>, name: &str) -> TextField<'a> { - TextField::new(name.to_owned(), draft).select_on_focus() + TextField::new(name.to_owned(), draft).select_on_focus().limit(None::) } diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index 51bdb02b38..c1bd4db826 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -205,6 +205,14 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// several sizes). #[prop] mixed_word: bool, + /// The value is derived, not chosen (an automatic leading that follows the font size). While the field is not in + /// edit it shows the value in parentheses, with its unit inside them ("(87.6 pt)"), and that text is its + /// accessible value; the field draws no separate unit then, as the unit is in the text. Focus starts an edit from + /// the plain number, without parentheses or unit. A committed edit reports the value as usual: it is the host's + /// job to turn this off, as the value is no longer derived. Steppers, presets and the popup slider work as usual. + /// A blank, mixed or named value is shown as it would be without this. + #[prop] + derived: bool, /// The field writes exactly this many decimals, zeros included ("1.00"), when it has no codec of its own. #[prop] fixed_decimals: Option, @@ -297,6 +305,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { snap_typed: false, automatic: false, mixed_word: false, + derived: false, commit_decimals: None, fixed_decimals: None, name_number: None, @@ -334,6 +343,15 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { self } + /// The whole value is selected when the field takes focus, so typing replaces it, as a value field in a photo + /// editor's sliders behaves. Focus by key or request selects it at once; a pointer press keeps the caret or range + /// it makes, and a plain click selects the whole value once it is released, as an address bar does. + #[must_use] + pub fn select_on_focus(mut self) -> Self { + self.options.select_on_focus = true; + self + } + /// Zoom typing: a Tab rewrites the draft and a press on the field's other parts keeps it unapplied. #[must_use] pub(super) fn zoom_typing(mut self) -> Self { @@ -378,15 +396,36 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { !self.status_zoom && self.unit_placement == UnitPlacement::Inside } - /// The unit drawn apart inside the field after the number: the field's own, else the symbol of its unit kind; - /// none when the host draws it after the field or the number's run holds it. - fn shown_unit(&self, units: &Units) -> Option