diff --git a/crates/color-ui/src/ui/picker/channel.rs b/crates/color-ui/src/ui/picker/channel.rs index ccd97daa06..8cb04ab0a5 100644 --- a/crates/color-ui/src/ui/picker/channel.rs +++ b/crates/color-ui/src/ui/picker/channel.rs @@ -10,7 +10,7 @@ use craft_ui::contract::{ Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, GlyphLabel, LabelKind, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Role, Show as _, ShowContainer as _, SideLabel, Sizing, }; -use craft_ui::form::{Field, SliderField, SliderFieldLayout}; +use craft_ui::form::{Field, FieldDecimals, SliderField, SliderFieldLayout}; use craft_ui::layout_components::Row; use craft_ui::primitives::{PaintShape, StrokeWidth}; use craft_ui::runtime::env::{Label, UnitKind}; @@ -149,7 +149,8 @@ impl Component for TrackRamp { } } -/// The slider and number field of a channel, over `value`, with `track` colours on the groove. +/// The slider and number field of a channel, over `value`, with `track` colours on the groove. The field shows the +/// decimals the rule declares, a percent channel too ("67", not the percent look's "66.7"). pub(crate) fn channel_slider<'a>( name: Label, value: Bind<'a, f64>, @@ -157,7 +158,7 @@ pub(crate) fn channel_slider<'a>( unit: ChannelUnit, track: Option<(Vec, bool)>, ) -> SliderField<'a> { - let field = SliderField::new(name, value, rule.range.clone()).step(rule.step); + let field = SliderField::new(name, value, rule.range.clone()).step(rule.step).field_decimals(FieldDecimals::Fixed(usize::from(rule.decimals))); let field = match unit { ChannelUnit::None => field, ChannelUnit::Percent => field.unit_kind(UnitKind::Percent), @@ -172,7 +173,8 @@ pub(crate) fn channel_slider<'a>( /// One channel on one line, as Photoshop's Color panel draws it: the label at the start (the channel's short label /// where one is given, "C"), which scrubs the value, the slider over the channel's colours with the pointer under its -/// track, and the number field with its unit at the end, as wide as its widest value. +/// track, and the number field with its unit at the end, as wide as its widest value, showing the channel's declared +/// decimals. #[derive(craft_ui::contract::Pattern)] pub struct ChannelRow<'a> { label: Label, diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index ab2fa66c29..03119e8114 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -685,3 +685,33 @@ fn a_request_for_the_swatches_opens_the_picker_on_its_swatch_view() { assert!(shows_swatches(request().on_swatches()), "the swatch view shows the library's cells"); assert!(!shows_swatches(request()), "without it the picker opens on the Color Models"); } + +/// The number a Compact picker's channel field named `channel` paints, the picker showing HSB `values`. +fn compact_field_number(values: [f32; 3], channel: &str) -> String { + let hsb = ModelValues::new(HsbModel.id(), &values); + let mut fixture = Fixture::new(move |ui| { + let mut color = PickedColor::in_model(HsbModel.to_srgb(&hsb.values), hsb); + let models: [&dyn ColorModel; 2] = [&HsbModel, &RgbModel]; + let _ = ColorPicker::new("Color", Bind::bound(&mut color)).layout(ColorPickerLayout::Compact).models(models).show(ui); + }); + fixture.room(vec2(600.0, 700.0)); + fixture.settle(); + let tree = fixture.tree(); + let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|t| tree.name_of(t.node) == Some(channel)); + let field = field.unwrap_or_else(|| panic!("the picker shows a {channel} field")).rect; + let texts = fixture.texts(); + let number = texts.iter().find(|run| field.contains(run.rect.center()) && run.text.starts_with(|c: char| c.is_ascii_digit())); + number + .unwrap_or_else(|| panic!("the {channel} field shows its value: {:?}", texts.iter().map(|r| r.text.to_string()).collect::>())) + .text + .to_string() +} + +/// A Compact picker's channel rows, which the Color panel and the harmony brightness row share, show the decimals their +/// channel declares, a percent channel too: HSB saturation declares none, so 66.7 % reads "67", not the percent look's +/// "66.7". +#[trial] +fn the_compact_pickers_percent_channels_show_the_decimals_they_declare() { + assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Saturation"), "67"); + assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Hue"), "210", "a degree channel keeps its whole degrees"); +} diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 6287e64633..c5c4b1a310 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1202,6 +1202,17 @@ impl BodyHooks<'_> { // A measuring run lays out and measures: it registers no instance, focus body, scroll region or body layer, // and claims no room in a parent flow. let real = !ui.is_sizing_pass(); + // A held container whose width its least width decides, not its content, shows across the width its column + // settles on with its fill children at their measures. It asks the column to sweep again with that width: laid + // out across it its own fill children take it, and its content-sized record was not made across it. + if !self.wide() + && self.held + && self.least_width > 0.0 + && matches!(props.layout, layout::BodyLayout::Stack) + && let Some(ColumnSweep::Count(column)) = env.column + { + crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Column, self.room.x); + } let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes(), real).below(core.content_rect.min.y + band); let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_))); let band_slot = ui.painter().add(Shape::Noop); diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index c16d15959c..3a232d1d90 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -87,9 +87,13 @@ impl BodyHooks<'_> { scoped.inside_label = None; scoped.cell_fills = false; // Along a width the container takes from its content, its regions measure at their content widths: a child - // that fills takes what it needs, not the whole room. A container that passes its column's width on measures - // them across it. - if !real && !self.wide() { + // that fills takes what it needs, not the whole room. A container given its width (a rect, a column's width it + // passes on, or the width its column settled on) lays its regions out across it in both runs: its bands are as + // wide as the container, so a child that fills takes the band, whatever column its parent is. + if self.wide() { + scoped.content_column = false; + scoped.content.0 = false; + } else if !real { scoped.content_column = true; } if props.header.is_some_and(|header| header.band == DragBand::Reorder) { diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 2cebed8f01..aa97d44113 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -222,6 +222,9 @@ pub enum LeastWidth { SideMenu, /// `size.dock.column`: a fixed side pane is as wide as a dock column. DockColumn, + /// `size.dialog.wrap`: a command palette's box, as wide as a dialog paragraph's line, so it keeps one width + /// while its results change instead of following its widest row. + Palette, } impl LeastWidth { @@ -236,6 +239,7 @@ impl LeastWidth { LeastWidth::WideDialog => tokens.size.dialog.least + tokens.size.dialog.wrap, LeastWidth::SideMenu => tokens.size.rail.width * 5.0, LeastWidth::DockColumn => tokens.size.dock.column, + LeastWidth::Palette => tokens.size.dialog.wrap, } } } diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 2758b2affa..b6c16389d0 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -676,6 +676,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/layout/body.rs b/crates/ui-contract/src/layout/body.rs index dd6e424734..7917515275 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -157,6 +157,11 @@ pub(crate) enum HeldKind { /// (`MeasureCx::picture_size`): it shows at the width it sizes at in the column's width, which may be narrower than /// the column. Picture, + /// A fill-width container whose least width decides its width, its body a content-sized `Stack` column + /// (`BodyHooks::plan_regions` reports it): it shows across the column's width, and laid out across it its own fill + /// children take that width where its content-sized measure left them at their measures. Whatever width it + /// measured at, the column sweeps again. + Column, } /// The held children of each content-sized `Stack` column in its measuring run, by column id: each child's kind and @@ -170,6 +175,11 @@ pub(crate) fn report_held(ctx: &egui::Context, column: Id, child: Id, kind: Held pass_state::with::(ctx, |held| { if let Some(children) = held.0.get_mut(&column) { let entry = children.entry(child).or_insert((kind, width)); + // A container that lays its content out as a column reports its kind once its own body ran, after the + // width `place_root` reported for it in flow: the kind of the two is its own. + if kind == HeldKind::Column { + entry.0 = HeldKind::Column; + } entry.1 = entry.1.min(width); } }); @@ -1166,14 +1176,15 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: /// is bounded: each sweep is `run_sharing`'s, with the column's sweep (`ColumnSweep`) in its children's env. It adds no /// `Ui` of its own, so the children have the ids `run_sharing` gives them when the column's width is not bounded. /// -/// A held child (`HeldKind`: a fill-width child, or a picture that took its least for want of room) measures at its -/// own width while the column settles its width from the others, so it may measure narrower than it shows. A -/// measuring run sweeps the children once, each held child reporting the width it measured at (`report_held`). When -/// one of them measured narrower than the column settled on, it sweeps them again with that width, at which the held -/// children measure in the column's width and the others reuse their records; else the first sweep stands, and each -/// held child keeps the record it made at its own width, which is the column's. It records which -/// (`sub(id, "column")`): the real run gives the held children the width the column shows at only after a second -/// sweep, so each shows as its records were made. +/// A held child (`HeldKind`: a fill-width child, a picture that took its least for want of room, or a container that +/// lays its content out as a column) measures at its own width while the column settles its width from the others, so +/// it may measure narrower than it shows. A measuring run sweeps the children once, each held child reporting the width +/// it measured at (`report_held`). When one of them measured narrower than the column settled on, or lays its content +/// out as a column (whose fill children take the column's width where its content-sized measure left them at their +/// measures, whatever it measured at), it sweeps them again with that width, at which the held children measure in the +/// column's width and the others reuse their records; else the first sweep stands, and each held child keeps the record +/// it made at its own width, which is the column's. It records which (`sub(id, "column")`): the real run gives the held +/// children the width the column shows at only after a second sweep, so each shows as its records were made. // PLAN: the second sweep's need is decided once for the column, not per held container at body/hooks.rs's reuse // rule: a container that reused its content-sized record there would be laid out across in the real run under records // not made across. @@ -1199,11 +1210,16 @@ fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: let installed = Env::install_for(ui, env.clone()); let (inner, rect) = measure_sharing(ui, &env, id, Axis::Y, layout, &mut body); Env::restore(&ctx, installed); - let narrowest = pass_state::with::(&ctx, |held| { - held.0.get(&id).map_or(f32::INFINITY, |children| children.values().fold(f32::INFINITY, |least, (_, width)| least.min(*width))) + let (narrowest, laid_out) = pass_state::with::(&ctx, |held| { + held.0.get(&id).map_or((f32::INFINITY, false), |children| { + children + .values() + .fold((f32::INFINITY, false), |(least, laid_out), (kind, width)| (least.min(*width), laid_out || *kind == HeldKind::Column)) + }) }); - // Half a point: less than a pixel shows at any scale the box runs. - let again = narrowest < rect.width() - 0.5; + // Half a point: less than a pixel shows at any scale the box runs. A held child that lays its content out as a + // column is swept again whatever it measured at: across the column's width its fill children take it. + let again = narrowest < rect.width() - 0.5 || laid_out; ((inner, rect, again), again) }); let column = rect.width(); diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 2197f80ff4..254e9985b6 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -81,6 +81,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. @@ -103,6 +106,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.rs b/crates/ui-contract/src/primitives/text.rs index 2ab15f72bf..b8933d6690 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -243,7 +243,8 @@ pub(crate) struct TextEnv<'a> { /// The baseline of a control's line of `role` whose centre line lies at `centre`: where a one-line text of `role` in /// its own face sits with its row centred on the centre line, as `Draw::text` centres a line in a taller rect. Every /// text in the line sits on it, whatever its face or size: a select's face, a field's mono digits and the smaller unit -/// after them. +/// after them. A text part set at a size of the caller's own is the one text that centres its own row on its part +/// instead, since a row taller than the role's would carry the part's text out of it (`TextOptions::size`). pub(crate) fn line_baseline(ctx: &Context, env: &TextEnv<'_>, role: TypeRole, centre: f32) -> f32 { let line = TextRun::new("x").role(role).layout(ctx, env, f32::INFINITY); centre - line.size().y / 2.0 + line.first_baseline diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 5c51fd6391..2687beda3d 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -193,6 +193,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. @@ -588,6 +590,8 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut muted_hint: input.options.look == crate::style::FieldLook::Quiet, 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, @@ -675,7 +679,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. @@ -727,6 +731,8 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { muted_hint: false, 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 293cbe9346..b16b5553e2 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -80,6 +80,13 @@ 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: a single-line part centres that row on the part + /// rather than on the role's baseline, which a row taller than the role's would leave. + 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. @@ -174,6 +181,8 @@ impl Default for TextOptions { keep_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 f64ccd5479..f8f890a095 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -28,6 +28,10 @@ pub(crate) struct Edit<'a> { pub muted_hint: bool, 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, @@ -46,7 +50,8 @@ pub(crate) struct Edit<'a> { /// is not clipped to `rect`. pub galley: Option>, /// The screen y of the baseline a single line without a laid-out galley sits on: its control's line's, which a - /// text in another face (mono digits) shares. `None` centres the line's row on the rect's centre line. + /// text in another face (mono digits) shares. `None` centres the line's row on the rect's centre line, and a text + /// whose size is the caller's own is centred there whatever this says. pub baseline: Option, /// How far a multi-line text taller than `rect` is scrolled up inside it, in points; the text part owns the offset /// (`text_adapter`), and a single line or a laid-out galley ignores it. @@ -92,6 +97,8 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) muted_hint, mono, role, + size, + top, ink, filter, char_limit, @@ -112,8 +119,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)); // A masked text shows dots and a disabled one the disabled colour: neither is coloured. @@ -164,7 +175,8 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size))); // A single-line edit runs in a rect one text row tall, or the part's height when that is taller, placed so the // text's baseline is `baseline`, else centred on the part's centre line. egui centres the row in the rect, whatever - // row it allocates from the rect's top. + // row it allocates from the rect's top. A text whose size is the caller's own is centred on the part too: its row is + // taller than the role's, so the role's baseline would lift the row and its clip out of the top of the part. let rect = if multiline || galley.is_some() { rect } else { @@ -179,7 +191,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) }; let row = probe.size().y; let first_baseline = probe.rows.first().and_then(|placed| placed.row.glyphs.first().map(|glyph| placed.pos.y + glyph.pos.y)); - let centre = match baseline.zip(first_baseline) { + // The row sits on the control's baseline, which every text of the line shares. A size of the caller's own sets + // a row taller than the role's that this baseline would carry out of the part's top, so that row is centred on + // the part's centre line instead, where the role's own row sits. + let centre = match baseline.zip(first_baseline).filter(|_| size.is_none()) { Some((baseline, first)) => baseline - first + row / 2.0, None => rect.center().y, }; @@ -229,7 +244,8 @@ 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, (centred, rtl) => { @@ -238,8 +254,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) (false, true) => egui::Align::Min, (false, false) => egui::Align::Max, }; - // A multi-line text starts at the part's top, however many of its lines the text fills. - egui::Align2([across, if multiline { egui::Align::Min } else { egui::Align::Center }]) + // A multi-line text starts at the part's top when the part asks (`top`), however many of its + // lines the text fills. + let down = if multiline && top { egui::Align::Min } else { egui::Align::Center }; + egui::Align2([across, down]) } }); if let Some(hint) = hint_text.clone() { diff --git a/crates/ui-contract/tests/it/text/mod.rs b/crates/ui-contract/tests/it/text/mod.rs index 67ebf9abe0..a30a7cbd14 100644 --- a/crates/ui-contract/tests/it/text/mod.rs +++ b/crates/ui-contract/tests/it/text/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod editor; pub(crate) mod input_cap; pub(crate) mod memo; pub(crate) mod resting; +pub(crate) mod sized; diff --git a/crates/ui-contract/tests/it/text/sized.rs b/crates/ui-contract/tests/it/text/sized.rs new file mode 100644 index 0000000000..8b5b69ca04 --- /dev/null +++ b/crates/ui-contract/tests/it/text/sized.rs @@ -0,0 +1,126 @@ +//! A single-line text part set at a size of the caller's own: its row is taller than the role's and still lies in the +//! part, on the part's centre line where the role's own row sits. + +use craft_behavior::{PartKey, PlainText, Sense}; +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::StyleCx; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Rect, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; + +const TEXT: PartKey = PartKey::new("text"); + +/// A size of the caller's own, well above the body role's: its row is much taller than the role's. +const LARGE: f32 = 40.0; + +/// A part far taller than the text it shows, to read off the row the text takes. +const ROOMY: f32 = 200.0; + +/// Half a point: rects compared across passes may round apart by that much. +const SNAP: f32 = 0.5; + +/// What the trial's paint read of the text part: the part's rect. +#[derive(Clone, Copy, Debug, Default)] +struct Painted { + part: Option, +} + +/// A single-line text part showing a value at a size the caller sets. +#[derive(Component)] +struct Sized<'a> { + #[common] + common: Common, + value: Bind<'a, String>, + size: Option, + height: f32, + painted: &'a RefCell, +} + +impl Component for Sized<'_> { + const ROLE: Role = Role::TEXT_INPUT; + const INPUT: Input = Input::Text; + const OVERLAYS: bool = false; + type Style = PlainStyle; + type Output = EditResponse; + + fn style(_: &StyleCx<'_>, _: SizedStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS + } + + /// The part's room: a component sizes the part for a text of the caller's own size, as tall as its row. + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(240.0, self.height) + } + + fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { + let options = TextOptions { size: self.size, ..TextOptions::default() }; + let (shown, rect) = (cx.value().cloned().unwrap_or_default(), cx.content_rect); + cx.text(TextKey::::new(TEXT), rect, &PlainText, &shown, &options); + } + + fn bind(&mut self) -> Option> { + Some(self.value.reborrow()) + } + + fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + if let Some(outcome) = cx.text(&TextKey::::new(TEXT)) { + self.painted.borrow_mut().part = Some(outcome.rect); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() + } +} + +/// The part "42" is shown in at `size` in a part `height` tall, its painted row, and the clip the row is painted under. +fn sized(size: Option, height: f32) -> (Fixture, Rect, Rect, Rect) { + let (value, painted) = (Rc::new(RefCell::new(String::from("42"))), 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(); + Sized { common: Common::new(), value: Bind::bound(&mut *held), size, height, painted: &read }.id_salt("sized").show(ui); + }); + fixture.settle(); + let part = painted.borrow().part.expect("the text part is laid out"); + let (row, clip) = { + let painted = fixture.texts().iter().find(|text| text.text == "42").expect("the value is painted"); + (painted.rect, painted.clip) + }; + (fixture, part, row, clip) +} + +/// A size of the caller's own sets a row taller than the role's, and the part a component sizes for it is as tall as +/// that row. The row keeps its place in the part, centred on the part's centre line where the role's own row sits, and +/// the clip that follows it stays inside: a baseline taken from the role would carry the taller row above the part's +/// top. Without a size the role's row keeps its place. +#[trial] +fn a_single_line_part_set_at_its_own_size_keeps_its_row_in_its_part() { + // A part far taller than the text shows what the row it lays out takes, and how much room a measure leaves the part. + let (_, roomy, taken, _) = sized(Some(LARGE), ROOMY); + let row_room = taken.height() + (ROOMY - roomy.height()); + let (_sized, part, row, clip) = sized(Some(LARGE), row_room); + let (_role, role_part, role_row, _) = sized(None, ROOMY); + assert!((part.height() - row.height()).abs() <= SNAP, "the part is as tall as the sized row: {part:?} vs {row:?}"); + assert!(row.height() > role_row.height() * 1.5, "{LARGE} points sets a taller row than the role's: {row:?} vs {role_row:?}"); + assert!( + role_row.top() >= role_part.top() - SNAP && role_row.bottom() <= role_part.bottom() + SNAP, + "the role's row lies in its part: {role_row:?} in {role_part:?}" + ); + assert!((role_row.center().y - role_part.center().y).abs() <= SNAP, "the role's row is centred on its part: {role_row:?} in {role_part:?}"); + assert!(row.top() >= part.top() - SNAP && row.bottom() <= part.bottom() + SNAP, "the sized row lies in its part: {row:?} in {part:?}"); + assert!((row.center().y - part.center().y).abs() <= SNAP, "the sized row is centred on its part: {row:?} in {part:?}"); + assert!( + clip.top() >= part.top() - SNAP && clip.bottom() <= part.bottom() + SNAP, + "the sized text is not clipped by a rect beyond the part: {clip:?} in {part:?}" + ); +} diff --git a/crates/ui-patterns/src/patterns/panels/palette.rs b/crates/ui-patterns/src/patterns/panels/palette.rs index 194516b824..28aa47c1c1 100644 --- a/crates/ui-patterns/src/patterns/panels/palette.rs +++ b/crates/ui-patterns/src/patterns/panels/palette.rs @@ -4,7 +4,8 @@ use super::words::PanelWords; use crate::contract::overlay::{Dismiss, Outside, OverlayFit, ViewportShare}; use crate::contract::{ - Bind, BodyCx, CollectionEvent, Overlay, Pattern, Politeness, Props, Show as _, ShowCollection as _, ShowContainer as _, Sizing, announce, clicked, + Bind, BodyCx, CollectionEvent, LeastWidth, Overlay, Pattern, Politeness, Props, Show as _, ShowCollection as _, ShowContainer as _, Sizing, + announce, clicked, }; use crate::display::{Shade, Text}; use crate::layout_components::{Row, Stack}; @@ -124,6 +125,8 @@ impl crate::contract::Outcome for PaletteOutput { /// out, showing the `placeholder`; it opens to the field with the key focus in the pass that opens it and lists the /// results in a popup under the field. The in-place field is the palette's face, so it is named by the palette's /// `label`, closed and open; the dialog face's field, inside a box named `label`, keeps the generic search name. +/// - Width (dialog face): at least `least_width` ([`LeastWidth::Palette`] by default), so the box keeps its width as +/// the query changes its rows; at most 60% of the window's width, where a row wider than the box shortens its label. /// - Empty query: with `suggested`, its heading and those commands; else the commands last run, newest first (the /// `recents` binding), else the first entries. /// - Fallback: with `fallback`, a last row follows the matches of a query, or stands alone when nothing matches. Picking @@ -167,6 +170,9 @@ pub struct CommandPalette<'a> { /// The row that hands the query back; its text is the template filled with the query as `{text}`. #[prop] fallback: Option, + /// The least width of the dialog face's content, from a size role; the box stays within its share of the window. + #[prop] + least_width: LeastWidth, } impl<'a> CommandPalette<'a> { @@ -185,6 +191,7 @@ impl<'a> CommandPalette<'a> { placeholder: None, suggested: None, fallback: None, + least_width: LeastWidth::Palette, } } @@ -204,7 +211,7 @@ impl<'a> CommandPalette<'a> { } fn show_dialog(self, ui: &mut Ui) -> PaletteOutput { - let CommandPalette { label, entries, index, open, uses, mut recents, placeholder, suggested, fallback, .. } = self; + let CommandPalette { label, entries, index, open, uses, mut recents, placeholder, suggested, fallback, least_width, .. } = self; let ctx = ui.ctx().clone(); let env = Env::of(ui); let words = env.words::(); @@ -213,8 +220,11 @@ impl<'a> CommandPalette<'a> { let uses: &dyn Fn(&CommandRef) -> u32 = uses.unwrap_or(&never_used); let hint: Label = placeholder.unwrap_or_else(|| words.palette_placeholder.clone()); let mut chosen = Chosen::default(); + // The box's width is its least width, or its widest row when that is wider, within the share of the window: the + // rows a query lists come and go, and a box as wide as them would jump while the user types. let shown = Popover::new(label.clone(), open) .collection_body() + .least_width(least_width) .overlay(|_| { let mut overlay = Overlay::modal().dismiss(Dismiss::new().outside(Outside::Close)); overlay.fit = OverlayFit::ContentCapped(SHARE); @@ -228,8 +238,13 @@ impl<'a> CommandPalette<'a> { let status = RefCell::new(Status::Quiet); // The field is the stack's header and the status its footer, so the list takes the room left in // the capped box and scrolls inside it. The three regions share the stack's memory, which is kept by - // its id across a close, so each opening starts a fresh session in the header, the first region. + // its id across a close, so each opening starts a fresh session in the header, the first region. The + // stack, the field and the list span the box's width, which its least width can make wider than its + // widest row: a content-sized stack left them at that row's width, in the box's start half, and the + // stack's regions lie in the stack's own width, so it asks for the least width the box asks for. Stack::new() + .fill_width() + .least_width(least_width) .header(|ui, stack| { let state = stack.memory::(); if opening { @@ -238,6 +253,7 @@ impl<'a> CommandPalette<'a> { TextField::search(words.palette_search.clone(), Bind::bound(&mut state.query)) .placeholder(hint.clone()) .drives(list_id) + .sizing(Sizing::FillWidth) .show(ui); }) .footer(|ui, stack| { diff --git a/crates/ui-patterns/tests/it/panels/palette.rs b/crates/ui-patterns/tests/it/panels/palette.rs index 4be3f59a23..e9e2c12f3a 100644 --- a/crates/ui-patterns/tests/it/panels/palette.rs +++ b/crates/ui-patterns/tests/it/panels/palette.rs @@ -3,7 +3,7 @@ //! remembers what it ran. use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, CommandSet, Overlay, Role, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, CommandSet, LeastWidth, Overlay, Role, Show as _, ShowContainer as _, clicked}; use craft_ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms}; use craft_ui::patterns::panels::{CommandPalette, PaletteFace}; use craft_ui::popover::Popover; @@ -48,6 +48,17 @@ struct Rig { /// A palette open over `entries`, inside a modal dialog when `in_dialog`, with `beneath` shown before it in the same /// window. `recents` binds the palette's recent commands to the rig when given; else the palette keeps them. fn rig(entries: Vec, recents: Option>, in_dialog: bool, beneath: impl Fn(&mut Ui) + 'static) -> Rig { + rig_least(entries, recents, in_dialog, None, beneath) +} + +/// [`rig`], with the palette's least width `least` when given. +fn rig_least( + entries: Vec, + recents: Option>, + in_dialog: bool, + least: Option, + beneath: impl Fn(&mut Ui) + 'static, +) -> Rig { let open = Rc::new(Cell::new(true)); let picked = Rc::new(RefCell::new(None::)); let refused = Rc::new(RefCell::new(None::)); @@ -62,6 +73,10 @@ fn rig(entries: Vec, recents: Option>, in_dialog: boo let view = env.view(); let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::())); let palette = CommandPalette::new("Commands", &entries, &index, Bind::bound(&mut is_open)); + let palette = match least { + Some(least) => palette.least_width(least), + None => palette, + }; let output = if bound { let mut recents = shown_held.borrow().clone(); let output = palette.recents(Bind::bound(&mut recents)).show(ui); @@ -112,6 +127,19 @@ fn disabled(fixture: &Fixture, label: &str) -> bool { rows(fixture).into_iter().find(|(name, _)| name.starts_with(label)).unwrap_or_else(|| panic!("no row {label}")).1 } +/// What the dialog face laid out, for a failing assertion: the box's width and those of the rows' list, the field and +/// the rows, so a box wider than everything it holds reads apart from a field left at its measure. +fn laid_out(fixture: &Fixture) -> String { + let wide = |role: Role| fixture.by_role(role).iter().map(|node| format!("{:.1}", node.rect.width())).collect::>().join(", "); + format!( + "the box {:.1} wide, its rows' list [{}] wide, the field [{}] wide, the rows [{}] wide", + fixture.by_role(Role::DIALOG).first().map_or(0.0, |node| node.rect.width()), + wide(Role::LIST_BOX), + wide(Role::TEXT_INPUT), + wide(Role::LIST_BOX_OPTION) + ) +} + #[trial] fn a_picked_command_runs_from_the_palette_and_comes_first_when_it_opens_again() { let entries = vec![ @@ -529,3 +557,73 @@ fn enter_on_a_disabled_first_match_runs_nothing() { assert!(open.get(), "the palette stays open"); assert!(take_output(fixture.ctx()).fired.is_empty(), "nothing ran"); } + +/// The dialog face is a steady, readable width: over short labels it opens at least the palette's least width, typing a +/// query that drops the widest rows leaves its width as it was, and in a narrow window it keeps to its share of it, +/// where a least width wider than that share gives way to it. The search field and the rows span the box's inner +/// width at either width. Guards against a box as wide as its widest row, which opened narrow and jumped as the results +/// changed, and against a field and rows left at the widest row's width, in the start half of the wider box. +#[trial] +fn the_dialog_face_keeps_a_readable_width_while_the_query_changes_its_rows() { + let entries = || vec![entry("cut", "Cut"), entry("copy", "Copy"), entry("paste", "Paste"), entry("pasteInside", "Paste Inside")]; + // A rig whose palette has the least width `role` (the default when `None`), and that width in its tokens. + let rigged = |role: Option| { + let least = Rc::new(Cell::new(0.0_f32)); + let read = least.clone(); + let points = move |ui: &mut Ui| { + read.set(role.unwrap_or(LeastWidth::Palette).points(craft_ui::runtime::env::Env::of(ui).tokens.tokens())); + }; + (rig_least(entries(), None, false, role, points), least) + }; + let (mut rig, least) = rigged(None); + let width = |fixture: &Fixture| fixture.by_role(Role::DIALOG).first().expect("the palette's box shows").rect.width(); + // The field and every row run from the box's start, less its padding, to its end, less the same padding. + let spans = |fixture: &Fixture, when: &str| { + let frame = fixture.by_role(Role::DIALOG).first().expect("the palette's box shows").rect; + let field = fixture.by_role(Role::TEXT_INPUT).first().expect("the search field shows").rect; + let pad = field.left() - frame.left(); + assert!(pad >= 0.0 && pad < frame.width() / 10.0, "{when}: the field starts inside the box's padding: {field:?} in {frame:?}"); + assert!( + (frame.right() - field.right() - pad).abs() <= 1.0, + "{when}: the field spans the box's inner width: {field:?} in {frame:?}; {}", + laid_out(fixture) + ); + let listed = fixture.by_role(Role::LIST_BOX_OPTION); + assert!(!listed.is_empty(), "{when}: the box lists rows"); + for row in listed { + let row = row.rect; + assert!( + (row.left() - field.left()).abs() <= 1.0 && (row.right() - field.right()).abs() <= 1.0, + "{when}: a row spans the box's inner width, as the field does: {row:?} under {field:?} in {frame:?}; {}", + laid_out(fixture) + ); + } + }; + rig.fixture.room(Vec2::new(1400.0, 900.0)).settle(); + let opened = width(&rig.fixture); + assert!(opened >= least.get(), "short labels open the box at its least width: {opened} against {}", least.get()); + spans(&rig.fixture, "opened"); + + rig.fixture.type_text("cut").settle(); + assert_eq!(names(&rig.fixture).len(), 1, "the query lists one short row: {:?}", names(&rig.fixture)); + let typed = width(&rig.fixture); + assert!((typed - opened).abs() <= 0.5, "the box keeps its width as the rows change: {typed} against {opened}"); + spans(&rig.fixture, "typed"); + + // The box's share is of the window, and a fixture's window is never narrower than 800 points, whatever the room + // (`Frames::screen`): the share is read from the window the layer shows in, not from the room. + let narrow = Vec2::new(400.0, 900.0); + rig.fixture.room(narrow).settle(); + let window = rig.fixture.ctx().content_rect().width(); + let kept = width(&rig.fixture); + assert!(kept <= window * 0.6 + 0.5, "a narrow window keeps the box to its share: {kept} in {window}"); + + // That share is wider than the palette's least width, which the box keeps there; a least width wider than the + // share gives way to it. + let (mut wide, least) = rigged(Some(LeastWidth::WideDialog)); + wide.fixture.room(narrow).settle(); + let window = wide.fixture.ctx().content_rect().width(); + assert!(least.get() > window * 0.6, "the wide least width {} is wider than the share of {window}", least.get()); + let kept = width(&wide.fixture); + assert!(kept <= window * 0.6 + 0.5, "a least width wider than the share gives way to it: {kept} in {window}"); +} diff --git a/crates/ui-widgets/src/form/mod.rs b/crates/ui-widgets/src/form/mod.rs index 71a31be6fc..740864318a 100644 --- a/crates/ui-widgets/src/form/mod.rs +++ b/crates/ui-widgets/src/form/mod.rs @@ -9,4 +9,4 @@ mod words; pub use field::{Field, FieldRowStyle, Help}; pub use group::{FieldGroup, FieldGroupStyle}; -pub use slider_field::{SliderField, SliderFieldLayout, SliderFieldOutput, SliderFieldStyle}; +pub use slider_field::{FieldDecimals, SliderField, SliderFieldLayout, SliderFieldOutput, SliderFieldStyle}; diff --git a/crates/ui-widgets/src/form/slider_field.rs b/crates/ui-widgets/src/form/slider_field.rs index 54435985fc..efa12ac5cf 100644 --- a/crates/ui-widgets/src/form/slider_field.rs +++ b/crates/ui-widgets/src/form/slider_field.rs @@ -33,6 +33,22 @@ pub enum SliderFieldLayout { Inline, } +/// The decimals a slider field's number field shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum FieldDecimals { + /// The number field's own look: its unit kind's decimals, or `typed_decimals` at most; a percent shows the decimals + /// its step needs in full, at most one ("67" with a step of 1, "66.7" with a step of 0.1 or finer). + #[default] + Look, + /// Exactly the decimals the step needs, zeros included, a percent too: "66.70" over 66.7 with a step of 0.01, where + /// the percent look shows "66.7"; "0.50" over a plain 0.5 with a step of 0.01. + Step, + /// Exactly this many decimals (at most 12), zeros included, a percent too: the decimals a value declares, such as + /// a colour channel's. + Fixed(usize), +} + /// The style of a slider field: the gap between its parts, the line height and the stacked number field's width. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] @@ -52,11 +68,13 @@ pub struct SliderFieldStyle { /// /// The step moves the slider's keys and wheel and the field's keys, wheel and scrub; typed values snap to it unless /// `typed_decimals` sets their independent precision. Without a step the field steps by a hundredth on a range 10 wide -/// or less and by 1 on a longer one, and by default rounds typed values to the places that step needs. The field and -/// the slider are Tab stops in the order they are read: the field and then the slider when stacked, the slider and then -/// the field when inline. A click on the row's label focuses the number field in either layout. A log or power scale -/// curves the -/// slider's track only: the field, typing and steps stay linear. +/// or less and by 1 on a longer one, and by default rounds typed values to the places that step needs. The field shows +/// its own look's decimals (for a percent, its step's up to one) unless `field_decimals` asks for the step's or a fixed +/// count, which leaves typing's snap to the step as it was; a scrub keeps the step's decimals either way, so a field +/// showing whole numbers over a hundredth step still moves by hundredths. The field and the slider are Tab stops in the +/// order they are read: the field and then the slider when stacked, the slider and then the field when inline. A click +/// on the row's label focuses the number field in either layout. A log or power scale curves the slider's track only: +/// the field, typing and steps stay linear. #[derive(crate::contract::Component, crate::contract::Props)] pub struct SliderField<'a> { #[common] @@ -76,6 +94,11 @@ pub struct SliderField<'a> { /// The decimal places retained and shown for typed values (at most 12), independently of the step; typing no longer snaps to it. #[prop] typed_decimals: Option, + /// The decimals the number field shows: its own look (the default), exactly the step's, or exactly a fixed count, + /// a percent included ("66.70" with a step of 0.01, not the percent look's "66.7"). Typed values snap to the step as + /// they do without it. + #[prop] + field_decimals: FieldDecimals, /// The change of one wheel notch over the slider where it is coarser than the step. #[prop(quantity = "step")] wheel_step: Option, @@ -159,6 +182,7 @@ impl<'a> SliderField<'a> { scale: SliderScale::Linear, step: None, typed_decimals: None, + field_decimals: FieldDecimals::Look, wheel_step: None, track_press: TrackPress::OnRelease, unit_kind: None, @@ -198,6 +222,7 @@ impl<'a> SliderField<'a> { scale: self.scale, step: self.step, typed_decimals: self.typed_decimals, + field_decimals: self.field_decimals, wheel_step: self.wheel_step, unit_kind: self.unit_kind, unit: self.unit.clone(), @@ -228,6 +253,7 @@ struct Look { scale: SliderScale, step: Option, typed_decimals: Option, + field_decimals: FieldDecimals, wheel_step: Option, unit_kind: Option, unit: Option