From 4d6ff42eb7d6c49a7d04a196eb4d62ad2f8140ca Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 11 Nov 2026 23:42:58 +0000 Subject: [PATCH] Selection parts: read-only text any component can make selectable PartsCx::selectable_text declares a run as a selection part with a press-only stop in no group; step 8b gives the focused one Select All and Copy; and PaintUi::selectable_text shows it through the text widget with the run's own galley, in the state's colours. Notice title and message, MetadataTable values (ListRow::cell_selectable) and SelectableText use it. SelectableText loses its Bind and Input::Text path and becomes a label whose value is its text. The suite presses the focus registration's press-only stops when Tab reaches nothing, instead of guessing from Input::Text and a read-only node. --- crates/menu/tests/it/native.rs | 2 +- crates/ui-contract/src/contract/cx/context.rs | 2 + crates/ui-contract/src/contract/paint_ui.rs | 60 +++++++++- crates/ui-contract/src/contract/run.rs | 6 + crates/ui-contract/src/contract/run/typed.rs | 1 + .../ui-contract/src/contract/steps/parts.rs | 9 +- .../ui-contract/src/contract/steps/stops.rs | 8 ++ crates/ui-contract/src/contract/text.rs | 56 ++++++++- crates/ui-contract/src/primitives/draw.rs | 10 +- .../src/primitives/text_adapter.rs | 24 +++- .../ui-contract/src/runtime/egui/text_edit.rs | 14 ++- crates/ui-contract/src/runtime/focus.rs | 6 + crates/ui-contract/src/testing/fixture.rs | 7 ++ crates/ui-contract/src/testing/suite/drive.rs | 32 +++--- .../ui-contract/src/testing/suite/states.rs | 2 +- .../ui-contract/src/testing/suite/variants.rs | 2 +- .../src/patterns/form_dialogs/properties.rs | 2 +- crates/ui-widgets/src/list/row.rs | 11 ++ crates/ui-widgets/src/list/row/paint.rs | 38 ++++-- crates/ui-widgets/src/list/row/show.rs | 9 +- crates/ui-widgets/src/notices/notice.rs | 19 ++- crates/ui-widgets/src/table/metadata.rs | 3 +- crates/ui-widgets/src/text/selectable_text.rs | 101 +++++++++------- .../src/text/selectable_text/stories.rs | 4 +- crates/ui-widgets/tests/it/text/selectable.rs | 108 +++++++++++++++++- docs/authoring.md | 2 + 26 files changed, 437 insertions(+), 101 deletions(-) diff --git a/crates/menu/tests/it/native.rs b/crates/menu/tests/it/native.rs index 6e543fc75..55515a0c9 100644 --- a/crates/menu/tests/it/native.rs +++ b/crates/menu/tests/it/native.rs @@ -92,7 +92,7 @@ fn through_in(menu: &mut NativeMenu, frames: &mut Frames, events: Vec impl FnMut(&mut egui::Ui) + use<> { let rect = Rc::new(Cell::new(egui::Rect::NOTHING)); let shown = rect.clone(); - let mut show = move |ui: &mut egui::Ui| shown.set(SelectableText::new("Note", "read me").id_salt("note").show(ui).response.rect); + let mut show = move |ui: &mut egui::Ui| shown.set(SelectableText::new("Note", "read me").id_salt("note").show(ui).rect); frames.idle(3, &mut show); click(frames, rect.get().center(), &mut show); frames.frame(vec![key_press(Key::A, Modifiers::COMMAND)], &mut show); diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index e74fc3908..6091e8622 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -158,6 +158,8 @@ pub struct CxCore<'a> { pub(crate) gestures: crate::contract::collection::Gestures, /// The text part's result of this pass, from step 8b. pub(crate) texts: Option<(PartKey, Box)>, + /// The selection parts step 7 declared, which `PaintUi::selectable_text` shows. + pub(crate) selections: Vec, /// Where the text part reserved the surface in the painter, so the field's surface paints beneath its text. pub(crate) surface_slot: Option, /// The editor part as step 8b set it up. diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 9960d23d3..e71b11c00 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -6,10 +6,11 @@ use super::label::{self, LeafLabel}; use super::run::{self, FaceSource, ShowAt}; use super::{ContentPainter, Cx, Show, TipFn}; use crate::primitives::sensing::PartResults; -use crate::primitives::{ContentPainterCx, Draw, DrawEnv, PaintRecord}; +use crate::primitives::{ContentPainterCx, Draw, DrawEnv, PaintRecord, TextRun, Wrap}; use crate::runtime::access; -use crate::runtime::egui::{alloc, child}; +use crate::runtime::egui::{alloc, child, focus as egui_focus, text_edit}; use crate::runtime::env::{Env, Label}; +use crate::runtime::focus::KeepKeys; use crate::runtime::layout_memory; use crate::runtime::memory::sub; use crate::style::{Flags, Ink, Stateful, StyleColor, StyleCx}; @@ -43,6 +44,8 @@ pub struct PaintUi<'a> { /// The composite's resolved enabled state and size, which the children it builds inherit. pub(crate) enabled: bool, pub(crate) size: ControlSize, + /// The selection parts step 7 declared. + pub(crate) selections: &'a [PartRef], /// The children's `Ui`, built on the first child under `sub(id, "children")`. pub(crate) kids: Option, } @@ -54,6 +57,59 @@ impl PaintUi<'_> { .text_direction(self.env.text_direction) } + /// Shows the selection part `part` (`PartsCx::selectable_text`): `run` in `rect`, painted as `Draw::text` + /// paints it, with the selection behind its characters; a line wider than `rect` is cut at its edge. A part step 7 did not declare (a face, an inert + /// component) paints as plain text. + pub fn selectable_text(&mut self, part: impl Into, rect: Rect, run: &TextRun<'_>) { + let part = part.into(); + if !self.selections.contains(&part) { + self.draw().text(rect, run); + return; + } + let (layout, at) = self.draw().place_text(rect, run); + self.record.borrow_mut().baseline.get_or_insert(at.y + layout.first_baseline); + let ctx = self.ui.ctx().clone(); + let widget = super::text::selection_id(self.id, part); + let multiline = run.wrap == Wrap::Wrap; + let keep = if multiline { KeepKeys::BlockArrows } else { KeepKeys::InlineArrows }; + let mut shown = layout.full.clone(); + // A line longer than its room is cut at the room's edge, as a field's is. + let mut cut = (layout.size().x > rect.width()).then(|| { + let mut cut = alloc::child(self.ui, egui::UiBuilder::new().max_rect(rect)); + cut.set_clip_rect(rect.intersect(cut.clip_rect())); + cut + }); + text_edit::show( + cut.as_mut().unwrap_or(&mut *self.ui), + text_edit::Edit { + id: widget, + rect: layout.galley.rect.translate(at.to_vec2()), + text: &mut shown, + read_only: true, + enabled: self.enabled, + focusable: self.enabled, + pointer: true, + multiline, + password: false, + hint: None, + mono: false, + role: run.role, + ink: crate::style::ink_color(&self.env.tokens, self.ink), + filter: egui_focus::event_filter(keep, false), + char_limit: None, + preedit: None, + rtl: false, + centred: false, + caret_visible: false, + underline: 0.0, + galley: Some(layout.galley.clone()), + }, + ); + if crate::runtime::egui::access::enabled(&ctx, widget) { + crate::runtime::egui::access::fold_widget(&ctx, widget, self.id); + } + } + /// The content-paint API for painting `part`: as [`draw`](Self::draw), and when the part was declared /// [`inactive`](super::PartBuilder::inactive) its data fills and strokes use the theme's disabled fill. pub fn draw_part(&self, part: impl Into) -> Draw<'_> { diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index d2adb00ed..ac0322f3d 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -370,6 +370,7 @@ fn blank_core<'a>( visible_rows: 0..0, gestures: Default::default(), texts: None, + selections: Vec::new(), surface_slot: None, editor: None, editor_inputs: Vec::new(), @@ -549,6 +550,7 @@ pub(super) fn paint_ui<'a>(ui: &'a mut Ui, env: &'a Env, core: &'a CxCore<'_>, s flags: core.state.flags & HOST_FLAGS, enabled: core.resolved.enabled, size: core.resolved.size, + selections: &core.selections, kids: None, } } @@ -927,6 +929,10 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h let keys = text_keys.unwrap_or_else(|| e.keys()); e.editor(ui, &mut parts.text, keys); } + if !parts.text.selections.is_empty() { + super::text::run_selections(e.core(), &parts.text.selections); + e.core().selections = parts.text.selections.iter().map(|decl| decl.part).collect(); + } // 9 update p.trace.mark(Step::Update); e.gesture_gate(); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index c92c7f574..233cea1b4 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -632,6 +632,7 @@ pub(crate) fn paint_face(ui: &mut Ui, env: &Env, source: &super::FaceSo flags: crate::style::Flags::empty(), enabled: step1.enabled && source.enabled, size: step1.size, + selections: &[], kids: None, }; face.paint(&mut pui, &cx); diff --git a/crates/ui-contract/src/contract/steps/parts.rs b/crates/ui-contract/src/contract/steps/parts.rs index af24e3d95..455ffc0d7 100644 --- a/crates/ui-contract/src/contract/steps/parts.rs +++ b/crates/ui-contract/src/contract/steps/parts.rs @@ -13,9 +13,14 @@ pub(crate) struct PartsStep { pub text: crate::contract::text::TextStep, } -/// Whether step 7 declared no parts, no roving group, no scroll part and no text or editor part. +/// Whether step 7 declared no parts, no roving group, no scroll part and no text, editor or selection part. pub(crate) fn declares_none(parts: &PartsStep) -> bool { - parts.decls.is_empty() && parts.rovings.is_empty() && parts.scrolls.is_empty() && parts.text.decl.is_none() && parts.text.editor.is_none() + parts.decls.is_empty() + && parts.rovings.is_empty() + && parts.scrolls.is_empty() + && parts.text.decl.is_none() + && parts.text.editor.is_none() + && parts.text.selections.is_empty() } /// Step 7's finding (22.4): a part that senses `CLICK` or `DRAG` is focusable, declares its keyboard path, or names diff --git a/crates/ui-contract/src/contract/steps/stops.rs b/crates/ui-contract/src/contract/steps/stops.rs index 3a2ce74a3..1038e350b 100644 --- a/crates/ui-contract/src/contract/steps/stops.rs +++ b/crates/ui-contract/src/contract/steps/stops.rs @@ -82,6 +82,14 @@ pub(crate) fn register_stops(input: &StopsIn<'_>) -> Vec { if input.focusable { focus::register_stop(ctx, if let Some(group) = input.group.or(input.row) { own().in_group(group) } else { own() }); } + // A selection part is a press-only stop in no group: neither Tab nor the arrows reach it. + if input.parts_focus { + for decl in &input.parts.text.selections { + let widget = crate::contract::text::selection_id(input.id, decl.part); + let stop = Stop::new(input.id, decl.keys()).part(decl.part).root(widget).in_body(input.body).press_only(); + focus::register_stop(ctx, stop); + } + } let mut after_header = Vec::new(); for (decl, extras) in &input.parts.decls { if extras.focusable && input.parts_focus { diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 29217aeb6..9f8a7185a 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -1,15 +1,22 @@ //! The text part of the pipeline (18.2): `PartsCx::text` registers the part with its typing run, and step 8b runs the //! text adapter, then the typing run over what the adapter recorded, and applies the run's events through `Cx`. +//! +//! Selection parts are read-only text with no typing run, any number per component: `PartsCx::selectable_text` +//! declares one and its press-only stop, step 8b gives the focused one Select All and Copy, and +//! `PaintUi::selectable_text` shows it, so it paints in the state's colours. use super::cx::{Cx, PartsCx, RecordedText, gesture_key}; use super::{Component, Edit as _, Focus as _, Overlays as _, ValueOf}; use crate::primitives::text_adapter::{self as adapter, End, TextState}; -use crate::primitives::{TextKey, TextOptions, TextOutcome}; +use crate::primitives::{TextKey, TextOptions, TextOutcome, TextRun, Wrap}; use crate::runtime::access::text as text_access; +use crate::runtime::focus::{EditSet, KeepKeys, KeyUse}; use crate::runtime::keys; use crate::runtime::memory::sub; use crate::runtime::motion::Animate as _; -use craft_behavior::{CancelReason, Caret, Codec, EditRun, Ended, EscapeRule, Escaped, Gesture, NotAValue, PartKey, Typed, TypingRun}; +use craft_behavior::{ + CancelReason, Caret, Codec, EditCommand, EditRun, Ended, EscapeRule, Escaped, Gesture, NotAValue, PartKey, PartRef, Typed, TypingRun, +}; use craft_keymap::Mods; use egui::{Rect, Ui}; use std::any::Any; @@ -32,6 +39,40 @@ pub(crate) struct TextStep { pub commit_now: bool, pub decl: Option, pub editor: Option, + pub selections: Vec, +} + +/// A selection part as `PartsCx::selectable_text` declared it. +pub(crate) struct SelectDecl { + pub part: PartRef, + pub text: String, + /// The text wraps: the arrows move the caret between lines. + pub multiline: bool, +} + +impl SelectDecl { + /// The keys a focused selection part keeps: a read-only text's, with Select All and Copy its only edit commands. + pub(crate) fn keys(&self) -> KeyUse { + let keys = KeyUse::of(crate::contract::Input::Text).with_edits(EditSet::NONE.with(EditCommand::SelectAll).with(EditCommand::Copy)); + if self.multiline { keys.with_keep(KeepKeys::BlockArrows) } else { keys } + } +} + +/// The egui text widget of the selection part `part` of component `id`, which holds key focus. +pub(crate) fn selection_id(id: egui::Id, part: PartRef) -> egui::Id { + sub(id, ("selection", part.key, part.index)) +} + +/// Step 8b for selection parts: the focused one takes this pass's Select All and Copy. +pub(crate) fn run_selections(core: &mut super::cx::CxCore<'_>, selections: &[SelectDecl]) { + let ctx = core.ctx.clone(); + let Some(focused) = selections.iter().find(|decl| crate::runtime::egui::focus::has_focus(&ctx, selection_id(core.id, decl.part))) else { + return; + }; + let widget = selection_id(core.id, focused.part); + while let Some(command) = core.intents.take_edit() { + adapter::select_or_copy(&ctx, widget, &focused.text, command); + } } pub(crate) struct TextDecl { @@ -188,6 +229,17 @@ fn resolver(codec: K, options: &TextOptions, rect: R } impl PartsCx<'_, C> { + /// Declares `run` as a selection part: read-only text that a press focuses, drag and double click select and Copy + /// copies, and that Tab and F6 pass over. `paint` shows it with `PaintUi::selectable_text` and the same run in + /// the state's colours. Its text is the component's own: it has no node of its own, so the component's node + /// names it. An elided run cannot be one, since the selection counts the characters shown. + pub fn selectable_text(&mut self, part: impl Into, run: &TextRun<'_>) { + debug_assert!(!matches!(run.wrap, Wrap::Elide | Wrap::ElidePath | Wrap::Clamp(_)), "a selection part shows its whole text"); + let part = part.into(); + debug_assert!(self.text.selections.iter().all(|decl| decl.part != part), "selection part {part:?} declared twice"); + self.text.selections.push(SelectDecl { part, text: run.full_text(), multiline: run.wrap == Wrap::Wrap }); + } + /// Registers the component's one text part (`INPUT = Input::Text`). pub fn text(&mut self, key: TextKey, rect: Rect, codec: &K, value: &K::Value, options: &TextOptions) { debug_assert!(self.text.decl.is_none(), "a component registers one text part"); diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index 877f52f32..95e9207da 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -200,12 +200,18 @@ impl<'a> Draw<'a> { /// vertically in a taller `rect`, so a label in a control or a row sits at the same place whatever the room; a /// wrapped run starts at the top. Records the elision and the first baseline. pub fn text(&self, rect: Rect, run: &TextRun<'_>) -> TextLayout { + let (layout, at) = self.place_text(rect, run); + self.galley(at, &layout); + layout + } + + /// `run` laid out in `rect`'s width, and where `text` paints it. + pub(crate) fn place_text(&self, rect: Rect, run: &TextRun<'_>) -> (TextLayout, Pos2) { let layout = run.layout(self.painter.ctx(), &self.text_env(), rect.width()); let at_end = self.text_direction == Direction::Rtl && !run.ltr; let x = if at_end { rect.right() - layout.size().x } else { rect.left() }; let spare = if layout.galley.rows.len() <= 1 { (rect.height() - layout.size().y).max(0.0) } else { 0.0 }; - self.galley(Pos2::new(x, rect.top() + spare / 2.0), &layout); - layout + (layout, Pos2::new(x, rect.top() + spare / 2.0)) } /// Paints a one-line `run` as `text` does, with the middle of its lowercase letters (the x-height) on the middle diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 457144beb..bd63c1036 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -215,16 +215,14 @@ fn apply(input: &mut AdapterIn<'_>, state: &mut TextState, text: &mut String, wi continue; } match command { - EditCommand::SelectAll => text_edit::select(ctx, widget, 0, text.chars().count()), - EditCommand::Copy | EditCommand::Cut => { + EditCommand::SelectAll | EditCommand::Copy => select_or_copy(ctx, widget, text, command), + EditCommand::Cut => { let (a, b) = selection(text); if a != b { let (lo, hi) = (a.min(b), a.max(b)); clipboard::copy_text(ctx, text[byte_of(text, lo)..byte_of(text, hi)].to_owned()); - if command == EditCommand::Cut { - replace_selection(ctx, widget, text, (lo, hi), ""); - changed = true; - } + replace_selection(ctx, widget, text, (lo, hi), ""); + changed = true; } } EditCommand::Paste => { @@ -250,6 +248,19 @@ fn apply(input: &mut AdapterIn<'_>, state: &mut TextState, text: &mut String, wi changed } +/// Select All or Copy on the text widget `widget` showing `text`: the edit commands read-only text takes. +pub(crate) fn select_or_copy(ctx: &Context, widget: Id, text: &str, command: EditCommand) { + match command { + EditCommand::SelectAll => text_edit::select(ctx, widget, 0, text.chars().count()), + EditCommand::Copy => { + let Some((a, b)) = text_edit::selection(ctx, widget).filter(|(a, b)| a != b) else { return }; + let (lo, hi) = (a.min(b), a.max(b)); + clipboard::copy_text(ctx, text[byte_of(text, lo)..byte_of(text, hi)].to_owned()); + } + _ => {} + } +} + /// The selection of the text widget `id` as character indices, `(caret, anchor)`. pub(crate) fn selection(ctx: &Context, id: Id) -> Option<(usize, usize)> { text_edit::selection(ctx, id) @@ -317,6 +328,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut centred: input.options.centred, caret_visible: input.caret_visible, underline: input.underline, + galley: None, }; let shown = text_edit::show(input.ui, edit); // egui's own IME output is dropped: the engine writes the pass's. diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index e4acc6d9d..8a6a79140 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -37,6 +37,9 @@ pub(crate) struct Edit<'a> { pub caret_visible: bool, /// The width of the preedit underline. pub underline: f32, + /// The text laid out already, as a run is painted: the widget shows this galley, which never scrolls, so the text + /// is not clipped to `rect`. + pub galley: Option>, } /// What the widget did in one pass. @@ -82,6 +85,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { centred, caret_visible, underline, + galley, } = edit; // The same font and optical size as a label of the same role: one text path. let env = crate::runtime::env::Env::of(ui); @@ -94,6 +98,9 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { let had_focus = ui.memory(|memory| memory.has_focus(id)); let entered = had_focus && ui.input(|input| input.key_pressed(egui::Key::Enter)); let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, wrap_width: f32| { + if let Some(galley) = &galley { + return galley.clone(); + } // egui masks only in its own layouter: a custom one lays out what it is given, so the dots are made here. The // preedit range counts bytes of the real text, so a masked field shows no preedit underline. let masked; @@ -129,7 +136,9 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { let output = { let ui = &mut super::alloc::child(ui, egui::UiBuilder::new().max_rect(rect)); // The text shows only inside the text part, however wide the line is. - ui.set_clip_rect(rect.intersect(ui.clip_rect())); + if galley.is_none() { + ui.set_clip_rect(rect.intersect(ui.clip_rect())); + } if !enabled && !focusable { super::style::disable_without_fade(ui); } @@ -154,7 +163,10 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { .event_filter(filter) .return_key(if multiline { Some(egui::KeyboardShortcut::new(egui::Modifiers::NONE, egui::Key::Enter)) } else { None }) .layouter(&mut layouter) + // A laid-out galley sits at the rect's corner, as a painted run does: egui's own row height + // (its default font's) would otherwise centre it lower. .align(match (centred, rtl) { + _ if galley.is_some() => egui::Align2::LEFT_TOP, (true, _) => egui::Align2::CENTER_CENTER, (false, true) => egui::Align2::RIGHT_CENTER, (false, false) => egui::Align2::LEFT_CENTER, diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 4394ab7b8..20d9e77f2 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -452,6 +452,12 @@ pub(crate) fn focused_stop(ctx: &Context) -> Option { }) } +/// The egui widgets that hold focus for last pass's press-only stops, which only a press reaches, in stop order. +#[cfg(feature = "testing")] +pub(crate) fn press_only_roots(ctx: &Context) -> Vec { + with(ctx, |state| state.last_stops.iter().filter(|rec| rec.stop.press_only).map(|rec| rec.stop.root).collect()) +} + /// The stop this pass's press takes focus for. The end hook moves focus there, after a layer the press opens has /// recorded its opener. pub(crate) fn pressed_stop(ctx: &Context) -> Option { diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index 01f521d63..197e2521e 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -612,6 +612,13 @@ impl Fixture { crate::runtime::focus::focused_stop(&self.frames.ctx) } + /// Where the stops that only a press reaches sit (read-only text, selection parts), in stop order: the bounds of + /// the egui widget that holds each one's focus. + pub fn press_only_stops(&self) -> Vec { + let ctx = &self.frames.ctx; + crate::runtime::focus::press_only_roots(ctx).into_iter().filter_map(|root| ctx.read_response(root).map(|response| response.rect)).collect() + } + /// The key role of the stop that holds focus: which key rows it takes (type-ahead, rename, reorder). pub fn focused_role(&self) -> Option { crate::runtime::focus::focused_rec(&self.frames.ctx).map(|rec| rec.stop.role) diff --git a/crates/ui-contract/src/testing/suite/drive.rs b/crates/ui-contract/src/testing/suite/drive.rs index b1aee6285..46ce543c1 100644 --- a/crates/ui-contract/src/testing/suite/drive.rs +++ b/crates/ui-contract/src/testing/suite/drive.rs @@ -98,16 +98,22 @@ pub(super) fn variant_name(plan: Plan, variant: usize) -> &'static str { } } -/// Tab once; when that focuses nothing and the shown component is read-only text, which Tab passes over, a press on -/// it, from which it takes focus. -pub(super) fn tab_or_press(fixture: &mut Fixture, text: bool) { +/// Tab once; when that focuses nothing, a press on the first stop that only a press reaches (read-only text), which +/// Tab passes over. +pub(super) fn tab_or_press(fixture: &mut Fixture) { fixture.key(Key::Tab, Modifiers::NONE); - let root = root_target(fixture); - if text && fixture.focused().is_none() && fixture.tree().data_of(root.node).is_some_and(|node| node.is_read_only()) { - fixture.click(&root); + if fixture.focused().is_none() { + press_only_stop(fixture); } } +/// Presses the first stop that only a press reaches; `false` when there is none. +fn press_only_stop(fixture: &mut Fixture) -> bool { + let Some(rect) = fixture.press_only_stops().first().copied() else { return false }; + fixture.click_at(rect.center()); + true +} + /// The node of the shown component, or the whole shown area when it has none. pub(super) fn root_target(fixture: &Fixture) -> Target { fixture.root_id().and_then(|id| fixture.node_of(id)).unwrap_or(Target { node: NodeKey::of(Id::NULL), rect: fixture.shown() }) @@ -197,8 +203,9 @@ fn pick(fixture: &mut Fixture, row: usize, by_click: bool) { } /// Presses Tab until the focus is inside the subject (its root or a descendant), for at most one cycle of the stops. -/// A story whose first stops belong to something else (an editor inside a canvas) still gets its text. Read-only -/// text, which Tab passes over, gets a press instead. `false` when neither reaches the subject. +/// A story whose first stops belong to something else (an editor inside a canvas) still gets its text. A subject that +/// only a press reaches (read-only text), which Tab passes over, gets a press instead. `false` when neither reaches +/// the subject. /// /// The focus is inside when the focus service's stop is the subject's component or AccessKit's focused node lies in /// the subject's node subtree. @@ -217,14 +224,7 @@ pub(super) fn focus_subject(fixture: &mut Fixture) -> bool { } let at = (stop, focused); if seen.contains(&at) { - let read_only = - |fixture: &Fixture| root.as_ref().is_some_and(|root| fixture.tree().data_of(root.node).is_some_and(|node| node.is_read_only())); - if !read_only(fixture) { - return false; - } - let target = root_target(fixture); - fixture.click(&target); - return fixture.focused_stop().is_some_and(|(id, _)| id == root_id); + return press_only_stop(fixture) && fixture.focused_stop().is_some_and(|(id, _)| id == root_id); } seen.push(at); fixture.key(Key::Tab, Modifiers::NONE); diff --git a/crates/ui-contract/src/testing/suite/states.rs b/crates/ui-contract/src/testing/suite/states.rs index 6f0a1fb65..ac3ccbddf 100644 --- a/crates/ui-contract/src/testing/suite/states.rs +++ b/crates/ui-contract/src/testing/suite/states.rs @@ -129,7 +129,7 @@ fn focusable_stories_are_tab_reachable(subject: &Subject) -> Result<(), String> continue; } let mut fixture = super::drive::input_fixture(story); - super::drive::tab_or_press(&mut fixture, matches!(subject.probe.input, craft_behavior::Input::Text | craft_behavior::Input::Editor)); + super::drive::tab_or_press(&mut fixture); if fixture.focused().is_none() { return Err(format!("{}: neither Tab nor a press on read-only text reached anything", story.name)); } diff --git a/crates/ui-contract/src/testing/suite/variants.rs b/crates/ui-contract/src/testing/suite/variants.rs index 3bcadaad2..a2b9a2caa 100644 --- a/crates/ui-contract/src/testing/suite/variants.rs +++ b/crates/ui-contract/src/testing/suite/variants.rs @@ -105,7 +105,7 @@ fn read_only_changes_nothing(subject: &Subject) -> Result<(), String> { } let before = fixture.data().snapshot(); fixture.take_outputs(); - tab_or_press(&mut fixture, is_text(subject)); + tab_or_press(&mut fixture); if focusable && fixture.focused().is_none() { return Err(format!("{}: a read-only story cannot take focus", story.name)); } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/properties.rs b/crates/ui-patterns/src/patterns/form_dialogs/properties.rs index ffd7b3e4a..1234edf5c 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/properties.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/properties.rs @@ -87,7 +87,7 @@ impl PropertiesTab { let (name, text) = (label.clone(), text.clone()); Param::custom(format!("properties.{at}.{row}"), label.clone(), move |ui, _, _| { let shown = Env::of(ui).view().resolve(&text); - SelectableText::new(name.clone(), shown.as_str()).multiline().show(ui).response + SelectableText::new(name.clone(), shown.as_str()).multiline().show(ui) }) } PropertyRow::Field(param) => (**param).clone(), diff --git a/crates/ui-widgets/src/list/row.rs b/crates/ui-widgets/src/list/row.rs index 894666853..cae164301 100644 --- a/crates/ui-widgets/src/list/row.rs +++ b/crates/ui-widgets/src/list/row.rs @@ -178,6 +178,8 @@ pub struct ListRow<'a> { pub(super) aligns: Vec<(ColumnKey, HAlign, bool)>, /// The columns that read in the muted look. pub(super) muted: Vec, + /// The columns whose wrapped text can be selected and copied. + pub(super) selectable: Vec, /// The toggle columns of the collection, from the item facts it records for the row: none of them holds the /// label, whether or not this row has a cell in it. pub(super) toggle_columns: Vec, @@ -253,6 +255,7 @@ impl<'a> ListRow<'a> { cells: Vec::new(), aligns: Vec::new(), muted: Vec::new(), + selectable: Vec::new(), toggle_columns: Vec::new(), toggle_keys: Vec::new(), toggles: Vec::new(), @@ -316,6 +319,14 @@ impl<'a> ListRow<'a> { self } + /// The wrapped text of the column `column` (`cell_lines`) can be selected and copied: a press on it focuses the + /// text instead of acting on the row, and Tab passes over it. + #[must_use] + pub fn cell_selectable(mut self, column: ColumnKey) -> Self { + self.selectable.push(column); + self + } + /// A toggle cell in the column `cell.column`; the collection flips it, the row shows it. #[must_use] pub fn toggle(mut self, cell: ToggleCell) -> Self { diff --git a/crates/ui-widgets/src/list/row/paint.rs b/crates/ui-widgets/src/list/row/paint.rs index bc267a368..b1777e83e 100644 --- a/crates/ui-widgets/src/list/row/paint.rs +++ b/crates/ui-widgets/src/list/row/paint.rs @@ -2,7 +2,8 @@ use super::ListRow; use super::placement::Placed; -use super::show::{TOGGLE, TRAILING}; +use super::show::{TEXT_CELL, TOGGLE, TRAILING}; +use super::style::ListRowStyle; use super::thumb::{RowThumb, target_at}; use super::trailing::{TrailingFace, TrailingItem, trailing_run}; use crate::buttons::IconButton; @@ -154,20 +155,33 @@ impl ListRow<'_> { impl ListRow<'_> { /// The text cells, inset and centred on the row's height, each aligned as its column says. - pub(super) fn paint_cells(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, placed: &Placed) { + /// The text cell `at` as a run in its column's look, without its colour. + pub(super) fn cell_run(&self, style: &ListRowStyle, at: usize) -> TextRun<'_> { + let text = &self.texts[at]; + let (align, numeric) = self.align_of(&text.column); + let mut span = Span::new(text.text.as_str()); + span.tabular = numeric; + let run = TextRun::spans(vec![span]).role(self.cell_look(style, &text.column).role).align(align); + if text.wrap { run.wrap(Wrap::Wrap) } else { run.elide() } + } + + /// Whether the text cell `at` is a selection part: wrapped text in a column `cell_selectable` names. + pub(super) fn cell_selects(&self, at: usize) -> bool { + let text = &self.texts[at]; + text.wrap && self.selectable.contains(&text.column) + } + + pub(super) fn paint_cells(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, placed: &Placed) { let sizes = &cx.style.sizes; let rtl = cx.env.direction().is_rtl(); - for (at, _, cell) in &placed.texts { + for (at, position, cell) in &placed.texts { let text = &self.texts[*at]; - let (align, numeric) = self.align_of(&text.column); + let (align, _) = self.align_of(&text.column); let look = self.cell_look(cx.style, &text.column); let cell = Rect::from_x_y_ranges(cell.x_range(), cx.rect.y_range()); let room = Flow::new(cell, rtl).span(sizes.cell_inset, sizes.cell_room(cell.width())); - let mut span = Span::new(text.text.as_str()); - span.tabular = numeric; - let run = TextRun::spans(vec![span]).role(look.role).color(cx.resolve(&look.color)).align(align); - let run = if text.wrap { run.wrap(Wrap::Wrap) } else { run.elide() }; - let layout = draw.layout(&run, room.width()); + let run = self.cell_run(cx.style, *at).color(cx.resolve(&look.color)); + let layout = ui.draw().layout(&run, room.width()); let top = if text.wrap { room.top() + ((room.height() - layout.size().y) / 2.0).max(0.0) } else { room.center().y - sizes.label_line / 2.0 }; let free = (room.width() - layout.size().x).max(0.0); @@ -177,7 +191,11 @@ impl ListRow<'_> { HAlign::End => free, }; let x = if rtl { room.right() - layout.size().x - inset } else { room.left() + inset }; - draw.galley(Pos2::new(x, top), &layout); + if self.cell_selects(*at) { + ui.selectable_text(TEXT_CELL.at(*position as u64), Rect::from_min_size(Pos2::new(x, top), layout.size()), &run); + } else { + ui.draw().galley(Pos2::new(x, top), &layout); + } } } } diff --git a/crates/ui-widgets/src/list/row/show.rs b/crates/ui-widgets/src/list/row/show.rs index 768280724..efa125631 100644 --- a/crates/ui-widgets/src/list/row/show.rs +++ b/crates/ui-widgets/src/list/row/show.rs @@ -27,7 +27,7 @@ use craft_theme::{Rgba, RowStyle, Stateful, TypeRole}; use egui::{CornerRadius, Pos2, Rect, Vec2}; pub(super) const TOGGLE: PartKey = PartKey::new("toggle"); -const TEXT_CELL: PartKey = PartKey::new("text-cell"); +pub(super) const TEXT_CELL: PartKey = PartKey::new("text-cell"); const TOGGLE_CELL: PartKey = PartKey::new("toggle-cell"); const LABEL_CELL: PartKey = PartKey::new("label-cell"); const DISCLOSURE: PartKey = PartKey::new("disclosure"); @@ -194,6 +194,11 @@ impl Component for ListRow<'_> { None => part, }; } + for (at, position, _) in &placed.texts { + if self.cell_selects(*at) { + cx.selectable_text(TEXT_CELL.at(*position as u64), &self.cell_run(cx.style, *at)); + } + } if let Some(disclosure) = placed.disclosure { let words = cx.words::(); let tip = if self.group == Some(true) { words.collapse_tip.clone() } else { words.expand_tip.clone() }; @@ -450,7 +455,7 @@ impl Component for ListRow<'_> { if let Some(fraction) = self.progress { ui.face(PROGRESS, Progress::new(fraction)); } - self.paint_cells(&ui.draw(), cx, &placed); + self.paint_cells(ui, cx, &placed); self.paint_trailing(ui, cx, &placed); } diff --git a/crates/ui-widgets/src/notices/notice.rs b/crates/ui-widgets/src/notices/notice.rs index 07b144c9c..aa00eaa9f 100644 --- a/crates/ui-widgets/src/notices/notice.rs +++ b/crates/ui-widgets/src/notices/notice.rs @@ -96,6 +96,9 @@ const ACTION: PartKey = PartKey::new("action"); const DISMISS: PartKey = PartKey::new("dismiss"); /// The title's band; the centred layout names it as a heading. const TITLE: PartKey = PartKey::new("title"); +/// The title's text and the message's: selection parts. +const TITLE_TEXT: PartKey = PartKey::new("title_text"); +const MESSAGE: PartKey = PartKey::new("message"); /// The heading level of the centred title: the empty state's top-level heading. const TITLE_LEVEL: usize = 1; const DISMISS_ICON: &str = "close"; @@ -137,7 +140,7 @@ const READING_WIDTH: f32 = 460.0; /// A message in a tone. The tone picks the icon and the colours; the neutral tone reads muted and has no icon. The /// message is the label; a title above it is optional. Actions read as links (as buttons in the centred layout) and /// are reported in the output; with `dismiss` a close button is the last part. With `announce` set, the first show is -/// announced once. +/// announced once. The title and message wrap and can be selected and copied; Tab passes over them. #[derive(crate::contract::Component, crate::contract::Props)] pub struct Notice<'a> { #[common] @@ -444,6 +447,13 @@ impl Component for Notice<'_> { { cx.part(TITLE, title).sense(Sense::HOVER); } + if let Some(title) = texts.title.as_deref().filter(|_| placed.title.is_some()) { + cx.selectable_text(TITLE_TEXT, &self.run(title, cx.style.title.role)); + } + if placed.message.is_some() { + let role = if self.title.is_some() { cx.style.detail.role } else { cx.style.message.role }; + cx.selectable_text(MESSAGE, &self.run(texts.message, role)); + } let default = self.actions.iter().rposition(|action| action.default); for (at, rect) in placed.actions.iter().enumerate() { let part = cx.part(ACTION.at(at as u64), *rect).sense(Sense::CLICK | Sense::FOCUS).focusable(); @@ -524,21 +534,20 @@ impl Component for Notice<'_> { if placed.dismiss.is_some() { ui.face(DISMISS, IconButton::new(IconId::new(DISMISS_ICON)).label(words.dismiss.clone())); } - let draw = ui.draw(); if let (Some(rect), Some(mut spec)) = (placed.icon, self.icon_spec()) { if spec.color.is_none() { spec.color = Some(cx.resolve(&cx.style.icon.color)); } - draw.icon(rect, &spec); + ui.draw().icon(rect, &spec); } if let (Some(rect), Some(title)) = (placed.title, self.title.as_ref()) { let run = self.run(cx.env.resolve(title).as_str(), cx.style.title.role); - draw.text(rect, &run.color(cx.resolve(&cx.style.title.color))); + ui.selectable_text(TITLE_TEXT, rect, &run.color(cx.resolve(&cx.style.title.color))); } let look = if self.title.is_some() { &cx.style.detail } else { &cx.style.message }; if let Some(message) = placed.message { let run = self.run(cx.resolved.label, look.role); - draw.text(message, &run.color(cx.resolve(&look.color))); + ui.selectable_text(MESSAGE, message, &run.color(cx.resolve(&look.color))); } } diff --git a/crates/ui-widgets/src/table/metadata.rs b/crates/ui-widgets/src/table/metadata.rs index c0c26fcd3..f23a19664 100644 --- a/crates/ui-widgets/src/table/metadata.rs +++ b/crates/ui-widgets/src/table/metadata.rs @@ -270,7 +270,8 @@ impl<'a> MetadataTable<'a> { .cells(icx.cells()) .striped(icx.row.striped) .cell_muted(NAME) - .cell_lines(VALUE, row.value.clone()); + .cell_lines(VALUE, row.value.clone()) + .cell_selectable(VALUE); if checks { line.toggle(ToggleCell::check(SHOW, ToggleState::of(source.toggled(icx.at, &SHOW)), words.show_field.clone())) } else { diff --git a/crates/ui-widgets/src/text/selectable_text.rs b/crates/ui-widgets/src/text/selectable_text.rs index c941441a9..eee571e10 100644 --- a/crates/ui-widgets/src/text/selectable_text.rs +++ b/crates/ui-widgets/src/text/selectable_text.rs @@ -3,86 +3,103 @@ #[cfg(feature = "testing")] mod stories; -use super::text_part; -use crate::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PartsCx, Props as _, Role}; -use crate::primitives::{TextOptions, TextRun}; +use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, PartsCx, Props as _, Role, Styled as _}; +use crate::primitives::{Span, TextRun, Wrap}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx}; -use craft_behavior::{Insets, Metrics, PlainText, Sense}; -use egui::{Rect, Vec2}; +use crate::style::{ComponentStyle, StyleCx, TextLook, TypeRole}; +use craft_behavior::{Insets, Metrics, PartKey, Sense}; +use craft_theme::{Stateful, States}; +use egui::{Rect, Response, Vec2}; -/// The style of selectable text: padding from the control metrics, no surface. +/// The selection part that shows the text. +const TEXT: PartKey = PartKey::new("text"); + +/// The style of selectable text: padding from the control metrics, no surface, the body role in the normal text +/// colour. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct SelectableStyle { #[style(metrics)] metrics: Metrics, + #[style(text)] + text: TextLook, } -/// Read-only text the user can focus, select and copy. +/// Read-only text the user focuses with a press to select and copy, which Tab passes over. Its node is a label named +/// by `label`, with the text as its value. #[derive(crate::contract::Component)] -#[component(exempt(case = "state:Mixed", reason = "Read-only text has no mixed state."))] -#[component(exempt(case = "state:Invalid", reason = "Read-only text has no value a check can refuse."))] -#[component(exempt(case = "values", reason = "Read-only text has no value a drive can change."))] -pub struct SelectableText<'a> { +pub struct SelectableText { #[common] common: Common, - value: Bind<'a, String>, - options: TextOptions, + text: String, + wrap: Wrap, + mono: bool, } -impl SelectableText<'_> { +impl SelectableText { /// Selectable `text` named `label`. pub fn new(label: impl Into