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

This commit is contained in:
aiongg
2026-11-12 14:32:44 +00:00
parent 8fc8f79834
commit 0897874266
24 changed files with 115 additions and 39 deletions
@@ -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};
+1 -1
View File
@@ -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};
@@ -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, _| {
+2 -2
View File
@@ -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;
}
+2 -2
View File
@@ -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;
+2 -2
View File
@@ -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
{
+3 -3
View File
@@ -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 }));
}
+5 -3
View File
@@ -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 }));
}
+1 -1
View File
@@ -55,7 +55,7 @@ type SettleFn<'a> = Box<dyn FnMut(&mut BodyCx<'_>, &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")]
@@ -130,9 +130,13 @@ impl<C: Component> 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<S: Show>(&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()))
+6
View File
@@ -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.
+15 -1
View File
@@ -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<CommandScope>,
/// 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<Sizing>,
}
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<Variant>) -> 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<Sizing>,
/// `Common.description`.
pub(crate) description: Option<&'p str>,
/// `Common.tooltip`.
+1 -1
View File
@@ -1099,7 +1099,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option<ShowAt>, 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.
@@ -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
@@ -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,
@@ -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<C: Component>(
}
/// 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<Sizing>) -> 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
+1 -1
View File
@@ -20,7 +20,7 @@ use egui::Ui;
/// A select over `entries` in a field with its caption.
fn pick<T: Value>(ui: &mut Ui, caption: &'static str, value: &mut T, entries: &[Entry<T>]) {
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);
});
}
+2 -2
View File
@@ -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());
});
+8
View File
@@ -493,6 +493,13 @@ pub(crate) fn derive(input: TokenStream) -> syn::Result<TokenStream> {
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<TokenStream> {
fn common_mut(&mut self, _: ::craft_ui::contract::Internal) -> &mut ::craft_ui::contract::Common {
#common_mut
}
#set_sizing
}
#has_props
#content_painter
-1
View File
@@ -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."),
@@ -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<Entry<String>> = 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 {
@@ -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<Entry<u8>> {
.collect()
}
/// `select` sized to its widest entry when `fit` is on.
fn fitted<S: Props>(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
});
@@ -4,3 +4,4 @@ mod combo_list;
mod date;
mod select_list;
mod select_steps;
mod select_width;
@@ -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");
}