From 0897874266059c0af97bf3bfc8c8f40508586a46 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 12 Nov 2026 01:52:40 +0000 Subject: [PATCH] Every component takes one sizing setter: a leaf with Sizing::Content is as wide as its content, without its style's ideal width, and the selects the old gallery fitted to their entries are content-sized --- crates/draw/src/ui/brush_settings/sections.rs | 4 +-- crates/font-manager/src/missing.rs | 2 +- .../src/ui/adjust/basic/photo_filter.rs | 11 +++++--- crates/imaging/src/ui/adjust/levels_panel.rs | 4 +-- crates/imaging/src/ui/layer_style/list.rs | 4 +-- crates/imaging/src/ui/warp/fields.rs | 4 +-- crates/imaging/src/ui/warp/pin/bar.rs | 6 ++--- crates/imaging/src/ui/wide_angle/panel.rs | 8 +++--- crates/ui-canvas/src/canvas/full_window.rs | 2 +- crates/ui-contract/src/contract/cx/measure.rs | 6 ++++- crates/ui-contract/src/contract/mod.rs | 6 +++++ crates/ui-contract/src/contract/props.rs | 16 +++++++++++- crates/ui-contract/src/contract/run.rs | 2 +- .../ui-contract/src/contract/steps/apply.rs | 2 +- crates/ui-contract/src/contract/steps/env.rs | 1 + .../ui-contract/src/contract/steps/measure.rs | 11 ++++---- crates/ui-gallery/src/chrome/options.rs | 2 +- crates/ui-gallery/src/chrome/overview.rs | 4 +-- crates/ui-macros/src/component.rs | 8 ++++++ crates/ui-macros/src/props.rs | 1 - .../ui-patterns/src/patterns/dock/switcher.rs | 3 ++- .../ui-widgets/src/pickers/select/stories.rs | 20 +++++++++----- crates/ui-widgets/tests/it/pickers/mod.rs | 1 + .../tests/it/pickers/select_width.rs | 26 +++++++++++++++++++ 24 files changed, 115 insertions(+), 39 deletions(-) create mode 100644 crates/ui-widgets/tests/it/pickers/select_width.rs diff --git a/crates/draw/src/ui/brush_settings/sections.rs b/crates/draw/src/ui/brush_settings/sections.rs index 6e72b16b9e..6e01a28713 100644 --- a/crates/draw/src/ui/brush_settings/sections.rs +++ b/crates/draw/src/ui/brush_settings/sections.rs @@ -3,8 +3,8 @@ use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, IconId, ItemSource, Mixed, Selection, SelectionChange, Value}; use craft_keymap::{Chord, Key, Mods}; use craft_ui::contract::{ - ActivateOn, Bind, CollectionEvent, ColumnKind, ColumnSpec, Outcome, Remember as _, SelectMode, ShowCollection as _, ShowContainer as _, Sizing, - SpaceAction, SweepApply, SweepStep, ToggleColumn, ToggleEdit, + ActivateOn, Bind, CollectionEvent, ColumnKind, ColumnSpec, Outcome, Props as _, Remember as _, SelectMode, ShowCollection as _, + ShowContainer as _, Sizing, SpaceAction, SweepApply, SweepStep, ToggleColumn, ToggleEdit, }; use craft_ui::layout_components::Stack; use craft_ui::list::{ListRow, ToggleCell, ToggleState}; diff --git a/crates/font-manager/src/missing.rs b/crates/font-manager/src/missing.rs index be89ebacdb..e95222a227 100644 --- a/crates/font-manager/src/missing.rs +++ b/crates/font-manager/src/missing.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use craft_behavior::{DisplayOrder, ItemSource}; use craft_font_catalog::{Catalog, Match}; -use craft_ui::contract::{Bind, SaveKey, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, Props as _, SaveKey, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft_ui::display::Text; use craft_ui::form::{Field, FieldGroup}; diff --git a/crates/imaging/src/ui/adjust/basic/photo_filter.rs b/crates/imaging/src/ui/adjust/basic/photo_filter.rs index a1b1ef5759..8bb6d52b79 100644 --- a/crates/imaging/src/ui/adjust/basic/photo_filter.rs +++ b/crates/imaging/src/ui/adjust/basic/photo_filter.rs @@ -3,7 +3,7 @@ use craft_theme::Srgba; use craft_ui::choice::{Checkbox, Radio, RadioGroup, Swatch}; use craft_ui::contract::{ - Bind, EditResponse, Entry, LabelKind, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, SideLabel, + Bind, EditResponse, Entry, LabelKind, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, SideLabel, Sizing, }; use craft_ui::form::Field; use craft_ui::layout_components::Row; @@ -270,8 +270,13 @@ impl<'a> PhotoFilterEditor<'a> { Field::new(words.filter.clone()).side(SideLabel::new().kind(LabelKind::Hidden)).id_salt("filter").show(ui, |ui, _| { Row::new().show(ui, |ui, _| { Radio::new(false).label(words.filter.clone()).show(ui); - preset_edit = - Some(Select::new(words.filter.clone(), Bind::given(preset), &entries).enabled(!use_color).id_salt("preset").show(ui)); + preset_edit = Some( + Select::new(words.filter.clone(), Bind::given(preset), &entries) + .enabled(!use_color) + .sizing(Sizing::Content) + .id_salt("preset") + .show(ui), + ); }); }); Field::new(words.color.clone()).side(SideLabel::new().kind(LabelKind::Hidden)).id_salt("color").show(ui, |ui, _| { diff --git a/crates/imaging/src/ui/adjust/levels_panel.rs b/crates/imaging/src/ui/adjust/levels_panel.rs index e6ac08fb3e..441b913e07 100644 --- a/crates/imaging/src/ui/adjust/levels_panel.rs +++ b/crates/imaging/src/ui/adjust/levels_panel.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use craft_behavior::{EditEvent, EditEvents, Mixed}; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Pattern, Props, Remember as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Pattern, Props, Remember as _, Show as _, ShowContainer as _, Sizing, clicked}; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::pickers::Select; @@ -171,7 +171,7 @@ impl<'a> LevelsPanel<'a> { let mut auto = false; Row::new().show(ui, |ui, _| { Text::new(words.channel.clone()).shade(Shade::Muted).role(TypeRole::Label).show(ui); - let select = Select::new(words.channel.clone(), Bind::given(channel), &entries).show(ui); + let select = Select::new(words.channel.clone(), Bind::given(channel), &entries).sizing(Sizing::Content).show(ui); if let Some(&at) = select.value() { picked = at; } diff --git a/crates/imaging/src/ui/layer_style/list.rs b/crates/imaging/src/ui/layer_style/list.rs index 2c4a633a56..0f50eb0d50 100644 --- a/crates/imaging/src/ui/layer_style/list.rs +++ b/crates/imaging/src/ui/layer_style/list.rs @@ -2,8 +2,8 @@ use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, IconId, ItemSource, Selection, SelectionChange}; use craft_ui::contract::{ - ActivateOn, Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, CommandSet, Commands as _, Remember as _, SelectMode, ShowCollection as _, - Sizing, SpaceAction, SweepApply, SweepStep, ToggleColumn, + ActivateOn, Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, CommandSet, Commands as _, Props as _, Remember as _, SelectMode, + ShowCollection as _, Sizing, SpaceAction, SweepApply, SweepStep, ToggleColumn, }; use craft_ui::list::{List, ListRow, RowEvent, RowInk, ToggleCell, ToggleState, TrailingFace, TrailingPart}; use craft_ui::primitives::IconSpec; diff --git a/crates/imaging/src/ui/warp/fields.rs b/crates/imaging/src/ui/warp/fields.rs index b1b08870c3..17ad847752 100644 --- a/crates/imaging/src/ui/warp/fields.rs +++ b/crates/imaging/src/ui/warp/fields.rs @@ -261,7 +261,7 @@ impl<'a> WarpFields<'a> { Entry::new(WarpGridChoice::Four, words.four.clone()), Entry::new(WarpGridChoice::Five, words.five.clone()), ]; - let pick = Select::new(words.grid.clone(), Bind::given(values.grid), &entries).show(ui); + let pick = Select::new(words.grid.clone(), Bind::given(values.grid), &entries).sizing(Sizing::Content).show(ui); if let Some(&picked) = pick.value() && picked != values.grid && let Some(size) = picked.size() @@ -277,7 +277,7 @@ impl<'a> WarpFields<'a> { .filter(|entry| !(on_type && entry.custom)) .map(|entry| Entry::new(entry.key.clone(), entry.label.clone())) .collect(); - let pick = Select::new(words.warp.clone(), Bind::given(values.style.clone()), &entries).show(ui); + let pick = Select::new(words.warp.clone(), Bind::given(values.style.clone()), &entries).sizing(Sizing::Content).show(ui); if let Some(picked) = pick.value() && *picked != values.style { diff --git a/crates/imaging/src/ui/warp/pin/bar.rs b/crates/imaging/src/ui/warp/pin/bar.rs index 2545e4356c..477543940c 100644 --- a/crates/imaging/src/ui/warp/pin/bar.rs +++ b/crates/imaging/src/ui/warp/pin/bar.rs @@ -5,7 +5,7 @@ use craft_theme::variant::Tone; use craft_ui::bars::{Bar, BarKind}; use craft_ui::buttons::{Button, IconButton}; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing, clicked}; use craft_ui::display::{Divider, Text}; use craft_ui::form::Field; use craft_ui::pickers::Select; @@ -112,7 +112,7 @@ fn body(ui: &mut Ui, session: &PinWarpSession, words: &PinWarpBarWords, notice: Entry::new(PinMode::Distort, words.distort.clone()), ]; captioned(ui, &words.mode, |ui| { - let picked = Select::new(words.mode.clone(), Bind::given(options.mode), &modes).show(ui); + let picked = Select::new(words.mode.clone(), Bind::given(options.mode), &modes).sizing(Sizing::Content).show(ui); if let Some(&mode) = picked.value().filter(|&&mode| mode != options.mode) { edits.push(PinEdit::Options(PinWarpOptions { mode, ..options })); } @@ -123,7 +123,7 @@ fn body(ui: &mut Ui, session: &PinWarpSession, words: &PinWarpBarWords, notice: Entry::new(PinDensity::More, words.more_points.clone()), ]; captioned(ui, &words.density, |ui| { - let picked = Select::new(words.density.clone(), Bind::given(options.density), &densities).show(ui); + let picked = Select::new(words.density.clone(), Bind::given(options.density), &densities).sizing(Sizing::Content).show(ui); if let Some(&density) = picked.value().filter(|&&density| density != options.density) { edits.push(PinEdit::Options(PinWarpOptions { density, ..options })); } diff --git a/crates/imaging/src/ui/wide_angle/panel.rs b/crates/imaging/src/ui/wide_angle/panel.rs index 92e1dede59..cbd44d6aca 100644 --- a/crates/imaging/src/ui/wide_angle/panel.rs +++ b/crates/imaging/src/ui/wide_angle/panel.rs @@ -6,7 +6,7 @@ use craft_behavior::{EditEvent, EditEvents, Mixed}; use craft_theme::{ControlSize, TypeRole}; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, Sizing, clicked}; use craft_ui::display::{Shade, Text}; use craft_ui::form::SliderField; use craft_ui::layout_components::{Row, Stack}; @@ -135,8 +135,10 @@ impl<'a> WideAnglePanel<'a> { Entry::new(ConstraintOrientation::Vertical, words.vertical.clone()), ]; let name = words.orientation_of.fill(&[("n", number.as_str())]); - let select = - Select::new(name, Bind::given(row.orientation), &orientations).size(ControlSize::Sm).id_salt(("orientation", index)); + let select = Select::new(name, Bind::given(row.orientation), &orientations) + .size(ControlSize::Sm) + .sizing(Sizing::Content) + .id_salt(("orientation", index)); if let Some(&orientation) = select.show(ui).value() { constraint = constraint.take().or(Some(WideAngleConstraintEdit::Orient { index, orientation })); } diff --git a/crates/ui-canvas/src/canvas/full_window.rs b/crates/ui-canvas/src/canvas/full_window.rs index ba28ec7a2a..75209a2586 100644 --- a/crates/ui-canvas/src/canvas/full_window.rs +++ b/crates/ui-canvas/src/canvas/full_window.rs @@ -55,7 +55,7 @@ type SettleFn<'a> = Box, &mut [FooterButton]) + 'a>; pub struct FullWindowDialog<'a> { #[common] common: Common, - #[container(sizing, surface, live, end, position, collection_body)] + #[container(surface, live, end, position, collection_body)] props: ContainerProps, /// Binds the open state to `open`. #[prop(name = "opened")] diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index 683dda936f..3cebff7c45 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -130,9 +130,13 @@ impl MeasureCx<'_, C> { } /// The size `face` has when `PaintUi::face` shows it as the look of a part: steps 1, 2 and 4 of the face run - /// under the composite's resolved `enabled` and `size`. A composite measured at its least measures the face at + /// under the composite's resolved `enabled`, `size` and sizing. A composite measured at its least measures the face at /// its least; otherwise the face has no proposal. pub fn face(&self, mut face: S) -> Vec2 { + // The face is the composite's look: a composite sized to its content sizes its face so. + if let Some(sizing) = self.resolved.sizing { + face.set_sizing(sizing, crate::contract::Internal::new()); + } let id = self.id.with("face"); let proposal = if self.proposal == Proposal::Min { Proposal::Min } else { Proposal::Ideal }; crate::contract::measure_under(&mut face, self.ui, Some(id), proposal, Some(&self.under())) diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index ab5da2b9f1..192435e7a6 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -221,6 +221,12 @@ pub trait Meta { fn common(&self, _: Internal) -> &Common; #[doc(hidden)] fn common_mut(&mut self, _: Internal) -> &mut Common; + /// Takes the caller's `Props::sizing`: a leaf keeps it in its `Common`; the derive writes a container's or a + /// collection's into its `ContainerProps`, over the default its constructor set. + #[doc(hidden)] + fn set_sizing(&mut self, sizing: Sizing, _: Internal) { + self.common_mut(Internal::new()).sizing = Some(sizing); + } } /// Written by the derive from a `#[container]` field, for containers and collections. diff --git a/crates/ui-contract/src/contract/props.rs b/crates/ui-contract/src/contract/props.rs index c82dfee44b..d9829289e3 100644 --- a/crates/ui-contract/src/contract/props.rs +++ b/crates/ui-contract/src/contract/props.rs @@ -1,6 +1,6 @@ //! `Common`, `Props`, `Resolved` and `Tooltip` (chapter 3). -use super::{IdSource, Internal, Meta}; +use super::{IdSource, Internal, Meta, Sizing}; use crate::runtime::commands::{CommandRef, CommandScope}; use crate::runtime::env::Label; use craft_behavior::DocKey; @@ -34,6 +34,8 @@ pub struct Common { pub(crate) command_scope: Option, /// The component's horizontal axis keeps its left-to-right order under a right-to-left interface. pub(crate) ltr_axis: bool, + /// A leaf's `Props::sizing`; a container or collection keeps it in its `ContainerProps`. + pub(crate) sizing: Option, } impl Common { @@ -56,6 +58,7 @@ impl Common { doc_key: None, command_scope: None, ltr_axis: false, + sizing: None, } } } @@ -98,6 +101,15 @@ pub trait Props: Meta + Sized { self } + /// How the component takes its size. A container or collection takes it over its own default (`ContainerProps`). + /// A leaf with `Sizing::Content` is as wide as its content, without the ideal width its style asks for where the + /// room allows (a field's `size.length.field`); a leaf otherwise keeps that width, and fills only along the axis + /// its `Component::fills` names. + fn sizing(mut self, sizing: Sizing) -> Self { + self.set_sizing(sizing, Internal::new()); + self + } + /// The variant; one the component does not accept gives its default. fn variant(mut self, variant: impl Into) -> Self { self.common_mut(Internal::new()).variant = Some(variant.into()); @@ -204,6 +216,8 @@ pub struct Resolved<'p> { pub(crate) default_stop: bool, /// `Common.ltr_axis`. pub(crate) ltr_axis: bool, + /// `Common.sizing`: a leaf's own sizing. + pub(crate) sizing: Option, /// `Common.description`. pub(crate) description: Option<&'p str>, /// `Common.tooltip`. diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index ef0fc9a406..8871291fa8 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1099,7 +1099,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h /// Step 5's size for `input`: what the component measures plus `extent`, padded and bounded by its style. fn measured(t: &mut dyn Erased, input: &MeasureIn<'_>, style: &dyn StyleView, resolved: &Resolved<'_>, extent: Vec2) -> (Vec2, Inputs) { let (content, inputs) = t.measure_content(input, resolved); - (steps::measure(style, input, content, extent), inputs) + (steps::measure(style, input, content, extent, resolved.sizing), inputs) } /// The pipeline: steps 1 to 17 for one component, whatever its type and shape. diff --git a/crates/ui-contract/src/contract/steps/apply.rs b/crates/ui-contract/src/contract/steps/apply.rs index 2a188f1b6a..66003e35a0 100644 --- a/crates/ui-contract/src/contract/steps/apply.rs +++ b/crates/ui-contract/src/contract/steps/apply.rs @@ -174,7 +174,7 @@ pub(crate) fn rerun_after_edit( let resized = if leaf { earlier.samples.iter().any(|sample| { let input = MeasureIn { ui: input.ui, env: input.env, proposal: sample.proposal, room: sample.room }; - measure(style, &input, p.measure_content(&input, resolved).0, Vec2::ZERO) != sample.took + measure(style, &input, p.measure_content(&input, resolved).0, Vec2::ZERO, resolved.sizing) != sample.took }) } else { earlier.measured diff --git a/crates/ui-contract/src/contract/steps/env.rs b/crates/ui-contract/src/contract/steps/env.rs index 08fa88aa60..897a5ae393 100644 --- a/crates/ui-contract/src/contract/steps/env.rs +++ b/crates/ui-contract/src/contract/steps/env.rs @@ -63,6 +63,7 @@ pub(crate) fn resolved<'p>(id: Id, step: &'p EnvStep, common: &'p Common) -> Res access_key: common.access_key, default_stop: common.default_stop, ltr_axis: common.ltr_axis, + sizing: common.sizing, description: common.description.as_deref(), tooltip: common.tooltip.as_ref(), doc_key: common.doc_key, diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index a2b65b221c..e18df81e0b 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -2,7 +2,7 @@ use super::ShapeKind; use crate::contract::cx::MeasureCx; -use crate::contract::{Component, Resolved, ValueOf}; +use crate::contract::{Component, Resolved, Sizing, ValueOf}; use crate::runtime::env::Env; use crate::runtime::layout_memory::{self, Inputs}; use crate::style::{ComponentStyle, StyleView}; @@ -31,9 +31,10 @@ pub(crate) fn measure_content( } /// Step 5, measure: the `content` size plus padding, then `max(min_size)`, and for any proposal but `Min` at least the -/// ideal width, up to the room. At `Min` a least width the style sets takes the place of `min_size`'s width. `extent` -/// is what the shape adds to the content: a body's remembered size or a collection's content size. -pub(crate) fn measure(style: &dyn StyleView, input: &MeasureIn<'_>, content: Vec2, extent: Vec2) -> Vec2 { +/// ideal width, up to the room, unless the component is sized to its content (`sizing`, a leaf's `Sizing::Content`). +/// At `Min` a least width the style sets takes the place of `min_size`'s width. `extent` is what the shape adds to the +/// content: a body's remembered size or a collection's content size. +pub(crate) fn measure(style: &dyn StyleView, input: &MeasureIn<'_>, content: Vec2, extent: Vec2, sizing: Option) -> Vec2 { let metrics = style.metrics(); let content = content + extent; let padding = Vec2::new(metrics.padding.start + metrics.padding.end, metrics.padding.top + metrics.padding.bottom); @@ -42,7 +43,7 @@ pub(crate) fn measure(style: &dyn StyleView, input: &MeasureIn<'_>, content: Vec _ => metrics.min_size, }; let mut size = (content + padding).max(floor); - if input.proposal != Proposal::Min { + if input.proposal != Proposal::Min && sizing != Some(Sizing::Content) { size.x = size.x.max(input.room.map_or(metrics.ideal_width, |room| metrics.ideal_width.min(room))); } size diff --git a/crates/ui-gallery/src/chrome/options.rs b/crates/ui-gallery/src/chrome/options.rs index 813fec4a0f..c6f0fbc5b4 100644 --- a/crates/ui-gallery/src/chrome/options.rs +++ b/crates/ui-gallery/src/chrome/options.rs @@ -20,7 +20,7 @@ use egui::Ui; /// A select over `entries` in a field with its caption. fn pick(ui: &mut Ui, caption: &'static str, value: &mut T, entries: &[Entry]) { Field::new(caption).sizing(Sizing::Content).show(ui, |ui, _| { - Select::new(caption, Bind::bound(&mut *value), entries).show(ui); + Select::new(caption, Bind::bound(&mut *value), entries).sizing(Sizing::Content).show(ui); }); } diff --git a/crates/ui-gallery/src/chrome/overview.rs b/crates/ui-gallery/src/chrome/overview.rs index 35e4c3dc2c..688dff19fa 100644 --- a/crates/ui-gallery/src/chrome/overview.rs +++ b/crates/ui-gallery/src/chrome/overview.rs @@ -8,7 +8,7 @@ use crate::viewer::{Catalog, ComponentInfo, PanelId, TreeKey, by_level, entry_of use craft_behavior::{ColumnWidth, Selection}; use craft_theme::variant::Tone; use craft_theme::{Tokens, TypeRole}; -use craft_ui::contract::{Bind, BodyCx, Entry, Gap, Lazy, Pad, Props as _, Scroll, Show as _, ShowContainer as _, StoryLayout}; +use craft_ui::contract::{Bind, BodyCx, Entry, Gap, Lazy, Pad, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, StoryLayout}; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::{Grid, Row, Stack}; use craft_ui::notices::Notice; @@ -259,7 +259,7 @@ pub(super) fn overview(ui: &mut Ui, p: &mut Panels<'_>) { ran = true; Row::new().show(ui, |ui, _| { Text::new("Level:").shade(Shade::Muted).show(ui); - Select::new("Level", Bind::bound(&mut chosen), &entries).show(ui); + Select::new("Level", Bind::bound(&mut chosen), &entries).sizing(Sizing::Content).show(ui); }); reported = grid(ui, level.title(), Some(PanelId::Overview), &cards, p, false, follow.flatten()); }); diff --git a/crates/ui-macros/src/component.rs b/crates/ui-macros/src/component.rs index 6c46cabff4..406fe4d6ef 100644 --- a/crates/ui-macros/src/component.rs +++ b/crates/ui-macros/src/component.rs @@ -493,6 +493,13 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result { Some(field) => (quote!(&self.#field), quote!(&mut self.#field)), None => return Err(syn::Error::new_spanned(ident, "`#[common]` needs a named field")), }; + let set_sizing = marked.container.and_then(|field| field.ident.as_ref()).map(|field| { + quote! { + fn set_sizing(&mut self, sizing: ::craft_ui::contract::Sizing, _: ::craft_ui::contract::Internal) { + self.#field.sizing = sizing; + } + } + }); let has_props = marked.container.and_then(|field| field.ident.as_ref()).map(|field| { quote! { impl #impl_generics ::craft_ui::contract::HasProps for #ident #type_generics #where_clause { @@ -551,6 +558,7 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result { fn common_mut(&mut self, _: ::craft_ui::contract::Internal) -> &mut ::craft_ui::contract::Common { #common_mut } + #set_sizing } #has_props #content_painter diff --git a/crates/ui-macros/src/props.rs b/crates/ui-macros/src/props.rs index bc9c4c1094..e1a490bb64 100644 --- a/crates/ui-macros/src/props.rs +++ b/crates/ui-macros/src/props.rs @@ -204,7 +204,6 @@ const COLLECTION: &[Forwarded] = &[ /// caller under the builder's own name. A new `ContainerProps` builder of that kind is added here. Builders whose name /// a component writes itself (`label`, `header`, `footer`, `scroll`) stay off the list. const CONTAINER: &[Forwarded] = &[ - ("sizing", "::craft_ui::contract::Sizing", "How the component takes its size: to its content or to the room it has."), ("command_scope", "::craft_ui::runtime::commands::CommandScope", "Commands of `scope` reach the component while focus is in it."), ("surface", "::craft_ui::style::SurfaceKind", "The surface painted behind the body."), ("live", "::craft_ui::contract::Politeness", "The body is a live region announced with this politeness."), diff --git a/crates/ui-patterns/src/patterns/dock/switcher.rs b/crates/ui-patterns/src/patterns/dock/switcher.rs index 5dabb8a146..7a8b944971 100644 --- a/crates/ui-patterns/src/patterns/dock/switcher.rs +++ b/crates/ui-patterns/src/patterns/dock/switcher.rs @@ -3,7 +3,7 @@ #[cfg(feature = "testing")] mod stories; -use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _}; +use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, Sizing}; use crate::display::Divider; use crate::docking::{DockWords, WorkspaceCommands}; use crate::menu::MenuItem; @@ -56,6 +56,7 @@ impl<'a, P> WorkspaceSwitcher<'a, P> { let entries: Vec> = set.builtin.iter().chain(&set.saved).map(|w| Entry::new(w.id.clone(), w.name.clone())).collect(); let shown = Select::new(words.choose_workspace.clone(), Bind::given(set.current.clone()), &entries) .size(ControlSize::Sm) + .sizing(Sizing::Content) .header_menu(|ui, _| { for ran in [WorkspaceCommands::Reset, WorkspaceCommands::New, WorkspaceCommands::Delete, WorkspaceCommands::Lock] { if ran == WorkspaceCommands::Lock { diff --git a/crates/ui-widgets/src/pickers/select/stories.rs b/crates/ui-widgets/src/pickers/select/stories.rs index 7696c76366..fb5b2afc78 100644 --- a/crates/ui-widgets/src/pickers/select/stories.rs +++ b/crates/ui-widgets/src/pickers/select/stories.rs @@ -1,7 +1,7 @@ //! Stories of `Select`. use super::Select; -use crate::contract::{Bind, Entry, Props as _, Role, Show as _, ShowContainer as _, Validity}; +use crate::contract::{Bind, Entry, Props, Role, Show as _, ShowContainer as _, Sizing, Validity}; use crate::contract::{LabelAlign, SideLabel}; use crate::form::{Field, FieldGroup}; use crate::primitives::IconSpec; @@ -41,6 +41,11 @@ fn tools() -> Vec> { .collect() } +/// `select` sized to its widest entry when `fit` is on. +fn fitted(select: S, fit: bool) -> S { + if fit { select.sizing(Sizing::Content) } else { select } +} + /// A row of the states story: the label column starts at the left edge, as the form list does. fn row(label: &'static str) -> Field { Field::new(label).side(SideLabel::new().align(LabelAlign::Start)).id_salt(label) @@ -50,23 +55,26 @@ fn row(label: &'static str) -> Field { fn select(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let size = *data.choice("size", ControlSize::Md, &[("Sm", ControlSize::Sm), ("Md", ControlSize::Md)]); let disabled = *data.value("disabled", false); + let fit = *data.value("fit", false); let units = units(); let unit = data.choice("unit", 0u8, &[("Pixels", 0), ("Inches", 1), ("Centimetres", 2), ("Points", 3)]); let out = FieldGroup::new("Select states").show(ui, |ui, _| { - let first = row("Units").show(ui, |ui, _| Select::new("Units", Bind::bound(unit), &units).size(size).enabled(!disabled).show(ui)); + let first = + row("Units").show(ui, |ui, _| fitted(Select::new("Units", Bind::bound(unit), &units).size(size).enabled(!disabled), fit).show(ui)); row("Resampling").show(ui, |ui, _| { - Select::new("Resampling", Bind::bound(&mut 1u8), &resampling()).size(size).enabled(!disabled).show(ui); + fitted(Select::new("Resampling", Bind::bound(&mut 1u8), &resampling()).size(size).enabled(!disabled), fit).show(ui); }); row("Tool").show(ui, |ui, _| { - Select::new("Tool", Bind::bound(&mut 0u8), &tools()).size(size).enabled(!disabled).show(ui); + fitted(Select::new("Tool", Bind::bound(&mut 0u8), &tools()).size(size).enabled(!disabled), fit).show(ui); }); let profiles = [Entry::new(0u8, "sRGB"), Entry::new(1, "Display P3"), Entry::new(2, "Adobe RGB")]; let mut none = u8::MAX; row("No choice").show(ui, |ui, _| { - Select::new("Profile", Bind::bound(&mut none), &profiles).placeholder("Choose a profile").size(size).enabled(!disabled).show(ui); + fitted(Select::new("Profile", Bind::bound(&mut none), &profiles).placeholder("Choose a profile").size(size).enabled(!disabled), fit) + .show(ui); }); row("Disabled").show(ui, |ui, _| { - Select::new("Locked units", Bind::bound(&mut 2u8), &units).size(size).enabled(false).show(ui); + fitted(Select::new("Locked units", Bind::bound(&mut 2u8), &units).size(size).enabled(false), fit).show(ui); }); first.inner }); diff --git a/crates/ui-widgets/tests/it/pickers/mod.rs b/crates/ui-widgets/tests/it/pickers/mod.rs index ea8b0173c4..e4a98ee876 100644 --- a/crates/ui-widgets/tests/it/pickers/mod.rs +++ b/crates/ui-widgets/tests/it/pickers/mod.rs @@ -4,3 +4,4 @@ mod combo_list; mod date; mod select_list; mod select_steps; +mod select_width; diff --git a/crates/ui-widgets/tests/it/pickers/select_width.rs b/crates/ui-widgets/tests/it/pickers/select_width.rs new file mode 100644 index 0000000000..094c7435c6 --- /dev/null +++ b/crates/ui-widgets/tests/it/pickers/select_width.rs @@ -0,0 +1,26 @@ +//! A select's width: the field width by default, its widest entry when it is sized to its content. + +use craft_ui::contract::{Bind, Entry, Props as _, Show as _, Sizing}; +use craft_ui::pickers::Select; +use craft_ui::testing::{Fixture, trial}; +use std::cell::Cell; +use std::rc::Rc; + +/// A select sized to its content is narrower than the field width a select takes by default, and still shows its +/// widest entry whole. +#[trial] +fn a_content_sized_select_fits_its_widest_entry() { + let rects = Rc::new(Cell::new([egui::Rect::NOTHING; 2])); + let seen = rects.clone(); + let mut fixture = Fixture::new(move |ui| { + let entries = [Entry::new(0u8, "One"), Entry::new(1u8, "Twelve")]; + let plain = Select::new("Plain", Bind::given(1u8), &entries).show(ui).response.rect; + let fitted = Select::new("Fitted", Bind::given(1u8), &entries).sizing(Sizing::Content).show(ui).response.rect; + seen.set([plain, fitted]); + }); + fixture.settle(); + let [plain, fitted] = rects.get(); + assert!(fitted.width() < plain.width(), "the content-sized select is narrower than the default one: {fitted:?} {plain:?}"); + let shown = fixture.texts().iter().find(|run| run.text == "Twelve" && fitted.contains_rect(run.rect)).map(|run| run.elided); + assert_eq!(shown, Some(false), "the content-sized select shows its widest entry whole inside its box"); +}