mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 01:08:38 +00:00
Merge pull request #3212 from storytold/lightcraft-pr/fw-text-fields
Text fields: focus, Escape, typing-run and rename fixes
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
|
||||
}
|
||||
|
||||
@@ -243,6 +243,7 @@ impl<C: Component> 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;
|
||||
|
||||
@@ -152,13 +152,15 @@ struct Renaming<K> {
|
||||
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<K> Default for Renaming<K> {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -678,6 +678,18 @@ impl<C: Collection> ShapeHooks<C> 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<C: Collection> 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<C: Collection> 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) {
|
||||
|
||||
@@ -17,7 +17,7 @@ impl<C: Collection> 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
|
||||
|
||||
@@ -102,6 +102,9 @@ fn resolve_value<V: Value>(comp: &mut dyn ValueSource<V>, 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::<Gesture<V>>(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<V: Value>(comp: &mut dyn ValueSource<V>, 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);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,11 @@ pub(crate) fn held_selection(memory: &mut MemoryStage, id: egui::Id) -> Option<(
|
||||
memory.shown::<TextState>(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::<TextState>(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<String> {
|
||||
memory.shown::<TextState>(state_id(id)).draft.clone()
|
||||
@@ -163,14 +168,16 @@ struct Resolved<V> {
|
||||
|
||||
/// 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<V> = Box<dyn FnOnce(&mut TextState, Option<&V>, bool) -> Resolved<V>>;
|
||||
type Resolve<V> = Box<dyn FnOnce(&mut TextState, Option<&V>, bool, bool) -> Resolved<V>>;
|
||||
|
||||
/// 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<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);
|
||||
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<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() {
|
||||
@@ -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<C: Component>(
|
||||
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::<TextState>(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<C: Component>(
|
||||
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<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();
|
||||
@@ -594,7 +659,11 @@ 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 })));
|
||||
// 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::<TextState>(state_id).seen = shown_copy(cx);
|
||||
cx.core.submitted |= resolved.submitted;
|
||||
|
||||
@@ -646,6 +646,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
|
||||
@@ -692,6 +696,7 @@ impl<T> EditResponse<T> {
|
||||
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<T> EditResponse<T> {
|
||||
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<T: Clone> EditResponse<T> {
|
||||
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,
|
||||
|
||||
@@ -83,6 +83,9 @@ pub(crate) struct TextState {
|
||||
pub change: Option<DraftChange>,
|
||||
/// `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.
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::<ImeResets>::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,
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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<Id>,
|
||||
/// 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<Id>,
|
||||
}
|
||||
|
||||
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))
|
||||
|
||||
@@ -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<Id>) -> Option<StopRec> {
|
||||
pub(super) fn restored_focus(&self, focused: Option<Id>) -> Option<StopRec> {
|
||||
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)?;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String>;
|
||||
|
||||
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::<String>::new(TEXT), rect, &PlainText, &shown, &options);
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, String>> {
|
||||
Some(self.value.reborrow())
|
||||
}
|
||||
|
||||
fn finish(self, cx: craft_ui::contract::Cx<'_, Self>) -> EditResponse<String> {
|
||||
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");
|
||||
}
|
||||
@@ -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<Sizing>,
|
||||
marks: Option<FieldMarks>,
|
||||
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,
|
||||
|
||||
@@ -124,7 +124,8 @@ fn text_part<V>() -> TextKey<V> {
|
||||
}
|
||||
|
||||
/// 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::<usize>)
|
||||
}
|
||||
|
||||
@@ -205,6 +205,14 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option<f64>> {
|
||||
/// 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<usize>,
|
||||
@@ -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<Label> {
|
||||
if !self.unit_inside() || self.look == NumberLook::Inline {
|
||||
/// The unit the field shows with its number: the field's own, else the symbol of its unit kind; none when the host
|
||||
/// draws it after the field.
|
||||
fn unit_label(&self, units: &Units) -> Option<Label> {
|
||||
if !self.unit_inside() {
|
||||
return None;
|
||||
}
|
||||
self.unit.clone().or_else(|| self.unit_kind.map(|kind| units.symbol(kind).into()))
|
||||
}
|
||||
|
||||
/// The unit drawn apart inside the field after the number: [`Self::unit_label`], except where the number's run holds
|
||||
/// it (the inline look) and for a derived value, whose unit is in its parenthesised text.
|
||||
fn shown_unit(&self, units: &Units, value: Option<&V>) -> Option<Label> {
|
||||
if self.look == NumberLook::Inline || self.derives(value) { None } else { self.unit_label(units) }
|
||||
}
|
||||
|
||||
/// Whether `value` is shown as a derived value: the field is `derived` and the value is a number it shows, not a
|
||||
/// blank, a mixed value or a name.
|
||||
fn derives(&self, value: Option<&V>) -> bool {
|
||||
self.derived && !self.shows_blank(value) && value.is_some_and(|value| value.named().is_none() && value.number().is_some())
|
||||
}
|
||||
|
||||
/// `number`, as the field writes it, as a derived value: in parentheses with its unit. The inline look's number
|
||||
/// already carries its unit.
|
||||
fn derived_text(&self, number: &str, units: &Units) -> String {
|
||||
match self.unit_label(units).filter(|_| self.look != NumberLook::Inline) {
|
||||
Some(unit) => format!("({number} {})", unit.as_str()),
|
||||
None => format!("({number})"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text the number's run holds around the number: the status zoom's sign; in the inline look the unit kind's
|
||||
/// unit word, else the field's own unit, against the number when it is one sign ("%", "°") and after a space
|
||||
/// otherwise.
|
||||
@@ -420,7 +459,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
/// The unit drawn this pass. A mixed value shows the dash alone: a unit beside it would claim a measure the
|
||||
/// selection does not have.
|
||||
fn painted_unit(&self, cx: &Cx<'_, Self>) -> Option<Label> {
|
||||
self.shown_unit(&cx.env.units()).filter(|_| cx.value().is_some_and(|value| !non_finite(Some(value))))
|
||||
self.shown_unit(&cx.env.units(), cx.value()).filter(|_| cx.value().is_some_and(|value| !non_finite(Some(value))))
|
||||
}
|
||||
|
||||
/// `stored` in the shown unit.
|
||||
@@ -546,7 +585,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
|
||||
let shared = content_sized(cx);
|
||||
// A mixed field that reads "Mixed" has no number for a unit to follow: the word takes the room.
|
||||
let worded = self.mixed_word && cx.value().is_none();
|
||||
let unit = self.shown_unit(&cx.env.units()).filter(|_| !worded).map(|unit| {
|
||||
let unit = self.shown_unit(&cx.env.units(), cx.value()).filter(|_| !worded).map(|unit| {
|
||||
let unit = Adornment::text(unit, cx.style.unit.role).apart().measured(cx);
|
||||
if shared { unit.in_column(cx.ui.ctx(), &UNITS) } else { unit }
|
||||
});
|
||||
@@ -692,6 +731,9 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
|
||||
let (sample, role) = if no_zoom_value {
|
||||
// Text editors draw their hint in the proportional face.
|
||||
(Cow::Borrowed(BLANK), self.options.role)
|
||||
} else if self.derives(shown) {
|
||||
// A derived value is sized as it shows at rest, in parentheses with its unit.
|
||||
(Cow::Owned(self.derived_text(&codec.sample(shown.unwrap_or(&blank)), &cx.env.units())), self.value_role())
|
||||
} else {
|
||||
(codec.sample(shown.unwrap_or(&blank)), self.value_role())
|
||||
};
|
||||
@@ -757,7 +799,11 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
|
||||
}
|
||||
let names = self.names(|row| cx.env.resolve(&row.label().clone()));
|
||||
let blank = V::blank().unwrap_or_else(|| V::of_number(self.rule().blank()));
|
||||
cx.text(text_part::<V>(), text, &self.ruled(&cx.env, shown.is_none(), names), shown.unwrap_or(&blank), &self.options);
|
||||
let ruled = self.ruled(&cx.env, shown.is_none(), names);
|
||||
// A derived value shows in parentheses until the field is edited; the text part keeps the plain number for the
|
||||
// edit to start from.
|
||||
self.options.resting = shown.filter(|value| self.derives(Some(*value))).map(|value| self.derived_text(&ruled.format(value), &cx.env.units()));
|
||||
cx.text(text_part::<V>(), text, &ruled, shown.unwrap_or(&blank), &self.options);
|
||||
let slider_reason =
|
||||
if self.presets.is_some() { "Alt+Down opens the presets list; the slider opens by pointer" } else { "Alt+Down opens the slider" };
|
||||
let chevron_rects = &placed.trailing[placed.trailing.len() - chevrons.len()..];
|
||||
|
||||
@@ -73,6 +73,9 @@ fn number_field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
.size(size)
|
||||
.show(ui);
|
||||
});
|
||||
row("Derived").show(ui, |ui, _| {
|
||||
NumberField::new("Leading", data.bind("derived", Some(SIZE))).unit_kind(UnitKind::Points).derived(true).size(size).show(ui);
|
||||
});
|
||||
row("Invalid").show(ui, |ui, _| {
|
||||
NumberField::new("Columns", data.bind("invalid", Some(7.0)).check(refuse_all)).range(COLUMNS).size(size).show(ui);
|
||||
});
|
||||
@@ -110,6 +113,12 @@ fn number_field_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
NumberField::new("Size", data.bind_mixed("mixed", Mixed::<Option<f64>>::Mixed)).show(ui).edit.into()
|
||||
}
|
||||
|
||||
/// A value that follows from other settings (an automatic leading) reads in parentheses, with its unit, until it is edited.
|
||||
#[story(NumberField<'static>, covers = [], drive = Drive::Never)]
|
||||
fn number_field_derived(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
NumberField::new("Leading", data.bind("derived", Some(SIZE))).unit_kind(UnitKind::Points).derived(true).show(ui).edit.into()
|
||||
}
|
||||
|
||||
#[story(NumberField<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn number_field_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
NumberField::new("Size", data.bind("invalid", Some(7.0)).check(refuse_all)).range(COLUMNS).show(ui).edit.into()
|
||||
|
||||
@@ -90,6 +90,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);
|
||||
|
||||
@@ -114,6 +114,29 @@ fn a_rename_draft_opens_the_field_with_it_and_without_one_the_field_holds_the_na
|
||||
assert_eq!(opened_with(empty_for_first, 1).as_deref(), Some(NAMES[1]), "a row without a draft opens with its name");
|
||||
}
|
||||
|
||||
/// The rename field caps no name length: a name typed past the text field's usual 1,024 characters is kept whole, and
|
||||
/// Enter commits all of it.
|
||||
#[trial]
|
||||
fn the_rename_field_accepts_a_name_longer_than_a_thousand_characters() {
|
||||
const LONG: usize = 1_500;
|
||||
let (mut fixture, seen) = rig(|_| None);
|
||||
request_rename(fixture.ctx(), list_id(), &0_usize);
|
||||
fixture.settle();
|
||||
fixture.type_text(&"x".repeat(LONG));
|
||||
fixture.settle();
|
||||
fixture.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
fixture.settle();
|
||||
let committed: Vec<usize> = seen
|
||||
.borrow()
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
CollectionEvent::Rename(EditEvent::Commit { after, .. }) => Some(after.name.chars().count()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(committed, [LONG], "the whole name was committed, none of it cut");
|
||||
}
|
||||
|
||||
/// The shapes drawn wholly inside a small square around `at`: an icon's, not a row fill's.
|
||||
fn drawn_at(shapes: &[egui::Shape], at: egui::Pos2) -> usize {
|
||||
let square = egui::Rect::from_center_size(at, Vec2::splat(24.0));
|
||||
|
||||
@@ -57,3 +57,24 @@ fn marking_decorative_disables_the_description_and_keeps_its_text() {
|
||||
assert_eq!(value.borrow().text, Mixed::Same("Kept".to_owned()));
|
||||
assert!(box_disabled(&fixture));
|
||||
}
|
||||
|
||||
/// Focus that moves from the description box to the check, another part of the same component, is the box losing its
|
||||
/// key focus: the field reports it once, in the pass it happens, and not while the focus stays in the box.
|
||||
#[trial]
|
||||
fn focus_moving_to_the_check_reports_the_box_losing_it_once() {
|
||||
let value = Rc::new(RefCell::new(AltText::new("")));
|
||||
let lost = Rc::new(std::cell::Cell::new(0_usize));
|
||||
let (shown, seen) = (value.clone(), lost.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = AltTextField::new(PROMPT, Bind::bound(&mut *shown.borrow_mut())).show(ui);
|
||||
seen.set(seen.get() + usize::from(out.text_lost_focus));
|
||||
});
|
||||
fixture.settle();
|
||||
let description = fixture.by_role(Role::MULTILINE_TEXT_INPUT).remove(0);
|
||||
fixture.click(&description);
|
||||
fixture.idle(3);
|
||||
assert_eq!(lost.get(), 0, "the box keeps its focus while it is typed in");
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.idle(3);
|
||||
assert_eq!(lost.get(), 1, "Tab to the check reports the loss once");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! A text field's typing run across focus changes: switching to another app carries the run on; focus that arrives
|
||||
//! between passes selects a select-on-focus field's text before the next pass's typing; a pointer that brings focus
|
||||
//! keeps the caret or range it made; and a run cut short by the field's removal is forgotten.
|
||||
|
||||
use craft_behavior::{CancelReason, EditEvent};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::runtime::focus::{self, FocusTarget};
|
||||
use craft_ui::testing::{Fixture, input, pointer, trial};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::{Event, Id, Key, Modifiers, Pos2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
/// How a pass of the field ended a typing run.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Ended {
|
||||
Commit,
|
||||
Cancel(CancelReason),
|
||||
}
|
||||
|
||||
/// A text field named "City" bound to `text`, shown while `shown` holds, alone in a window.
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
text: Rc<RefCell<String>>,
|
||||
shown: Rc<Cell<bool>>,
|
||||
/// The next pass asks for the field's focus after drawing it, as a dialog does.
|
||||
focus_after: Rc<Cell<bool>>,
|
||||
field: Rc<Cell<Id>>,
|
||||
ended: Rc<RefCell<Vec<Ended>>>,
|
||||
/// How many passes reported `text_lost_focus`.
|
||||
lost: Rc<Cell<usize>>,
|
||||
}
|
||||
|
||||
fn rig(text: &str, select_on_focus: bool) -> Rig {
|
||||
let text = Rc::new(RefCell::new(text.to_owned()));
|
||||
let (shown, focus_after) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(false)));
|
||||
let field = Rc::new(Cell::new(Id::NULL));
|
||||
let ended = Rc::new(RefCell::new(Vec::new()));
|
||||
let lost = Rc::new(Cell::new(0));
|
||||
let (held, on, asks, id, log, lost_seen) = (text.clone(), shown.clone(), focus_after.clone(), field.clone(), ended.clone(), lost.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
if !on.get() {
|
||||
return;
|
||||
}
|
||||
let mut text = held.borrow_mut();
|
||||
let mut field = TextField::new("City", Bind::bound(&mut *text));
|
||||
if select_on_focus {
|
||||
field = field.select_on_focus();
|
||||
}
|
||||
let out = field.show(ui);
|
||||
id.set(out.response.id);
|
||||
lost_seen.set(lost_seen.get() + usize::from(out.text_lost_focus));
|
||||
log.borrow_mut().extend(out.events.iter().filter_map(|event| match event {
|
||||
EditEvent::Commit { .. } => Some(Ended::Commit),
|
||||
EditEvent::Cancel { reason, .. } => Some(Ended::Cancel(*reason)),
|
||||
_ => None,
|
||||
}));
|
||||
if asks.take() {
|
||||
focus::request(ui.ctx(), FocusTarget::Id(out.response.id));
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
Rig { fixture, text, shown, focus_after, field, ended, lost }
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn text(&self) -> String {
|
||||
self.text.borrow().clone()
|
||||
}
|
||||
|
||||
fn ended(&self) -> Vec<Ended> {
|
||||
self.ended.borrow().clone()
|
||||
}
|
||||
|
||||
fn lost_focus(&self) -> usize {
|
||||
self.lost.get()
|
||||
}
|
||||
|
||||
fn focused(&self) -> bool {
|
||||
self.fixture.focused_stop().map(|(id, _)| id) == Some(self.field.get())
|
||||
}
|
||||
|
||||
fn at(&self) -> Pos2 {
|
||||
self.fixture.by_label("City").expect("the field").center()
|
||||
}
|
||||
|
||||
/// A click in the middle of the field, well after any other: two clicks never make a double click.
|
||||
fn click(&mut self) {
|
||||
self.fixture.advance(1.0);
|
||||
let at = self.at();
|
||||
self.fixture.click_at(at);
|
||||
self.fixture.settle();
|
||||
}
|
||||
|
||||
fn select_all(&mut self) {
|
||||
self.fixture.key(Key::A, Modifiers::COMMAND);
|
||||
self.fixture.settle();
|
||||
}
|
||||
|
||||
fn type_text(&mut self, text: &str) {
|
||||
self.fixture.type_text(text);
|
||||
self.fixture.settle();
|
||||
}
|
||||
|
||||
fn escape(&mut self) {
|
||||
self.fixture.key(Key::Escape, Modifiers::NONE);
|
||||
self.fixture.settle();
|
||||
}
|
||||
|
||||
/// Clicks into the field and retypes its whole text as `text`.
|
||||
fn retype(&mut self, text: &str) {
|
||||
self.click();
|
||||
self.select_all();
|
||||
self.type_text(text);
|
||||
}
|
||||
|
||||
/// The field is not shown for a few passes, too few for its memory to go, while the app sets its text to `text`;
|
||||
/// then it is shown again.
|
||||
fn away_while_the_app_sets(&mut self, text: &str) {
|
||||
self.shown.set(false);
|
||||
self.fixture.idle(4);
|
||||
*self.text.borrow_mut() = text.to_owned();
|
||||
self.shown.set(true);
|
||||
self.fixture.settle();
|
||||
}
|
||||
}
|
||||
|
||||
/// Switching to another app and back is no focus move: the field keeps the focus and its run, the selection it had
|
||||
/// carries on, and nothing commits, cancels or reports `text_lost_focus`; Escape afterwards still gives back the text
|
||||
/// from before the run.
|
||||
#[trial]
|
||||
fn switching_apps_carries_on_with_the_typing_run() {
|
||||
let mut rig = rig("Lisbon", false);
|
||||
rig.retype("Rome");
|
||||
rig.select_all();
|
||||
rig.fixture.frame(vec![pointer::window_blurred()]);
|
||||
rig.fixture.idle(4);
|
||||
assert!(rig.focused(), "the field keeps the focus while the window is in the background");
|
||||
assert_eq!(rig.ended(), [], "the window losing focus ends nothing");
|
||||
rig.fixture.frame(vec![Event::WindowFocused(true)]);
|
||||
rig.fixture.settle();
|
||||
assert!(rig.focused(), "the field has the focus when the window is back");
|
||||
assert_eq!(rig.ended(), [], "the window coming back ends nothing");
|
||||
assert_eq!(rig.lost_focus(), 0, "an app switch is no focus loss: the field reports none, going or coming back");
|
||||
rig.type_text("Porto");
|
||||
assert_eq!(rig.text(), "Porto", "the selection carried on: typing replaced it");
|
||||
rig.escape();
|
||||
assert_eq!(rig.text(), "Lisbon", "Escape gives back the text from before the run");
|
||||
assert_eq!(rig.ended(), [Ended::Cancel(CancelReason::Escape)]);
|
||||
}
|
||||
|
||||
/// A dialog asks for the field's focus after drawing it, so the focus arrives at the end of the pass: the field selects
|
||||
/// its text before the next pass's input, and text typed in that pass replaces it.
|
||||
#[trial]
|
||||
fn text_typed_in_the_pass_focus_arrives_replaces_a_select_on_focus_text() {
|
||||
let mut rig = rig("Craft Library", true);
|
||||
rig.focus_after.set(true);
|
||||
rig.fixture.frame(Vec::new());
|
||||
assert!(rig.focused(), "the request moved the focus to the field for the next pass");
|
||||
rig.fixture.frame(vec![input::text("Fresh")]);
|
||||
rig.fixture.settle();
|
||||
assert_eq!(rig.text(), "Fresh", "the first typed text replaced the selected text");
|
||||
rig.escape();
|
||||
assert_eq!(rig.text(), "Craft Library", "Escape gives back the text from before the run");
|
||||
assert_eq!(rig.ended(), [Ended::Cancel(CancelReason::Escape)]);
|
||||
}
|
||||
|
||||
/// A plain click into a select-on-focus field selects its whole text, as a browser's address bar does.
|
||||
#[trial]
|
||||
fn a_click_into_a_select_on_focus_field_selects_its_text() {
|
||||
let mut rig = rig("Lisbon", true);
|
||||
rig.click();
|
||||
rig.type_text("Kyoto");
|
||||
assert_eq!(rig.text(), "Kyoto");
|
||||
}
|
||||
|
||||
/// A drag into a select-on-focus field selects what the drag covers: the focus the press brought does not replace the
|
||||
/// pointer's range with the whole text.
|
||||
#[trial]
|
||||
fn a_drag_into_a_select_on_focus_field_selects_what_it_covers() {
|
||||
let mut rig = rig("Lisbon Portugal Europe Atlantic Ocean", true);
|
||||
let field = rig.fixture.by_label("City").expect("the field").rect;
|
||||
let (from, to) = (field.center(), egui::pos2(field.right() + 40.0, field.center().y));
|
||||
rig.fixture.drag_at(from, to - from);
|
||||
rig.fixture.settle();
|
||||
assert!(rig.focused(), "the press focused the field");
|
||||
rig.type_text("X");
|
||||
let text = rig.text();
|
||||
assert!(text.starts_with("Lisbon") && text.ends_with('X') && text != "X", "the drag's range was replaced: {text:?}");
|
||||
}
|
||||
|
||||
/// A field removed in the middle of a run and shown again after the app changed its text starts afresh from that text:
|
||||
/// the run cut short is not replayed as a Cancel that puts back the text from before it.
|
||||
#[trial]
|
||||
fn a_run_cut_short_by_removal_is_forgotten() {
|
||||
let mut rig = rig("Lisbon", false);
|
||||
rig.retype("Rome");
|
||||
assert_eq!(rig.text(), "Rome", "the typing reached the binding");
|
||||
rig.away_while_the_app_sets("Porto");
|
||||
assert_eq!(rig.text(), "Porto", "the text the app set stays");
|
||||
assert!(!rig.focused(), "no run is under way");
|
||||
assert!(!rig.ended().contains(&Ended::Commit), "the run cut short commits nothing: {:?}", rig.ended());
|
||||
rig.retype("Kyoto");
|
||||
rig.escape();
|
||||
assert_eq!(rig.text(), "Porto", "Escape gives back the text the new run began with");
|
||||
}
|
||||
|
||||
/// A field removed in the middle of a run and shown again with its text unchanged keeps the typed text: the run is
|
||||
/// forgotten, not cancelled back to the text from before it.
|
||||
#[trial]
|
||||
fn a_run_cut_short_by_removal_keeps_the_typed_text() {
|
||||
let mut rig = rig("Lisbon", false);
|
||||
rig.retype("Rome");
|
||||
rig.away_while_the_app_sets("Rome");
|
||||
assert_eq!(rig.text(), "Rome", "the typed text stays");
|
||||
rig.retype("Kyoto");
|
||||
rig.escape();
|
||||
assert_eq!(rig.text(), "Rome", "Escape gives back the text the new run began with");
|
||||
}
|
||||
|
||||
/// A field removed while its edit menu holds the focus starts afresh too.
|
||||
#[trial]
|
||||
fn a_field_removed_with_its_edit_menu_open_starts_afresh() {
|
||||
let mut rig = rig("Lisbon", false);
|
||||
rig.retype("Rome");
|
||||
rig.fixture.advance(1.0);
|
||||
let at = rig.at();
|
||||
rig.fixture.frame(vec![pointer::secondary(at, true)]);
|
||||
rig.fixture.frame(vec![pointer::secondary(at, false)]);
|
||||
rig.fixture.settle();
|
||||
let cut = rig.fixture.by_label("Cut").expect("the edit menu's Cut").center();
|
||||
rig.fixture.click_at(cut);
|
||||
rig.away_while_the_app_sets("Porto");
|
||||
assert_eq!(rig.text(), "Porto", "the text the app set stays");
|
||||
assert!(!rig.focused(), "no run is under way");
|
||||
assert!(!rig.ended().contains(&Ended::Commit), "the run cut short commits nothing: {:?}", rig.ended());
|
||||
rig.retype("Kyoto");
|
||||
rig.escape();
|
||||
assert_eq!(rig.text(), "Porto", "Escape gives back the text the new run began with");
|
||||
}
|
||||
|
||||
/// The edit menu holds the field's editing focus while it is open: that is no focus loss, so the field reports none in
|
||||
/// the passes the menu is open.
|
||||
#[trial]
|
||||
fn an_open_edit_menu_is_no_focus_loss() {
|
||||
let mut rig = rig("Lisbon", false);
|
||||
rig.retype("Rome");
|
||||
rig.fixture.advance(1.0);
|
||||
let at = rig.at();
|
||||
rig.fixture.frame(vec![pointer::secondary(at, true)]);
|
||||
rig.fixture.frame(vec![pointer::secondary(at, false)]);
|
||||
rig.fixture.settle();
|
||||
assert!(rig.fixture.by_label("Cut").is_some(), "the edit menu is open");
|
||||
rig.fixture.idle(4);
|
||||
assert_eq!(rig.lost_focus(), 0, "the passes with the menu open report no focus loss");
|
||||
}
|
||||
@@ -2,15 +2,18 @@ pub(crate) mod access;
|
||||
pub(crate) mod alt_text;
|
||||
pub(crate) mod chips;
|
||||
pub(crate) mod edit_menu;
|
||||
pub(crate) mod edit_run;
|
||||
pub(crate) mod fields;
|
||||
pub(crate) mod hex;
|
||||
mod kit;
|
||||
pub(crate) mod linked;
|
||||
pub(crate) mod mixed_blank;
|
||||
pub(crate) mod number;
|
||||
pub(crate) mod number_derived;
|
||||
pub(crate) mod number_length;
|
||||
pub(crate) mod number_look;
|
||||
pub(crate) mod number_scrub_step;
|
||||
pub(crate) mod number_select;
|
||||
pub(crate) mod rtl_paragraph;
|
||||
pub(crate) mod selectable;
|
||||
pub(crate) mod step_arrows;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! A derived number (an automatic leading) shows in parentheses until it is edited, and an edit starts from the plain number.
|
||||
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _};
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Key, Modifiers};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// The value the automatic setting works out.
|
||||
const COMPUTED: f64 = 87.6;
|
||||
|
||||
/// A derived field is read out in parentheses with its unit; focusing it shows the plain number to edit, and a
|
||||
/// committed number is the field's value.
|
||||
#[trial]
|
||||
fn a_derived_number_shows_in_parentheses_and_edits_from_the_plain_number() {
|
||||
let value = Rc::new(Cell::new(Some(COMPUTED)));
|
||||
let id = Rc::new(Cell::new(egui::Id::NULL));
|
||||
let (shown, seen) = (value.clone(), id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = shown.get();
|
||||
let out = NumberField::new("Leading", Bind::bound(&mut current)).id_salt("leading").unit_kind(UnitKind::Points).derived(true).show(ui);
|
||||
seen.set(out.response.id);
|
||||
shown.set(current);
|
||||
});
|
||||
fixture.settle();
|
||||
assert_eq!(fixture.tree().value(id.get()), Some("(87.6 pt)"), "an idle derived field reads out its value in parentheses");
|
||||
assert_eq!(fixture.tree().numeric(id.get()).and_then(|numeric| numeric.value), Some(COMPUTED), "its numeric value is the plain number");
|
||||
|
||||
let field = fixture.by_label("Leading").expect("the Leading number field");
|
||||
fixture.click(&field).settle();
|
||||
assert_eq!(fixture.tree().value(id.get()), Some("87.6"), "an edit starts from the plain number");
|
||||
|
||||
fixture.key(Key::A, Modifiers::COMMAND).type_text("12").key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(value.get(), Some(12.0), "the committed number is the field's value");
|
||||
assert_eq!(fixture.tree().numeric(id.get()).and_then(|numeric| numeric.value), Some(12.0), "the field reports the committed number");
|
||||
}
|
||||
|
||||
/// A blank value is no number to derive: the field shows it as it would without `derived`, never as empty
|
||||
/// parentheses, and an edit from the blank still starts from nothing.
|
||||
#[trial]
|
||||
fn a_blank_derived_number_shows_no_parentheses() {
|
||||
let value = Rc::new(Cell::new(None::<f64>));
|
||||
let id = Rc::new(Cell::new(egui::Id::NULL));
|
||||
let (shown, seen) = (value.clone(), id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = shown.get();
|
||||
let out = NumberField::new("Leading", Bind::bound(&mut current)).id_salt("leading").unit_kind(UnitKind::Points).derived(true).show(ui);
|
||||
seen.set(out.response.id);
|
||||
shown.set(current);
|
||||
});
|
||||
fixture.settle();
|
||||
let text = fixture.tree().value(id.get()).unwrap_or_default().to_owned();
|
||||
assert!(!text.contains('('), "a blank value is not shown as a derived value: {text:?}");
|
||||
let field = fixture.by_label("Leading").expect("the Leading number field");
|
||||
fixture.click(&field).settle();
|
||||
fixture.type_text("12").key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(value.get(), Some(12.0), "a number typed over the blank is the field's value");
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! A number field's `select_on_focus`: a click on the value selects its whole text, so typing replaces it.
|
||||
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::form::SliderField;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Key, Modifiers};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// A field that writes every decimal ("0.00"): a click on it and "0.5" typed give 0.5, not "0.000.5".
|
||||
#[trial]
|
||||
fn a_click_on_a_select_on_focus_number_field_selects_its_value() {
|
||||
let value = Rc::new(Cell::new(Some(0.0)));
|
||||
let held = Rc::clone(&value);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut now = held.get();
|
||||
NumberField::new("Amount", Bind::bound(&mut now)).range(-1.0..=1.0).step(0.01).fixed_decimals(2).select_on_focus().show(ui);
|
||||
held.set(now);
|
||||
});
|
||||
fixture.settle();
|
||||
let field = fixture.by_label("Amount").expect("the field");
|
||||
fixture.click(&field).settle();
|
||||
fixture.type_text("0.5");
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(value.get(), Some(0.5), "the typed value replaced the shown one");
|
||||
}
|
||||
|
||||
/// A slider field passes the option to its number field.
|
||||
#[trial]
|
||||
fn a_click_on_a_select_on_focus_slider_fields_value_selects_it() {
|
||||
let value = Rc::new(Cell::new(20.0));
|
||||
let held = Rc::clone(&value);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut now = held.get();
|
||||
SliderField::new("Size", Bind::bound(&mut now), 0.0..=100.0).step(1.0).select_on_focus().show(ui);
|
||||
held.set(now);
|
||||
});
|
||||
fixture.settle();
|
||||
let field = fixture.by_label("Size").expect("the field");
|
||||
fixture.click(&field).settle();
|
||||
fixture.type_text("36");
|
||||
fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(value.get(), 36.0, "the typed value replaced the shown one");
|
||||
}
|
||||
@@ -297,3 +297,183 @@ fn the_clear_part_empties_the_field_in_the_pass_of_its_click() {
|
||||
assert_eq!(text.borrow().as_str(), "", "the click emptied the text");
|
||||
assert_eq!(fixture.tree().value(id.get()), Some(""), "the field reads empty in the pass of the click");
|
||||
}
|
||||
|
||||
/// 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)));
|
||||
// What the field reported: the commits and cancels of its events and the passes that reported a submit.
|
||||
let (commits, cancels, submits) = (Rc::new(Cell::new(0_u32)), Rc::new(Cell::new(0_u32)), Rc::new(Cell::new(0_u32)));
|
||||
let (shown, scope_saw, lost_seen, field) = (text.clone(), passed.clone(), lost.clone(), id.clone());
|
||||
let (seen_commits, seen_cancels, seen_submits) = (commits.clone(), cancels.clone(), submits.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);
|
||||
for event in out.events.iter() {
|
||||
match event {
|
||||
craft_behavior::EditEvent::Commit { .. } => seen_commits.set(seen_commits.get() + 1),
|
||||
craft_behavior::EditEvent::Cancel { .. } => seen_cancels.set(seen_cancels.get() + 1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
seen_submits.set(seen_submits.get() + u32::from(out.submitted));
|
||||
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");
|
||||
let (commits_before, cancels_before) = (commits.get(), cancels.get());
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.idle(3);
|
||||
assert_eq!(*text.borrow(), "abc", "Escape keeps the typed text");
|
||||
assert_eq!(commits.get() - commits_before, 1, "the open typing run commits exactly once");
|
||||
assert_eq!(cancels.get() - cancels_before, 0, "and nothing is cancelled");
|
||||
assert_eq!(submits.get(), 0, "the Escape submits nothing");
|
||||
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");
|
||||
}
|
||||
|
||||
/// A field that keeps its text on Escape does so only while it can be edited: one that went read-only in the middle of
|
||||
/// a typing run takes Escape as a plain field does, so the run is cancelled, not committed. (A read-only component
|
||||
/// refuses every event that carries a value, so the cancel reaches the app as an event and writes nothing back.)
|
||||
#[trial]
|
||||
fn a_field_that_went_read_only_mid_run_cancels_its_run_on_escape() {
|
||||
let text = Rc::new(RefCell::new(String::from("old")));
|
||||
let read_only = Rc::new(Cell::new(false));
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let id = Rc::new(Cell::new(Id::NULL));
|
||||
let (shown, locked, log, field) = (text.clone(), read_only.clone(), events.clone(), id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut held = shown.borrow_mut();
|
||||
let out = TextField::new("Filter", Bind::bound(&mut *held)).keeps_on_escape().select_on_focus().read_only(locked.get()).show(ui);
|
||||
field.set(out.response.id);
|
||||
log.borrow_mut().extend(out.events.iter().map(|event| match event {
|
||||
craft_behavior::EditEvent::Commit { .. } => "commit",
|
||||
craft_behavior::EditEvent::Cancel { .. } => "cancel",
|
||||
_ => "other",
|
||||
}));
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.type_text("new");
|
||||
fixture.idle(2);
|
||||
assert_eq!(*text.borrow(), "new", "the typing reached the binding");
|
||||
read_only.set(true);
|
||||
fixture.idle(2);
|
||||
events.borrow_mut().clear();
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.idle(3);
|
||||
assert!(!events.borrow().contains(&"commit"), "the run is not committed: {:?}", events.borrow());
|
||||
assert!(events.borrow().contains(&"cancel"), "the run is cancelled: {:?}", events.borrow());
|
||||
// The draft is gone: the field shows the host's value again, not the text typed before the run ended.
|
||||
*text.borrow_mut() = String::from("host");
|
||||
fixture.idle(3);
|
||||
assert_eq!(fixture.tree().value(id.get()), Some("host"), "the field shows the host's value");
|
||||
}
|
||||
|
||||
/// A kept Escape that closes the popover the field sits in hands focus back to the popover's opener, as any Escape that
|
||||
/// closes it does: the field is let go only after the popover's focus restoration has found it holding the focus.
|
||||
#[trial]
|
||||
fn a_kept_escape_that_closes_its_popover_returns_focus_to_the_opener() {
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::popover::Popover;
|
||||
use craft_ui::testing::contract::clicked;
|
||||
let open = Rc::new(Cell::new(false));
|
||||
let text = Rc::new(RefCell::new(String::new()));
|
||||
let opener_id = Rc::new(Cell::new(Id::NULL));
|
||||
let (shown, held, opener_seen) = (open.clone(), text.clone(), opener_id.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let opener = Button::new("Filter options").show(ui);
|
||||
opener_seen.set(opener.response.id);
|
||||
let mut is_open = shown.get();
|
||||
if clicked(&opener) {
|
||||
is_open = !is_open;
|
||||
}
|
||||
Popover::new("Filter", Bind::bound(&mut is_open)).opened_by(&opener).show(ui, |ui, _| {
|
||||
let mut query = held.borrow_mut();
|
||||
TextField::new("Query", Bind::bound(&mut *query)).keeps_on_escape().show(ui);
|
||||
});
|
||||
shown.set(is_open);
|
||||
});
|
||||
fixture.settle();
|
||||
let button = fixture.by_label("Filter options").expect("the opener");
|
||||
fixture.click(&button);
|
||||
fixture.idle(4);
|
||||
assert!(open.get() && fixture.by_label("Query").is_some(), "the popover opened on its field");
|
||||
fixture.type_text("ab");
|
||||
fixture.idle(2);
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.idle(6);
|
||||
assert_eq!(*text.borrow(), "ab", "the kept Escape keeps the text");
|
||||
assert!(!open.get(), "the Escape closed the popover");
|
||||
assert_eq!(fixture.focused(), Some(opener_id.get()), "focus returned to the opener");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user