Text parts open the framework edit menu on a context request

Every craft text control (TextField, NumberField, ChipField, AltTextField, DateField, ComboBox) shows the
EditMenu in a context menu on a right click in its text, the Menu key or Shift+F10. The open menu holds the
focus without ending the text part's typing run or losing its selection, so Escape closes the menu and the
field keeps editing, and a picked row acts on the field's selection once the focus is back. Rows run their
EditCommands through the command board, the same route an app's Edit menu uses.

- record_context counts a secondary release on a component's text widget
- a secondary press inside the selection keeps the selection
- EditCommand::Delete: the Delete command run from a menu deletes a text part's selection; the Delete and
  Backspace keys stay the text part's own deletion, and editors leave the command to the app
- TextField/NumberField::own_context_menu for a caller that hangs its own context menu on the field
  (the transform fields' unit menu)
This commit is contained in:
aiongg
2026-11-12 18:32:56 +00:00
parent 70d4172b6e
commit e1d34a0093
25 changed files with 287 additions and 26 deletions
+3
View File
@@ -95,6 +95,9 @@ pub enum EditCommand {
Undo,
/// Redo the last undone edit.
Redo,
/// Delete the selection. It arrives only as a run of the Delete command (a menu row): the Delete and Backspace
/// keys stay a text part's own deletion.
Delete,
}
/// A position in a text document.
@@ -395,6 +395,9 @@ impl Cells<'_> {
if percent {
number = number.commit_decimals(decimals);
}
if menu.is_some() {
number = number.own_context_menu();
}
let shown = number.show(ui);
events = shown.edit.events.clone();
if let Some(entries) = menu {
@@ -257,6 +257,13 @@ impl<C: Component> Cx<'_, C> {
crate::runtime::keys::context_part(&self.core.ctx, self.core.id)
}
/// Whether the component was asked for its context menu in this pass: a secondary click on it, the Menu key or
/// Shift+F10 it did not take, or AccessKit's `ShowContextMenu`. Recorded after `update`, so `overlay` and
/// `finish` read it.
pub fn context_requested(&self) -> bool {
crate::runtime::keys::context_request(&self.core.ctx, self.core.id).is_some()
}
/// Names the member of this container's roving group (`ContainerProps.roving`) that Tab arrives at; the
/// first member when none is named.
pub fn roving_arrival(&mut self, member: Id) {
+1
View File
@@ -97,6 +97,7 @@ pub use registry::registrations;
pub use registry::{CollectionEntry, ContainerEntry, Exemption, LeafEntry, PatternKind, PatternProbe, Probe, Registration, ShowEntry};
pub use sampler::Sampler;
pub use settle::SettleCx;
pub use text::EDIT_MENU;
pub use values::{Bind, BindMut, EditResponse, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed};
use crate::runtime::memory::sub;
@@ -291,7 +291,7 @@ impl PopupHandle {
self.is_open_in(&mut cx.core)
}
pub(super) fn is_open_in(self, core: &mut CxCore<'_>) -> bool {
pub(crate) fn is_open_in(self, core: &mut CxCore<'_>) -> bool {
self.registered(core);
open_now(core.memory, self.id)
}
@@ -89,13 +89,20 @@ fn double_click(core: &CxCore<'_>) -> Option<Option<PartRef>> {
.map(|&(key, index)| Some(PartRef { key, index }))
}
/// Step 9, after `update`: a secondary release on the component, or a `ContextMenu` intent it did not take, records a
/// context request that the overlay step and the popups shown after it read in this pass (9.2 rule 3). The request
/// is at the part under the pointer for a release, at the active part for the intent, else at the component.
/// Step 9, after `update`: a secondary release on the component (its text part included, which is a widget of its
/// own over it), or a `ContextMenu` intent it did not take, records a context request that the overlay step and the
/// popups shown after it read in this pass (9.2 rule 3). The request is at the part under the pointer for a release,
/// at the active part for the intent, else at the component.
pub(crate) fn record_context(core: &CxCore<'_>) {
let hovered = || {
core.response.hovered()
|| core.texts.as_ref().is_some_and(|(key, _)| {
core.ctx.read_response(crate::primitives::text_adapter::text_id(core.id, *key)).is_some_and(|text| text.hovered())
})
};
let part = if core.intents.untaken(&Intent::ContextMenu) {
focus::active_part(&core.ctx, core.id)
} else if core.response.hovered() && crate::runtime::pointer::frame(&core.ctx).release == Some(craft_behavior::PointerButton::Secondary) {
} else if crate::runtime::pointer::frame(&core.ctx).release == Some(craft_behavior::PointerButton::Secondary) && hovered() {
core.results.iter().find(|(_, result)| result.hovered).map(|(&(key, index), _)| PartRef { key, index })
} else {
return;
+11
View File
@@ -22,6 +22,10 @@ use egui::{Rect, Ui};
use std::any::Any;
use std::sync::Arc;
/// The popup name of a text part's edit menu: step 8b registers it for every text part, and the text control opens
/// and shows it from its `overlay` hook.
pub const EDIT_MENU: &str = "edit";
/// The id of the text adapter's state in the component's memory.
fn state_id(id: egui::Id) -> egui::Id {
sub(id, "text_state")
@@ -399,6 +403,7 @@ pub(crate) fn run<C: Component>(
let read_only = cx.core.resolved.read_only || !enabled;
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 = cx.popup(EDIT_MENU).is_open_in(&mut cx.core);
serve_access(cx, &mut state, widget, &decl.shown, read_only);
cx.core.surface_slot = Some(ui.painter().add(egui::Shape::Noop));
let out = adapter::run(
@@ -418,6 +423,7 @@ pub(crate) fn run<C: Component>(
pointer,
rtl,
focused,
held,
ink,
intents: &mut cx.core.intents,
list_open,
@@ -491,6 +497,11 @@ impl<C: Component> Cx<'_, C> {
crate::runtime::egui::repaint::request(&self.core.ctx);
}
/// The key of the text part step 8b ran in this pass; `None` for a component that declared none.
pub fn text_part(&self) -> Option<PartKey> {
self.core.texts.as_ref().map(|(part, _)| *part)
}
/// The result of the text part `key` this pass: the draft, the laid-out text and the caret blink. `None` while
/// the text service has not produced one (a part first registered this pass), and for a key `parts` never
/// registered, which is a debug assertion.
@@ -75,6 +75,9 @@ pub(crate) struct TextState {
pub completions: completion::Completions,
/// The draft change `Cx::set_draft` asked for, applied at the start of the next pass.
pub change: Option<DraftChange>,
/// The selection, `(caret, anchor)`, the text part had when its edit menu took the focus: egui collapses the
/// selection of a widget without focus, and the menu's command acts on it once the focus is back.
pub held_selection: Option<(usize, usize)>,
}
/// The id of a text part's egui widget, which holds key focus.
@@ -113,6 +116,9 @@ pub(crate) struct AdapterIn<'a> {
pub rtl: bool,
/// The text widget holds key focus.
pub focused: bool,
/// The text part's own edit menu is open and holds the focus: losing the focus to it ends no typing run, and
/// getting it back is no new focus.
pub held: bool,
pub ink: egui::Color32,
pub intents: &'a mut Intents,
/// A list the component opened on the text is shown (a dropdown, the completions): Escape is the list's.
@@ -235,6 +241,13 @@ fn apply(input: &mut AdapterIn<'_>, state: &mut TextState, text: &mut String, wi
changed = true;
}
}
EditCommand::Delete => {
let (a, b) = selection(text);
if a != b {
replace_selection(ctx, widget, text, (a.min(b), a.max(b)), "");
changed = true;
}
}
EditCommand::Paste => {
if let Some(pasted) = keys::pasted_text(ctx, input.id) {
let pasted = if input.options.multiline() { pasted.to_string() } else { pasted.replace(['\n', '\r'], " ") };
@@ -301,6 +314,15 @@ fn held_mods(ctx: &Context) -> Mods {
pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut {
let (ctx, widget) = (input.ctx, text_id(input.id, input.key));
let focused_before = input.focused;
if input.held {
if state.held_selection.is_none() {
state.held_selection = selection(ctx, widget);
}
} else if let Some((caret, anchor)) = state.held_selection.take()
&& input.focused
{
select(ctx, widget, anchor, caret);
}
let mut base = state.draft.clone().or_else(|| state.normalised.take()).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) {
@@ -362,7 +384,16 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
underline: input.underline,
galley: None,
};
// A secondary press inside the selection keeps the selection for the edit menu it opens, as native fields do;
// egui's widget moves the caret to any press, so the selection from before the press is put back.
let secondary = crate::runtime::pointer::frame(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary);
let kept = selection(ctx, widget).filter(|(caret, anchor)| secondary && caret != anchor);
let shown = text_edit::show(input.ui, edit);
if let Some((caret, anchor)) = kept
&& selection(ctx, widget).is_some_and(|(at, _)| (caret.min(anchor)..=caret.max(anchor)).contains(&at))
{
select(ctx, widget, anchor, caret);
}
// egui's own IME output is dropped: the engine writes the pass's.
if let Some(caret) = shown.caret.filter(|_| shown.focused) {
ime::note_caret(ctx, widget, input.rect, caret, input.options.mask);
@@ -391,10 +422,10 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
}
} else if separated {
state.end = Some(End::Separator);
} else if shown.lost_focus && state.draft.is_some() && state.end.is_none() {
} else if shown.lost_focus && !input.held && state.draft.is_some() && state.end.is_none() {
state.end = Some(End::Blur);
}
state.focused = shown.focused;
state.focused = shown.focused || input.held;
let full = display;
let layout = TextLayout::new(shown.galley, false, full);
let baseline = (!layout.full.is_empty()).then(|| shown.galley_pos.y + layout.first_baseline);
@@ -88,6 +88,9 @@ pub struct TextOptions {
/// Why a draft the codec cannot parse is no value ("Not a hex color"): while such a draft shows, it is the
/// component's refusing validity message, unless its binding refuses or warns with one of its own.
pub unparsed: Option<Message>,
/// The control's caller hangs a context menu of its own on it: a context request opens that menu, not the text
/// part's edit menu.
pub own_menu: bool,
}
impl Default for TextOptions {
@@ -115,6 +118,7 @@ impl Default for TextOptions {
centred: false,
arrows_from_end: false,
unparsed: None,
own_menu: false,
}
}
}
@@ -397,6 +397,8 @@ fn build_keymap(registry: &registry::Registry, platform: Platform, overrides: Op
.defs()
.iter()
.filter_map(|def| registry.edit_of(&def.command.id).map(|edit| (edit, &def.command)))
// Delete's keys (Delete, Backspace) stay a focused text part's own deletion, which also deletes one character.
.filter(|(edit, _)| *edit != EditCommand::Delete)
.flat_map(|(edit, command)| {
keymap.bindings(command).into_iter().filter(|binding| !binding.trigger.double).map(move |binding| (edit, binding.trigger.chord))
})
@@ -29,17 +29,25 @@ pub enum EditCommands {
#[command(label = "Redo", modal = "declared", edit = "redo", icon = "redo", default = "Cmd+Shift+Z")]
Redo,
/// Delete the selection. Delete and Backspace both bind it (the key labelled Delete on macOS reports Backspace).
/// It carries no text-edit intent: a text part's own Delete key stays its deletion.
#[command(label = "Delete", modal = "declared", icon = "trash", default = "Delete", default = "Backspace")]
/// Those keys stay a focused text part's own deletion; a run of the command (a menu row) reaches the text part as
/// its edit.
#[command(label = "Delete", modal = "declared", edit = "delete", icon = "trash", default = "Delete", default = "Backspace")]
Delete,
}
impl EditCommands {
/// Every edit command that a focused component can take as an `Intent::Edit`.
pub const ALL: [EditCommands; 6] =
[EditCommands::Cut, EditCommands::Copy, EditCommands::Paste, EditCommands::SelectAll, EditCommands::Undo, EditCommands::Redo];
pub const ALL: [EditCommands; 7] = [
EditCommands::Cut,
EditCommands::Copy,
EditCommands::Paste,
EditCommands::SelectAll,
EditCommands::Undo,
EditCommands::Redo,
EditCommands::Delete,
];
/// The intent a component takes this command as; `None` for a command that is always the app's.
/// The intent a component takes this command as.
pub const fn edit(self) -> Option<EditCommand> {
Some(match self {
EditCommands::Cut => EditCommand::Cut,
@@ -48,7 +56,7 @@ impl EditCommands {
EditCommands::SelectAll => EditCommand::SelectAll,
EditCommands::Undo => EditCommand::Undo,
EditCommands::Redo => EditCommand::Redo,
EditCommands::Delete => return None,
EditCommands::Delete => EditCommand::Delete,
})
}
@@ -61,6 +69,7 @@ impl EditCommands {
EditCommand::SelectAll => EditCommands::SelectAll,
EditCommand::Undo => EditCommands::Undo,
EditCommand::Redo => EditCommands::Redo,
EditCommand::Delete => EditCommands::Delete,
_ => return None,
})
}
@@ -213,7 +213,7 @@ impl EditSet {
/// No command.
pub const NONE: EditSet = EditSet(0);
/// Every command.
pub const ALL: EditSet = EditSet(0b11_1111);
pub const ALL: EditSet = EditSet(0b111_1111);
const fn bit(command: EditCommand) -> u8 {
1 << match command {
@@ -222,6 +222,7 @@ impl EditSet {
EditCommand::Paste => 2,
EditCommand::SelectAll => 3,
EditCommand::Undo => 4,
EditCommand::Delete => 6,
_ => 5,
}
}
@@ -330,9 +331,11 @@ impl KeyUse {
Input::Editor => (KeepKeys::BlockArrows, ActivateKeys::Neither, OwnerClass::Text),
_ => (KeepKeys::None, ActivateKeys::Neither, OwnerClass::Widget),
};
// Text parts and editors list every edit command (11.3).
let edits = match owner {
OwnerClass::Text => EditSet::ALL,
// Text parts list every edit command (11.3); editors every one but Delete, whose run (a menu row) stays the
// app's command while an editor has the focus.
let edits = match input {
Input::Text => EditSet::ALL,
Input::Editor => EditSet(EditSet::ALL.0 & !EditSet::bit(EditCommand::Delete)),
_ => EditSet::NONE,
};
let owner_text = matches!(owner, OwnerClass::Text);
+7 -1
View File
@@ -119,7 +119,13 @@ fn edit_tokens(edit: &LitStr) -> syn::Result<TokenStream> {
"select_all" => "SelectAll",
"undo" => "Undo",
"redo" => "Redo",
_ => return Err(syn::Error::new(edit.span(), "`edit` is `\"cut\"`, `\"copy\"`, `\"paste\"`, `\"select_all\"`, `\"undo\"` or `\"redo\"`")),
"delete" => "Delete",
_ => {
return Err(syn::Error::new(
edit.span(),
"`edit` is `\"cut\"`, `\"copy\"`, `\"paste\"`, `\"select_all\"`, `\"undo\"`, `\"redo\"` or `\"delete\"`",
));
}
};
let name = syn::Ident::new(name, edit.span());
Ok(quote!(::craft_ui::runtime::commands::EditCommand::#name))
+23 -3
View File
@@ -1,8 +1,9 @@
//! `EditMenu`: the rows of a text control's context menu.
use super::MenuItem;
use crate::contract::Show as _;
use super::{Menu, MenuItem, MenuWords};
use crate::contract::{Component, Cx, OverlayUi, Overlays as _, Show as _, ShowContainer as _, Trigger, WordSetCx as _};
use crate::display::Divider;
use crate::primitives::TextOptions;
use crate::runtime::commands::EditCommands;
use egui::Ui;
@@ -18,7 +19,7 @@ pub struct EditMenuOutput {
///
/// Each row is a `MenuItem::command` over an `EditCommands` command, so its label, icon, chord and enabled state come
/// from the command: the focused text part publishes which commands apply (no selection, no Cut, Copy or Delete).
/// Menu-body content: show it in the body of the `Menu::context` of the text control.
/// Menu-body content: every text control shows it as its edit menu, on a right click in its text.
#[derive(crate::contract::Pattern)]
pub struct EditMenu;
@@ -43,3 +44,22 @@ impl EditMenu {
EditMenuOutput { ran }
}
}
/// The context menu of a component's text part, the one every text control opens: a context request on the component
/// (a right click, the Menu key, Shift+F10) opens the [`EditMenu`] at the pointer, or at the control for a key. Its
/// rows run their `EditCommands` through the command board, which hands each to the focused text part once the pick has
/// closed the menu and given the focus back. Every text control calls this from its `overlay` hook with its text
/// part's options; it opens nothing for a control whose caller hangs a context menu of its own on it
/// (`TextOptions::own_menu`).
pub(crate) fn text_menu<C: Component>(ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, C>, options: &TextOptions) {
let Some(text) = cx.text_part() else { return };
let popup = cx.popup(crate::contract::EDIT_MENU);
// A request at another part (a chip, a chevron) is that part's.
let at_text = cx.context_part().is_none_or(|part| part.key == text);
if !options.own_menu && cx.context_requested() && at_text && !popup.is_open(cx) {
popup.open(cx);
}
let name = cx.words::<MenuWords>().edit.clone();
let layer = super::layer(false).opened_by(&cx.core.response, Trigger::Context);
ui.show(popup, layer, |ui, _| Menu::inline(name.clone()).show(ui, |ui, _| EditMenu.show(ui)));
}
+1
View File
@@ -13,6 +13,7 @@ mod stories;
mod words;
pub use bar::{MenuBar, MenuBarOutput, MenuBarStyle, MenuHelp, MenuTitle};
pub(crate) use edit::text_menu;
pub use edit::{EditMenu, EditMenuOutput};
pub use item::{MenuItem, MenuItemOutput, MenuItemStyle};
pub use panel::{GroupItem, PanelMenu, PanelMenuOutput, PanelRow};
+1
View File
@@ -7,6 +7,7 @@ craft_ui::words! {
bar_all: "menu.barAll" = "Menu";
bar_search: "menu.barSearch" = "Search menus";
bar_no_matches: "menu.barNoMatches" = "No matching commands";
edit: "menu.edit" = "Edit";
panel_move_to: "menu.panelMoveTo" = "Move Panel To";
panel_auto_collapse: "menu.panelAutoCollapse" = "Auto-Collapse Iconic Panels";
panel_minimize: "menu.panelMinimize" = "Minimize";
@@ -194,6 +194,7 @@ impl Component for ComboBox<'_> {
/// the text from before the keys. A pick comes back as `Activate` (Enter or a click) and puts the option's text
/// in the field.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
crate::menu::text_menu(ui, cx, &self.text_options());
let popup = cx.popup("options");
let options = self.options;
let query = cx.memory::<Typing>().draft.clone().unwrap_or_default();
+1
View File
@@ -293,6 +293,7 @@ impl Component for DatePicker<'_> {
/// The calendar: a precision switch when more than one is offered, the page, and Today and Clear. The day under
/// the pointer is proposed; a pick proposes and commits, and closes the popover.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
crate::menu::text_menu(ui, cx, &TextOptions::new());
let popup = cx.popup("calendar");
let dates = cx.env.dates();
let words = cx.words::<PickerWords>();
+8 -2
View File
@@ -5,7 +5,9 @@ mod stories;
use super::{FieldStyle, text_part};
use crate::choice::Checkbox;
use crate::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, PartsCx, Props as _, Role, WordSetCx as _};
use crate::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, OverlayUi, PaintUi, PartsCx, Props as _, Role, WordSetCx as _,
};
use crate::primitives::{TextOptions, TextRun};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, Flags, StyleCx, SurfaceLook};
@@ -140,7 +142,6 @@ fn sizes(cx: &MeasureCx<'_, AltTextField<'_>>) -> (f32, Vec2) {
impl Component for AltTextField<'_> {
const ROLE: Role = Role::TEXT_INPUT;
const INPUT: crate::contract::Input = crate::contract::Input::Text;
const OVERLAYS: bool = false;
type Style = AltTextFieldStyle;
type Output = EditResponse<AltText>;
@@ -191,6 +192,11 @@ impl Component for AltTextField<'_> {
}
}
/// The edit menu.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
crate::menu::text_menu(ui, cx, &TextOptions::default());
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let words = cx.words::<AltTextWords>();
ui.face(DECORATIVE, check_face(shown_of(cx.value()).decorative, &words));
+1
View File
@@ -440,6 +440,7 @@ impl Component for ChipField<'_> {
/// The menu of the hidden chips: one row per chip, its whole text; choosing one removes it.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
crate::menu::text_menu(ui, cx, &self.options);
let popup = cx.popup("more");
let chips = cx.value().cloned().unwrap_or_default();
let shown = self.shown.unwrap_or(chips.len()).min(chips.len());
+10 -1
View File
@@ -192,6 +192,14 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
.label(label)
}
/// The caller hangs a context menu of its own on the field (`Menu::context` over its response, a unit menu): a
/// right click opens that menu instead of the field's edit menu.
#[must_use]
pub fn own_context_menu(mut self) -> Self {
self.options.own_menu = true;
self
}
/// A drag on the field's side label scrubs the value too, with or without the focus in the field.
#[must_use]
pub fn scrub_by_label(mut self) -> Self {
@@ -497,8 +505,9 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
}
}
/// The presets list and the popup slider.
/// The edit menu, the presets list and the popup slider.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
crate::menu::text_menu(ui, cx, &self.options);
if let Some(rows) = self.presets {
self.show_presets(ui, cx, rows);
}
+10 -1
View File
@@ -157,6 +157,14 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
self
}
/// The caller hangs a context menu of its own on the field (`Menu::context` over its response): a right click opens
/// that menu instead of the field's edit menu.
#[must_use]
pub fn own_context_menu(mut self) -> Self {
self.options.own_menu = true;
self
}
/// Enter acts in the field itself (it saves the value or runs a search): the field takes it, and an enclosing
/// dialog's default button does not. A field without this leaves Enter to that button. In a multi-line field
/// Enter still adds a line, and Cmd+Enter (Ctrl+Enter off macOS) submits. `EditResponse::submit_mods` holds the
@@ -304,8 +312,9 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
}
}
/// The completion list under the field, over what the text adapter holds.
/// The edit menu, and the completion list under the field, over what the text adapter holds.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
crate::menu::text_menu(ui, cx, &self.options);
if self.options.complete.is_some() {
completions::show(ui, cx, &text_part::<C::Value>(), self.options.complete_on_enter);
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn a_letter_no_row_takes_while_a_menu_is_open_does_not_reach_the_text_field_unde
let held = text.clone();
let mut fixture = Fixture::new(move |ui| {
let mut value = held.borrow_mut();
let field = craft_ui::text::TextField::new("Name", craft_ui::contract::Bind::bound(&mut *value)).show(ui);
let field = craft_ui::text::TextField::new("Name", craft_ui::contract::Bind::bound(&mut *value)).own_context_menu().show(ui);
Menu::context("Field menu", &field.response).show(ui, |ui, _| {
MenuItem::new("Copy").show(ui);
MenuItem::new("Paste").show(ui);
@@ -0,0 +1,124 @@
//! The edit menu of a text part: a right click opens Undo, Cut, Copy, Paste, Delete and Select All over the field;
//! the open menu takes Escape and gives the field back its typing run; a picked row and an Edit command fired from
//! elsewhere (a menu bar, the palette) both reach the focused field through the same command route.
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::commands::{EditCommands, FireSource, fire};
use craft_ui::testing::{Fixture, pointer, trial};
use craft_ui::text::TextField;
use egui::{Id, Key, Modifiers};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// A text field holding "hello" with the focus and a typing run.
struct Rig {
fixture: Fixture,
text: Rc<RefCell<String>>,
field: Rc<Cell<Id>>,
}
fn rig() -> Rig {
let text = Rc::new(RefCell::new("hello".to_owned()));
let field = Rc::new(Cell::new(Id::NULL));
let (held, id) = (text.clone(), field.clone());
let mut fixture = Fixture::new(move |ui| {
id.set(TextField::new("Name", Bind::bound(&mut *held.borrow_mut())).show(ui).response.id);
});
fixture.settle();
let name = fixture.by_label("Name").expect("the text field");
fixture.click(&name);
fixture.settle();
Rig { fixture, text, field }
}
impl Rig {
fn right_click_in_the_field(&mut self) {
let at = self.fixture.by_label("Name").expect("the field").center();
self.fixture.frame(vec![pointer::secondary(at, true)]);
self.fixture.frame(vec![pointer::secondary(at, false)]);
self.fixture.settle();
}
fn menu_open(&self) -> bool {
self.fixture.by_label("Select All").is_some()
}
/// What the frames that deliver `events`, one per frame, and the idle frames after them put on the clipboard.
fn copied_through(&mut self, events: Vec<egui::Event>) -> Vec<String> {
let mut copied = Vec::new();
for event in events.into_iter().map(Some).chain(std::iter::repeat_n(None, 8)) {
self.fixture.frame(event.into_iter().collect());
copied.extend_from_slice(self.fixture.copied());
}
copied
}
fn focus_in_the_field(&self) -> bool {
self.fixture.focused_stop().map(|(id, _)| id) == Some(self.field.get())
}
}
#[trial]
fn a_right_click_opens_the_edit_menu_and_its_cut_cuts_the_selection() {
let mut rig = rig();
rig.fixture.key(Key::A, Modifiers::COMMAND);
rig.fixture.settle();
rig.right_click_in_the_field();
assert!(rig.menu_open(), "a right click in the field opens its edit menu");
for row in ["Undo", "Cut", "Copy", "Paste"] {
assert!(rig.fixture.by_label(row).is_some(), "the edit menu has {row}");
}
let cut = rig.fixture.by_label("Cut").expect("the Cut row").center();
let copied = rig.copied_through(vec![pointer::moved(cut), pointer::press(cut), pointer::release(cut)]);
assert_eq!(copied, ["hello"], "Cut puts the selection on the clipboard");
rig.fixture.settle();
assert_eq!(*rig.text.borrow(), "", "and takes it out of the field");
assert!(!rig.menu_open(), "the pick closes the menu");
assert!(rig.focus_in_the_field(), "the focus is back in the field");
}
#[trial]
fn escape_closes_the_edit_menu_and_the_field_keeps_its_typing_run() {
let mut rig = rig();
rig.fixture.type_text("abc");
rig.fixture.settle();
assert_eq!(*rig.text.borrow(), "helloabc", "the typing reaches the field");
rig.right_click_in_the_field();
assert!(rig.menu_open(), "the edit menu is open");
rig.fixture.key(Key::Escape, Modifiers::NONE);
rig.fixture.settle();
assert!(!rig.menu_open(), "Escape closes the menu");
assert!(rig.focus_in_the_field(), "the focus is back in the field");
assert_eq!(*rig.text.borrow(), "helloabc", "the Escape the menu took leaves the draft alone");
rig.fixture.type_text("d");
rig.fixture.settle();
assert_eq!(*rig.text.borrow(), "helloabcd", "typing goes on in the field");
rig.fixture.key(Key::Escape, Modifiers::NONE);
rig.fixture.settle();
assert_eq!(*rig.text.borrow(), "hello", "the field's own Escape still restores the value from before its run");
}
#[trial]
fn an_edit_command_fired_from_elsewhere_reaches_the_focused_field() {
let mut rig = rig();
rig.fixture.key(Key::A, Modifiers::COMMAND);
rig.fixture.settle();
assert!(fire(rig.fixture.ctx(), EditCommands::Cut, FireSource::Pointer), "Cut runs while the field has a selection");
assert_eq!(rig.copied_through(Vec::new()), ["hello"], "the fired Cut cuts the field's selection");
rig.fixture.settle();
assert_eq!(*rig.text.borrow(), "");
}
/// The Delete row deletes the field's selection: the command reaches the focused text part as its edit, not the app.
#[trial]
fn the_edit_menus_delete_deletes_the_selection_in_the_field() {
let mut rig = rig();
rig.fixture.key(Key::A, Modifiers::COMMAND);
rig.fixture.settle();
rig.right_click_in_the_field();
let delete = rig.fixture.by_label("Delete").expect("the Delete row");
rig.fixture.click(&delete);
rig.fixture.settle();
assert_eq!(*rig.text.borrow(), "", "Delete takes the selection out of the field");
assert!(rig.focus_in_the_field(), "the focus is back in the field");
}
+1
View File
@@ -1,5 +1,6 @@
mod access;
mod chips;
mod edit_menu;
mod fields;
mod hex;
mod kit;