From 2b80ba2cdcf9ba3c0e7176328962fde5ec8bb1c2 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Mon, 23 Nov 2026 21:56:49 +0100 Subject: [PATCH 01/24] Text parts: a size of the caller's own, the laid-out text's screen origin in the outcome, and multi-line text that starts at the top of its part when asked TextOptions::size sets the text at a size of the caller's own in place of the role's (the face stays the role's, and the optical size follows the size); TextOutcome::origin is where the laid-out text sits on screen this pass, margin and scroll included, so an editor paints gutters beside its rows; TextOptions::top starts a multi-line text at the top of its part, the old centring staying the default. The top placement keeps next's horizontal placement (centred, or end-aligned against the text direction), moving only the vertical. Ported from design-port/fw-textfield-rows 05508b95f and 52f3d2096, squashed: the second made the first's unconditional top start an option. --- crates/ui-contract/src/contract/text.rs | 1 + crates/ui-contract/src/primitives/sensing.rs | 4 + .../src/primitives/text_adapter.rs | 8 +- .../ui-contract/src/primitives/text_input.rs | 8 + .../ui-contract/src/runtime/egui/text_edit.rs | 26 ++- crates/ui-widgets/tests/it/text/mod.rs | 1 + .../ui-widgets/tests/it/text/part_layout.rs | 161 ++++++++++++++++++ 7 files changed, 202 insertions(+), 7 deletions(-) create mode 100644 crates/ui-widgets/tests/it/text/part_layout.rs diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index fd5609e631..aa951c543c 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -571,6 +571,7 @@ pub(crate) fn run( let caret = adapter::caret_byte(&ctx, widget, state.draft.as_deref().unwrap_or(out.layout.full())); *cx.core.memory.shown::(state_id) = state; let mut outcome = resolved.outcome; + outcome.origin = out.origin; outcome.layout = Some(out.layout); outcome.caret_visible = caret_visible; outcome.composing = crate::runtime::ime::composing(&ctx, widget); diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index f5d6671c55..2eebe72e40 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -80,6 +80,9 @@ pub struct TextOutcome { pub value: Option, /// The laid-out text, so an editor draws gutters and line numbers beside it. pub layout: Option, + /// Where the origin of `layout` sits on screen this pass, the text's margin and scroll included: a row of the + /// layout is at its galley position moved by this. The rect's corner until the text is laid out. + pub origin: egui::Pos2, /// Whether the caret stroke shows this pass (the caret blink). pub caret_visible: bool, /// The draft is not a value of the codec. @@ -102,6 +105,7 @@ impl TextOutcome { draft: None, value: None, layout: None, + origin: rect.min, caret_visible: true, invalid: false, committed: None, diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index de55fff503..defe4f2eca 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -175,6 +175,8 @@ pub(crate) struct AdapterOut { pub clicked: bool, /// The screen y of the first row's baseline; `None` while the text is empty. pub baseline: Option, + /// Where the laid-out text's origin sits on screen, after the multi-line scroll. + pub origin: Pos2, } /// The rows of a laid-out text as AccessKit lines, with the byte where each starts in the text. @@ -543,6 +545,8 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut hint: input.placeholder, mono: input.options.mono, role: input.options.role, + size: input.options.size, + top: input.options.top, ink: input.ink, filter, char_limit: input.options.limit, @@ -629,7 +633,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut let full = display; let layout = TextLayout::new(shown.galley, false, full); let baseline = (!layout.full().is_empty()).then_some(shown.galley_pos.y + layout.first_baseline); - AdapterOut { layout, focused: shown.focused, tab, clicked: shown.clicked, baseline } + AdapterOut { layout, focused: shown.focused, tab, clicked: shown.clicked, baseline, origin: shown.galley_pos } } /// What [`show_selectable`] shows: the read-only text of a selection part. @@ -680,6 +684,8 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { hint: None, mono: false, role: run.role, + size: None, + top: false, ink, filter: egui_focus::event_filter(keep, false), char_limit: None, diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index d8b20fc5b6..27756ab961 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -68,6 +68,12 @@ pub struct TextOptions { pub mono: bool, /// The type role the text is set in; a monospace text takes the mono role's face and size instead. pub role: TypeRole, + /// The text size in points in place of the role's, for text whose size is the user's to choose (a document + /// editor's text size); the face stays the role's. `None` takes the role's size. The component sizes the part for + /// it, since a role's line height no longer measures the text. + pub size: Option, + /// A multi-line text starts at the top of its part; unset, it is centred on the part's height, as a single line is. + pub top: bool, /// The text colour; `None` takes the surface's ink. A disabled part shows the disabled text colour whatever this is. pub ink: Option, /// What Tab does in this field. @@ -146,6 +152,8 @@ impl Default for TextOptions { clear_on_escape: false, mono: false, role: TypeRole::Body, + size: None, + top: false, ink: None, tab: TabKey::default(), caret: None, diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 779684c381..36325998ce 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -25,6 +25,10 @@ pub(crate) struct Edit<'a> { pub hint: Option<&'a str>, pub mono: bool, pub role: TypeRole, + /// The text size in points in place of the role's (`TextOptions::size`). + pub size: Option, + /// A multi-line text starts at the top of the rect (`TextOptions::top`). + pub top: bool, pub ink: Color32, pub filter: EventFilter, pub char_limit: Option, @@ -86,6 +90,8 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) hint, mono, role, + size, + top, ink, filter, char_limit, @@ -105,8 +111,12 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) // Behind selected text and the selected text itself: the field's roles. let selection = (tokens.color.accent.soft, tokens.color.text.normal); let facts = crate::fonts::stack_facts(ui.ctx()); - let font_id = tokens.font(facts, role, mono); - let optical_size = tokens.optical_size(facts, role, mono); + let mut font_id = tokens.font(facts, role, mono); + // A size of the caller's own keeps the role's face; the optical size follows the size the text is set at. + let optical_size = tokens.optical_size(facts, role, mono).map(|role_size| size.unwrap_or(role_size)); + if let Some(size) = size { + font_id.size = size; + } 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| { @@ -206,13 +216,17 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) .event_filter(filter) .return_key(if multiline { Some(egui::KeyboardShortcut::new(line_break, egui::Key::Enter)) } else { None }) .layouter(&mut layouter) - // A laid-out galley sits at the rect's corner, as a painted run does. + // A laid-out galley sits at the rect's corner, as a painted run does; the lines of a multi-line text + // start at the top of its part when the part asks (`top`), whatever room is left below them. .align(match (centred, rtl) { _ if galley.is_some() => egui::Align2::LEFT_TOP, + (true, _) if multiline && top => egui::Align2::CENTER_TOP, (true, _) => egui::Align2::CENTER_CENTER, - (false, rtl) => match (end_aligned, rtl) { - (true, false) | (false, true) => egui::Align2::RIGHT_CENTER, - (true, true) | (false, false) => egui::Align2::LEFT_CENTER, + (false, rtl) => match (end_aligned != rtl, multiline && top) { + (true, true) => egui::Align2::RIGHT_TOP, + (true, false) => egui::Align2::RIGHT_CENTER, + (false, true) => egui::Align2::LEFT_TOP, + (false, false) => egui::Align2::LEFT_CENTER, }, }); if let Some(hint) = hint_text.clone() { diff --git a/crates/ui-widgets/tests/it/text/mod.rs b/crates/ui-widgets/tests/it/text/mod.rs index 96a930d668..2589be32e8 100644 --- a/crates/ui-widgets/tests/it/text/mod.rs +++ b/crates/ui-widgets/tests/it/text/mod.rs @@ -10,6 +10,7 @@ pub(crate) mod mixed_blank; pub(crate) mod number; pub(crate) mod number_length; pub(crate) mod number_scrub_step; +pub(crate) mod part_layout; pub(crate) mod rtl_paragraph; pub(crate) mod selectable; pub(crate) mod submit_key; diff --git a/crates/ui-widgets/tests/it/text/part_layout.rs b/crates/ui-widgets/tests/it/text/part_layout.rs new file mode 100644 index 0000000000..59c56841c0 --- /dev/null +++ b/crates/ui-widgets/tests/it/text/part_layout.rs @@ -0,0 +1,161 @@ +//! A text part's laid-out text for the component that shows it: set at a size of the caller's own, and placed on screen +//! where its rows are drawn, so an editor paints gutters beside them. + +use craft_behavior::{Metrics, PartKey, PlainText, Sense}; +use craft_ui::contract::{Bind, BindMut, Common, Component, Cx, Input, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _}; +use craft_ui::primitives::{TextKey, TextOptions}; +use craft_ui::style::{ComponentStyle, StyleCx}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers, Pos2, Rect, Response, Vec2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +const TEXT: PartKey = PartKey::new("text"); + +/// Half a point: rects compared across passes may round apart by that much. +const SNAP: f32 = 0.5; + +#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +#[non_exhaustive] +struct PlainStyle { + #[style(metrics)] + metrics: Metrics, +} + +/// What an editor's paint read of its text part: the part's rect, the layout's origin and each row's screen top and +/// bottom. +#[derive(Clone, Debug, Default)] +struct Painted { + part: Option, + origin: Option, + rows: Vec<(f32, f32)>, +} + +/// A multi-line text part of a fixed size, whose paint reads the part's outcome as a gutter would. +#[derive(Component)] +struct Editor<'a> { + #[common] + common: Common, + value: Bind<'a, String>, + size: Option, + top: bool, + painted: &'a RefCell, +} + +impl Component for Editor<'_> { + const ROLE: Role = Role::TEXT_INPUT; + const INPUT: Input = Input::Text; + const OVERLAYS: bool = false; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: EditorStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(240.0, 80.0) + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS + } + + fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { + let mut options = TextOptions::new(); + options.lines = Some(3); + options.size = self.size; + options.top = self.top; + let rect = cx.content_rect; + if let Some(value) = cx.value() { + cx.text(TextKey::new(TEXT), rect, &PlainText, value, &options); + } + } + + fn bind(&mut self) -> Option> { + Some(self.value.reborrow()) + } + + fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(outcome) = cx.text(&TextKey::::new(TEXT)) else { return }; + let Some(layout) = &outcome.layout else { return }; + let origin = outcome.origin; + let rows = layout.galley.rows.iter().map(|row| (origin.y + row.min_y(), origin.y + row.max_y())).collect(); + *self.painted.borrow_mut() = Painted { part: Some(outcome.rect), origin: Some(origin), rows }; + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// Shows an editor over `text` set at `size` and returns what its paint read after the fixture settles. The text starts at +/// the top of its part as an editor's does. +fn editor(text: &str, size: Option) -> (Fixture, Rc>, Rc>) { + shown_editor(text, size, true) +} + +/// [`editor`], with the text starting at the top of its part or not (`TextOptions::top`). +fn shown_editor(text: &str, size: Option, top: bool) -> (Fixture, Rc>, Rc>) { + let (value, painted) = (Rc::new(RefCell::new(text.to_owned())), Rc::new(RefCell::new(Painted::default()))); + let (shown, read) = (value.clone(), painted.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut held = shown.borrow_mut(); + Editor { common: Common::new(), value: Bind::bound(&mut *held), size, top, painted: &*read }.id_salt("editor").show(ui); + }); + fixture.settle(); + (fixture, value, painted) +} + +/// A size of the caller's own sets the text at that size, not the role's: the rows of a part set at 30 points are +/// taller than those of the same text at its role's size, and still lie in order down the part. +#[trial] +fn a_part_set_at_its_own_size_lays_its_rows_out_at_that_size() { + let row = |painted: &Painted| painted.rows.first().map_or(0.0, |(top, bottom)| bottom - top); + let (_plain, _, at_role) = editor("one\ntwo", None); + let (_large, _, at_size) = editor("one\ntwo", Some(30.0)); + let (at_role, at_size) = (at_role.borrow().clone(), at_size.borrow().clone()); + assert!(row(&at_role) > 0.0 && at_role.rows.len() == 2, "the role's text lays out two rows: {at_role:?}"); + assert!(row(&at_size) > row(&at_role) * 1.5, "30 points sets taller rows than the role's size: {at_size:?} vs {at_role:?}"); + assert!(at_size.rows.windows(2).all(|pair| pair[1].0 >= pair[0].1 - SNAP), "the rows lie in order: {at_size:?}"); +} + +/// A multi-line text shorter than its part starts at the part's top when the part asks for it (`TextOptions::top`): its +/// one row lies in the top half of the part. Without it the text keeps the placement every field had, centred on the +/// part's height. +#[trial] +fn a_short_multi_line_text_starts_at_the_top_of_its_part_when_asked_to() { + let (_fixture, _, painted) = editor("one", None); + let painted = painted.borrow().clone(); + let part = painted.part.expect("the part is laid out"); + let row = painted.rows.first().copied().expect("the text has a row"); + assert!(row.0 >= part.top() - SNAP && row.1 < part.center().y, "the row sits at the top of the part: {painted:?}"); + let (_fixture, _, kept) = shown_editor("one", None, false); + let kept = kept.borrow().clone(); + let row = kept.rows.first().copied().expect("the text has a row"); + assert!(row.0 < part.center().y && row.1 > part.center().y, "without the option the row is centred on the part: {kept:?}"); +} + +/// The outcome's origin is where the layout is drawn: at rest its rows start inside the part, and once the text is +/// longer than the part and scrolled to the caret at its end, the origin moves up with the text, so the last row is +/// the one in view at the part's bottom. +#[trial] +fn the_origin_follows_the_text_where_it_is_drawn() { + let lines = (1..=12).map(|line| line.to_string()).collect::>().join("\n"); + let (mut fixture, value, painted) = editor(&lines, None); + let rest = painted.borrow().clone(); + let part = rest.part.expect("the part is laid out"); + let first = rest.rows.first().copied().expect("the text has rows"); + assert!(part.expand(SNAP).contains(rest.origin.expect("the layout is placed")), "at rest the layout starts in the part: {rest:?}"); + assert!(first.0 >= part.top() - SNAP && first.1 <= part.bottom() + SNAP, "the first row shows in the part: {rest:?}"); + + // Focus puts the caret at the end of plain text. + fixture.key(Key::Tab, Modifiers::NONE); + fixture.type_text("!"); + fixture.idle(3); + assert!(value.borrow().ends_with("12!"), "the typing lands at the end: {:?}", value.borrow()); + let scrolled = painted.borrow().clone(); + let last = scrolled.rows.last().copied().expect("the text has rows"); + assert!(scrolled.origin.is_some_and(|origin| origin.y < part.top()), "the origin moves up with the scrolled text: {scrolled:?}"); + assert!(last.1 <= part.bottom() + SNAP && last.0 >= part.top() - SNAP, "the caret's row, the last, is drawn in the part: {scrolled:?}"); +} From 2650b60a3b32067382f82e8dd6419d5cde81be18 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Mon, 23 Nov 2026 22:52:59 +0100 Subject: [PATCH 02/24] Text parts trial: the editor's output is an EditResponse, which is where next reads a component's value type --- crates/ui-widgets/tests/it/text/part_layout.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/ui-widgets/tests/it/text/part_layout.rs b/crates/ui-widgets/tests/it/text/part_layout.rs index 59c56841c0..526304bdf4 100644 --- a/crates/ui-widgets/tests/it/text/part_layout.rs +++ b/crates/ui-widgets/tests/it/text/part_layout.rs @@ -2,11 +2,13 @@ //! where its rows are drawn, so an editor paints gutters beside them. use craft_behavior::{Metrics, PartKey, PlainText, Sense}; -use craft_ui::contract::{Bind, BindMut, Common, Component, Cx, Input, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _}; +use craft_ui::contract::{ + Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _, +}; use craft_ui::primitives::{TextKey, TextOptions}; use craft_ui::style::{ComponentStyle, StyleCx}; use craft_ui::testing::{Fixture, trial}; -use egui::{Key, Modifiers, Pos2, Rect, Response, Vec2}; +use egui::{Key, Modifiers, Pos2, Rect, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -47,7 +49,8 @@ impl Component for Editor<'_> { const INPUT: Input = Input::Text; const OVERLAYS: bool = false; type Style = PlainStyle; - type Output = Response; + // The value is the component's: its output carries the `String` it edits, so the part reads it as `cx.value()`. + type Output = EditResponse; fn style(_: &StyleCx<'_>, _: EditorStyleKey) -> PlainStyle { PlainStyle::default() @@ -84,8 +87,8 @@ impl Component for Editor<'_> { *self.painted.borrow_mut() = Painted { part: Some(outcome.rect), origin: Some(origin), rows }; } - fn finish(self, cx: Cx<'_, Self>) -> Response { - cx.response.clone() + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() } } From 171c23f51d9c7c4ea7ac3fec2b38c7d43acc83c4 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 16:49:48 +0100 Subject: [PATCH 03/24] ui-widgets text field: measure the text in the face it is drawn in A monospace text field (the hex field) measured its codec sample, and counted width_chars, in the body face while drawing in the monospace face, so a content-sized hex field cut off part of its sixth digit. The field now measures its sample and its multi-line rows in the face it draws, and a mono field counts width_chars in the mono role's face (a new face style key input). The placeholder stays measured in the field's role, as the editor draws it proportional. width_chars still does not widen a content-sized field, as documented. Trial: a_content_sized_hex_field_shows_all_six_digits. --- crates/ui-widgets/src/text/hex.rs | 5 +-- crates/ui-widgets/src/text/mod.rs | 8 ++++- crates/ui-widgets/src/text/text_field.rs | 42 ++++++++++++++++++------ crates/ui-widgets/tests/it/text/hex.rs | 25 +++++++++++++- 4 files changed, 66 insertions(+), 14 deletions(-) diff --git a/crates/ui-widgets/src/text/hex.rs b/crates/ui-widgets/src/text/hex.rs index 9a4d15b26b..16e4485924 100644 --- a/crates/ui-widgets/src/text/hex.rs +++ b/crates/ui-widgets/src/text/hex.rs @@ -133,8 +133,9 @@ pub type HexField<'a> = TextField<'a, HexCodec>; const NOT_HEX: Word = Word::keyed("hexField.unparsed", "Not a hex color"); impl<'a> TextField<'a, HexCodec> { - /// A hex field named `label` that shows and edits `value` as monospace digits. A draft that is no colour says so - /// ("Not a hex color", `TextField::unparsed`). Its row names the digits with [`hash_label`](Self::hash_label). + /// A hex field named `label` that shows and edits `value` as monospace digits; sized `Sizing::Content`, it is as wide + /// as its digits in that face. A draft that is no colour says so ("Not a hex color", `TextField::unparsed`). Its row + /// names the digits with [`hash_label`](Self::hash_label). pub fn hex(label: impl Into