mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 01:44:25 +00:00
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.
This commit is contained in:
@@ -92,7 +92,7 @@ fn through_in(menu: &mut NativeMenu, frames: &mut Frames, events: Vec<egui::Even
|
||||
fn selected_text(frames: &mut Frames) -> 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);
|
||||
|
||||
@@ -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<dyn TextResult>)>,
|
||||
/// The selection parts step 7 declared, which `PaintUi::selectable_text` shows.
|
||||
pub(crate) selections: Vec<craft_behavior::PartRef>,
|
||||
/// Where the text part reserved the surface in the painter, so the field's surface paints beneath its text.
|
||||
pub(crate) surface_slot: Option<egui::layers::ShapeIdx>,
|
||||
/// The editor part as step 8b set it up.
|
||||
|
||||
@@ -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<Ui>,
|
||||
}
|
||||
@@ -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<PartRef>, 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<PartRef>) -> Draw<'_> {
|
||||
|
||||
@@ -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<ShowAt>, 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();
|
||||
|
||||
@@ -632,6 +632,7 @@ pub(crate) fn paint_face<C: Show>(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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -82,6 +82,14 @@ pub(crate) fn register_stops(input: &StopsIn<'_>) -> Vec<Stop> {
|
||||
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 {
|
||||
|
||||
@@ -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<TextDecl>,
|
||||
pub editor: Option<super::editor::EditorDecl>,
|
||||
pub selections: Vec<SelectDecl>,
|
||||
}
|
||||
|
||||
/// 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<K: Codec + Clone + 'static>(codec: K, options: &TextOptions, rect: R
|
||||
}
|
||||
|
||||
impl<C: Component> 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<PartRef>, 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<K: Codec + Clone + 'static>(&mut self, key: TextKey<K::Value>, rect: Rect, codec: &K, value: &K::Value, options: &TextOptions) {
|
||||
debug_assert!(self.text.decl.is_none(), "a component registers one text part");
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<std::sync::Arc<egui::Galley>>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
|
||||
@@ -452,6 +452,12 @@ pub(crate) fn focused_stop(ctx: &Context) -> Option<StopKey> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<Id> {
|
||||
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<StopKey> {
|
||||
|
||||
@@ -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<Rect> {
|
||||
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<craft_behavior::KeyRole> {
|
||||
crate::runtime::focus::focused_rec(&self.frames.ctx).map(|rec| rec.stop.role)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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<ColumnKey>,
|
||||
/// The columns whose wrapped text can be selected and copied.
|
||||
pub(super) selectable: Vec<ColumnKey>,
|
||||
/// 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<ColumnKey>,
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::<ListWords>();
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<Label>, text: &str) -> Self {
|
||||
SelectableText { common: Common::new(), value: Bind::given(text.to_owned()), options: TextOptions::default() }.label(label).read_only(true)
|
||||
SelectableText { common: Common::new(), text: text.to_owned(), wrap: Wrap::Line, mono: false }.label(label)
|
||||
}
|
||||
|
||||
/// The text wraps over several lines.
|
||||
#[must_use]
|
||||
pub fn multiline(mut self) -> Self {
|
||||
self.options.lines = Some(usize::MAX);
|
||||
self.wrap = Wrap::Wrap;
|
||||
self
|
||||
}
|
||||
|
||||
/// Monospace text.
|
||||
#[must_use]
|
||||
pub fn mono(mut self) -> Self {
|
||||
self.options.mono = true;
|
||||
self.mono = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn run(&self, role: TypeRole) -> TextRun<'_> {
|
||||
let span = if self.mono { Span::new(self.text.as_str()).mono() } else { Span::new(self.text.as_str()) };
|
||||
TextRun::spans(vec![span]).role(role).wrap(self.wrap)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for SelectableText<'_> {
|
||||
const ROLE: Role = Role::TEXT_INPUT;
|
||||
const INPUT: crate::contract::Input = crate::contract::Input::Text;
|
||||
impl Component for SelectableText {
|
||||
const ROLE: Role = Role::LABEL;
|
||||
const INPUT: crate::contract::Input = crate::contract::Input::Display;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = SelectableStyle;
|
||||
type Output = EditResponse<String>;
|
||||
type Output = Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: SelectableTextStyleKey) -> SelectableStyle {
|
||||
SelectableStyle { metrics: Metrics::new().padding(Insets::horizontal(cx.control().pad_x)) }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let text = cx.value().map_or("", String::as_str);
|
||||
let run = TextRun::new(text);
|
||||
cx.layout(&if self.options.multiline() { run.wrap(crate::primitives::Wrap::Line) } else { run }).size()
|
||||
}
|
||||
|
||||
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
if let Some(value) = cx.value() {
|
||||
cx.text(text_part::<String>(), cx.content_rect, &PlainText, value, &self.options);
|
||||
let text = &cx.tokens.color.text;
|
||||
let color = cx.color(text.normal);
|
||||
let off = States::new(color, color, color, cx.color(text.disabled));
|
||||
SelectableStyle {
|
||||
metrics: Metrics::new().padding(Insets::horizontal(cx.control().pad_x)),
|
||||
text: TextLook::new(TypeRole::Body, Stateful::new(color).off(off)),
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, String>> {
|
||||
Some(self.value.reborrow())
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::HOVER
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<String> {
|
||||
cx.edit_response()
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
cx.layout(&self.run(cx.style.text.role)).size()
|
||||
}
|
||||
|
||||
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
cx.selectable_text(TEXT, &self.run(cx.style.text.role));
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.value(self.text.clone());
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
ui.selectable_text(TEXT, cx.content_rect, &self.run(cx.style.text.role).color(cx.resolve(&cx.style.text.color)));
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ use egui::Ui;
|
||||
|
||||
const LONG: &str = "A name that runs on well past the end of the field, so the field scrolls its text under the caret";
|
||||
|
||||
#[story(SelectableText<'static>, covers = [Default], drive = Drive::Never)]
|
||||
#[story(SelectableText, covers = [Default], drive = Drive::Never)]
|
||||
fn selectable_text(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
SelectableText::new("Path", "/projects/poster.indd").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(SelectableText<'static>, covers = [LongText], drive = Drive::Never)]
|
||||
#[story(SelectableText, covers = [LongText], drive = Drive::Never)]
|
||||
fn selectable_text_long(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
SelectableText::new("Path", LONG).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
//! `SelectableText`: read-only text the user focuses with a press to select and copy, which Tab passes over.
|
||||
//! Selection parts: read-only text the user focuses with a press to select and copy, which Tab passes over
|
||||
//! (`SelectableText`, a notice's title and message, a toast's text, a metadata table's values).
|
||||
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _};
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::{Bind, CollectionEvent, Props as _, Show as _};
|
||||
use craft_ui::notices::{Notice, NoticeAction, ToastStack};
|
||||
use craft_ui::runtime::toast;
|
||||
use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui::text::{SelectableText, TextField};
|
||||
use egui::{Event, Id, Key, Modifiers};
|
||||
use egui::{Event, Id, Key, Modifiers, Rect, Vec2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -19,7 +24,7 @@ fn tab_passes_over_read_only_text_and_a_press_selects_it_for_copy() {
|
||||
let seen = ids.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
seen[0].set(TextField::new("Before", Bind::given(String::new())).id_salt("before").show(ui).response.id);
|
||||
seen[1].set(SelectableText::new("Path", "/projects/poster.indd").show(ui).response.id);
|
||||
seen[1].set(SelectableText::new("Path", "/projects/poster.indd").show(ui).id);
|
||||
seen[2].set(TextField::new("After", Bind::given(String::new())).id_salt("after").show(ui).response.id);
|
||||
});
|
||||
fixture.settle();
|
||||
@@ -35,3 +40,98 @@ fn tab_passes_over_read_only_text_and_a_press_selects_it_for_copy() {
|
||||
fixture.frame(vec![Event::Copy]);
|
||||
assert_eq!(fixture.copied(), ["/projects/poster.indd"]);
|
||||
}
|
||||
|
||||
/// Where `text` was painted.
|
||||
fn painted(fixture: &Fixture, text: &str) -> Rect {
|
||||
fixture.texts().iter().find(|painted| painted.text == text).unwrap_or_else(|| panic!("{text:?} is painted")).rect
|
||||
}
|
||||
|
||||
/// Select All then Copy in the focused text.
|
||||
fn copy_all(fixture: &mut Fixture) -> Vec<String> {
|
||||
fixture.key(Key::A, Modifiers::COMMAND);
|
||||
fixture.frame(vec![Event::Copy]);
|
||||
fixture.copied().to_vec()
|
||||
}
|
||||
|
||||
/// A notice's title and message are two selection parts: Tab goes from the field before the notice to its action and
|
||||
/// on to the field after it; a press on the message focuses it and Copy copies the message alone; a drag over the
|
||||
/// start of the title selects part of it.
|
||||
#[trial]
|
||||
fn notice_title_and_message_select_and_copy_apart() {
|
||||
let ids = Rc::new([Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL)]);
|
||||
let seen = ids.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
seen[0].set(TextField::new("Before", Bind::given(String::new())).id_salt("before").show(ui).response.id);
|
||||
let notice = Notice::new(Tone::Warn, "The link to poster.png is broken.").title("Missing file").action(NoticeAction::new("Relink"));
|
||||
seen[1].set(notice.id_salt("notice").show(ui).response.id);
|
||||
seen[2].set(TextField::new("After", Bind::given(String::new())).id_salt("after").show(ui).response.id);
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
assert_eq!(stop(&fixture), Some(ids[1].get()), "Tab reaches the notice's action");
|
||||
assert!(fixture.focused_stop().is_some_and(|(_, part)| part.is_some()));
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
assert_eq!(stop(&fixture), Some(ids[2].get()), "Tab passes over the title and message");
|
||||
|
||||
let message = painted(&fixture, "The link to poster.png is broken.");
|
||||
fixture.click_at(message.center());
|
||||
assert_eq!(stop(&fixture), Some(ids[1].get()), "a press focuses the message");
|
||||
assert_eq!(copy_all(&mut fixture), ["The link to poster.png is broken."]);
|
||||
|
||||
let title = painted(&fixture, "Missing file");
|
||||
fixture.drag_at(title.left_center() + Vec2::new(1.0, 0.0), Vec2::new(title.width() / 2.0, 0.0));
|
||||
fixture.frame(vec![Event::Copy]);
|
||||
let copied = fixture.copied().last().cloned().unwrap_or_default();
|
||||
assert!(!copied.is_empty() && "Missing file".starts_with(&copied) && copied != "Missing file", "the drag selected {copied:?}");
|
||||
}
|
||||
|
||||
/// A toast card's message is selectable: a press, Select All and Copy copy it and leave the card up, and Tab passes
|
||||
/// over the text to the card's dismiss button.
|
||||
#[trial]
|
||||
fn toast_text_selects_and_copies() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let ctx = ui.ctx().clone();
|
||||
if toast::cards(&ctx).is_empty() {
|
||||
toast::post(&ctx, toast::Toast::new("poster.png was saved to Pictures.").tone(Tone::Good).title("Exported").timeout(None));
|
||||
}
|
||||
ToastStack::show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
let dismiss = fixture.focused_stop();
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
assert_eq!(fixture.focused_stop(), dismiss, "Tab stays on the dismiss button, the card's one Tab stop");
|
||||
assert!(dismiss.is_some_and(|(_, part)| part.is_some()), "Tab reaches the dismiss button");
|
||||
|
||||
let message = painted(&fixture, "poster.png was saved to Pictures.");
|
||||
fixture.click_at(message.center());
|
||||
assert_eq!(copy_all(&mut fixture), ["poster.png was saved to Pictures."]);
|
||||
fixture.settle();
|
||||
assert!(fixture.texts().iter().any(|painted| painted.text == "Exported"), "the card stays up");
|
||||
}
|
||||
|
||||
/// A metadata table's value is selectable: a press on it, Select All and Copy copy the value, the press selects no
|
||||
/// row, and Tab passes over the values.
|
||||
#[trial]
|
||||
fn metadata_value_copies_without_selecting_the_row() {
|
||||
let selected = Rc::new(Cell::new(false));
|
||||
let seen = selected.clone();
|
||||
let groups = vec![MetadataGroup::new("Camera", vec![MetadataRow::new("Make", "FUJIFILM"), MetadataRow::new("Model", "X100V")])];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = MetadataTable::new("Metadata", &groups).show(ui);
|
||||
if out.table.events.iter().any(|event| matches!(event, CollectionEvent::Selection(_))) {
|
||||
seen.set(true);
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
for _ in 0..3 {
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
assert!(fixture.focused_stop().is_none_or(|(_, part)| part.is_none()), "Tab passes over the values: {:?}", fixture.focused_stop());
|
||||
}
|
||||
|
||||
let value = painted(&fixture, "X100V");
|
||||
fixture.click_at(value.center());
|
||||
assert_eq!(copy_all(&mut fixture), ["X100V"]);
|
||||
assert!(!selected.get(), "the press on the value selected no row");
|
||||
}
|
||||
|
||||
@@ -111,6 +111,8 @@ A component is shown through a parent's `show`, never by allocating a rect itsel
|
||||
|
||||
`cx.part(KEY, rect)` registers a part. `ui.face(KEY, Other::new())` paints another component as the look of a part, so a composite reuses the look of the component it wears. A part that only a pointer reaches states why keyboard users do not need it: `.pointer_only("Enter activates the component")`.
|
||||
|
||||
Read-only text the user can select and copy is a selection part: `parts` declares the run with `cx.selectable_text(KEY, &run)`, and `paint` shows it with `ui.selectable_text(KEY, rect, &run)` in place of `draw().text`, with the same run in the state's colours. A press focuses it; drag and double click select; Select All and Copy work; Tab, F6 and the arrows pass over it. A component may declare any number. The text has no node of its own, so the component's node carries it. A notice's title and message, a metadata table's values (`ListRow::cell_selectable`) and `SelectableText` are selection parts.
|
||||
|
||||
### Values
|
||||
|
||||
A value component's `Output` is `EditResponse<T>`. It binds with `Bind<T>` and reports through `cx.propose`, `cx.commit` and `cx.adopt`; each gesture ends in one `EditEvent::Commit`. Components with `Input::Editor` own their caret through `ImeSurface`.
|
||||
|
||||
Reference in New Issue
Block a user