views-w2: net change of 3 commits

- views-w2: written by an agent
- views-w2: review fixes (review-1)
- owed by graph-w1 (views-w2 review 1): the collection's fill share reads weight_of, so a non-positive or non-finite weight counts as 1
This commit is contained in:
Dylan M. Taylor committed 2026-11-28 13:52:35 -05:00
1 parent 812e0745aa
commit 9a46b3f2f4
18 files changed
+314 -72

No files matched your search

+12 -11
View File
@@ -382,6 +382,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 {
let props = comp.props(Internal::new());
let weight = layout::body::weight_of(comp.common(Internal::new()));
match self.sizing(props) {
Sizing::Fill => {
use craft_behavior::Axis;
@@ -390,8 +391,8 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
// size once the room is less.
let room = crate::layout::flow_room(ui);
let (x, y) = (
crate::layout::fill_size(ui, id, Axis::X, size.x, room.x, self.given.0, 1.0), // P3(views-w2): vw.F2
crate::layout::fill_size(ui, id, Axis::Y, size.y, room.y, self.given.1, 1.0), // P3(views-w2): vw.F2
crate::layout::fill_size(ui, id, Axis::X, size.x, room.x, self.given.0, weight),
crate::layout::fill_size(ui, id, Axis::Y, size.y, room.y, self.given.1, weight),
);
Vec2::new(x, y)
}
@@ -404,18 +405,16 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
let room = if held { room.min(crate::layout::flow_room(ui).x) } else { room };
// Given the height of the row line it sits on, it fills that line (`given_axes`).
let height = if self.given.1 {
crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, crate::layout::flow_room(ui).y, true, 1.0) // P3(views-w2): vw.F2
crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, crate::layout::flow_room(ui).y, true, weight)
} else {
size.y
};
// P3(views-w2): vw.F2
Vec2::new(crate::layout::fill_size(ui, id, craft_behavior::Axis::X, size.x, room, self.given.0 || held, 1.0), height)
Vec2::new(crate::layout::fill_size(ui, id, craft_behavior::Axis::X, size.x, room, self.given.0 || held, weight), height)
}
// Its content's width, and the height as `Fill` takes it.
Sizing::FillHeight => {
let room = crate::layout::flow_room(ui);
// P3(views-w2): vw.F2
Vec2::new(size.x, crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, room.y, self.given.1, 1.0))
Vec2::new(size.x, crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, room.y, self.given.1, weight))
}
Sizing::Content => size,
}
@@ -1881,10 +1880,12 @@ impl BodyHooks<'_> {
let id = cx.core.id;
let open = if self.open_given { self.open } else { open_now(comp, &mut *cx.core.memory, id, props) };
let flows = matches!(at.at, ShowAt::Flow) && self.in_flow(comp);
self.measure_open_room(at, id, open, flows)
let weight = layout::body::weight_of(comp.common(Internal::new()));
self.measure_open_room(at, id, open, flows, weight)
}
fn measure_open_room(&mut self, at: &Measuring<'_, '_>, id: Id, open: bool, flows: bool) -> Result<bool, Vec2> {
/// `measure_room` once the body knows whether it is open; `weight` is the body's fill weight (`weight_of`).
fn measure_open_room(&mut self, at: &Measuring<'_, '_>, id: Id, open: bool, flows: bool, weight: f32) -> Result<bool, Vec2> {
let props = Arc::clone(&self.props);
self.open = open || self.shown_closed;
self.open_at_read = self.open;
@@ -1938,11 +1939,11 @@ impl BodyHooks<'_> {
return Err(Vec2::ZERO);
}
if let Some(share) = crate::layout::fill_share(at.ui, x).filter(|_| flows && self.given.0) {
self.room.x = share;
self.room.x = share * weight;
}
let mut scrolled_share = false;
if let Some(share) = crate::layout::fill_share(at.ui, y).filter(|_| flows && self.given.1) {
self.room.y = share;
self.room.y = share * weight;
scrolled_share = scrolled_y;
}
// A body that fills both axes its parent gives it takes the room, whatever its contents take: a parent's
@@ -202,7 +202,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
let width = if self.content_sized(comp) || self.from_content.0 {
size.x
} else {
let weight = comp.common(Internal::new()).fill_weight.unwrap_or(1.0);
let weight = crate::layout::body::weight_of(comp.common(Internal::new()));
crate::layout::body::fill_size(ui, id, Axis::X, size.x, self.room.x, true, weight)
};
let height = match (self.scrolls && self.room.y.is_finite(), sizing) {
+13 -10
View File
@@ -90,11 +90,13 @@ impl Lazy {
// runs or not, so what scrolls into reach does not change the body's content.
let real = !sizing && !crate::runtime::measure::active(&ctx);
// A memoized view whose content filled the axis the body around it shares is one of the children that fill
// that body: a real run shows it in its share, as the body gives a child that fills it directly.
// that body: a real run shows it in its share, its content's weight times the share of one, as the body gives a
// child that fills it directly.
let share = env
.shares()
.filter(|axis| memo && real && lazy::fills(&ctx, id, sizing) == Some(*axis))
.and_then(|axis| crate::layout::fill_share(ui, axis).map(|share| (axis, share)));
.filter(|_| memo && real)
.and_then(|axis| lazy::fills(&ctx, id, sizing).filter(|(along, _)| *along == axis))
.and_then(|(axis, weight)| crate::layout::fill_share(ui, axis).map(|share| (axis, share * weight)));
// A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width
// its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not
// narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a
@@ -204,7 +206,7 @@ impl Lazy {
let rect = child.min_rect();
// The child `Ui` writes its widget rect when it drops: the record holds it as written.
drop(child);
let fills = if memo { crate::layout::take_view_fill(&ctx, id).map(|(axis, _weight)| axis) } else { None }; // P3(views-w2): vw.F2
let fills = if memo { crate::layout::take_view_fill(&ctx, id) } else { None };
let record = run.recording.then(|| replay::close(&ctx, place.layer));
if let Some(shift) = audited {
return place_audit_run(ui, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run);
@@ -326,18 +328,19 @@ fn share_of(region: Rect, rtl: bool, axis: Axis, share: f32) -> Rect {
/// Places the extent `rect` of the memoized view `id` in flow in `ui` (`place_view`) as one unit of the body around it,
/// and returns the rect it took. `fills` is the axis the body shares which the view's content filled in a measuring
/// run: the view is then one of the children that fill the body, as a child shown there directly is. It takes its
/// share along the axis once the body knows it; in the first sweep of the body's measuring run it is counted and takes
/// run, with the filling child's weight: the view is then one of the children that fill the body, as a child shown
/// there directly is. It takes its share along the axis once the body knows it; in the first sweep of the body's
/// measuring run it is counted with that weight and takes
/// nothing there (`counting_fills`), outside the least measure, where it takes what its content took. In a shrinking
/// row it is a unit that does not narrow below what it takes, as a body that fills the row is.
///
/// Any other view reports its extent to the shrinking row around it: what it takes, in the row's counting sweep, and
/// its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows from what it takes
/// in no room down to what it takes with every leaf at its least.
fn place_unit(ui: &mut Ui, (shrink, fills): (Option<Shrink>, Option<Axis>), id: egui::Id, rect: Rect, rtl: bool) -> Rect {
fn place_unit(ui: &mut Ui, (shrink, fills): (Option<Shrink>, Option<(Axis, f32)>), id: egui::Id, rect: Rect, rtl: bool) -> Rect {
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let Some(axis) = fills.filter(|axis| env.shares() == Some(*axis)) else {
let Some((axis, weight)) = fills.filter(|(axis, _)| env.shares() == Some(*axis)) else {
let took = place_view(ui, rect);
match shrink {
Some(Shrink::Count(row)) => crate::layout::report_shrink(&ctx, row, id, rect.width(), rect.width(), None, (false, None)),
@@ -348,9 +351,9 @@ fn place_unit(ui: &mut Ui, (shrink, fills): (Option<Shrink>, Option<Axis>), id:
};
let content = rect.size();
let along = match crate::layout::fill_share(ui, axis) {
Some(share) => Some(share),
Some(share) => Some(share * weight),
None if crate::layout::counting_fills(ui, axis) && !env.least => {
crate::layout::count_fill_view(ui, 1.0); // P3(views-w2): vw.F2
crate::layout::count_fill_view(ui, weight);
Some(0.0)
}
None => None,
+4 -5
View File
@@ -39,8 +39,7 @@ pub struct Common {
pub(crate) ltr_axis: bool,
/// A leaf's `Props::sizing`; a container or collection keeps it in its `ContainerProps`.
pub(crate) sizing: Option<Sizing>,
/// `Props::fill_weight`.
#[allow(dead_code)] // P3(views-w2): vw.F1
/// `Props::fill_weight`; read through `layout::weight_of`, which applies the default.
pub(crate) fill_weight: Option<f32>,
}
@@ -136,9 +135,9 @@ pub trait Props: Meta + Sized {
/// A child filling the main axis of a `Stack` or `Row` takes `weight` shares of the room left; the default is 1, and
/// a non-finite or non-positive weight counts as 1.
fn fill_weight(self, weight: f32) -> Self {
let _ = weight;
todo!("vw.F1")
fn fill_weight(mut self, weight: f32) -> Self {
self.common_mut(Internal::new()).fill_weight = Some(weight);
self
}
/// The variant; one the component does not accept gives its default.
+4 -2
View File
@@ -338,13 +338,15 @@ impl<C: Component> ShapeHooks<C> for LeafHooks {
// A leaf is given an axis its enclosing body does not size from its content: there it fills, elsewhere it keeps
// its measured size, so it never sets that size.
let content = Env::of(ui).content;
let common = comp.common(super::Internal::new());
let weight = crate::layout::body::weight_of(common);
let fill = |measured: f32, offered: f32, along: Axis| {
let given = if along == Axis::X { !content.0 } else { !content.1 };
crate::layout::fill_size(ui, id, along, measured, offered, given, 1.0) // P3(views-w2): vw.F2
crate::layout::fill_size(ui, id, along, measured, offered, given, weight)
};
// The control beside an inspector's label fills the cell the label leaves, unless its caller sized it to its
// content.
let sizing = comp.common(super::Internal::new()).sizing;
let sizing = common.sizing;
if sizing == Some(super::Sizing::Fill) {
return Vec2::new(fill(size.x, room.x, Axis::X), fill(size.y, room.y, Axis::Y));
}
+27 -15
View File
@@ -137,12 +137,13 @@ impl BodyLayout {
#[derive(Default)]
pub(crate) struct Cursors(IdMap<Cursor>);
/// The number of children that fill the main axis of each `Stack` or `Row` body measured this pass, by body id.
/// The sum of the weights of the children that fill the main axis of each `Stack` or `Row` body measured this pass, by
/// body id.
#[derive(Default)]
pub(crate) struct FillCounts(IdMap<f32>);
/// The memoized views running this pass whose content holds a direct child that fills the axis the body around the
/// view shares (`Scoped::fill_view`), by view id, with that axis.
/// view shares (`Scoped::fill_view`), by view id, with that axis and the filling child's weight.
#[derive(Default)]
pub(crate) struct ViewFills(IdMap<(Axis, f32)>);
@@ -414,7 +415,8 @@ enum MainFill {
///
/// `given` is the caller's own fact: whether the child is given `axis` (a leaf where its body does not size from its
/// content, a container given the axis or held across its column, a collection where it fills). `offered` is the room
/// the flow offers it along `axis`, `measured` what it measured.
/// the flow offers it along `axis`, `measured` what it measured. `weight` is the child's `weight_of`: a share `s` is the
/// share of one weight, which the child takes `weight` times.
pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32, given: bool, weight: f32) -> f32 {
let env = Env::of(ui);
// Across an unwrapped row's content-height line a child that fills is shown across the line the row settled on in
@@ -436,7 +438,7 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32
if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, axis).is_some() {
return match main_fill(ui, id, axis, weight) {
MainFill::Measuring => 0.0,
MainFill::Share(share, _) => measured.max(share),
MainFill::Share(share, _) => measured.max(share * weight),
MainFill::Room(_) => measured,
};
}
@@ -445,11 +447,17 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32
}
match main_fill(ui, id, axis, weight) {
MainFill::Measuring => 0.0,
MainFill::Share(share, least) => least.max(share),
MainFill::Share(share, least) => least.max(share * weight),
MainFill::Room(least) => least.max(offered),
}
}
/// The weight a component that fills the main axis of its body takes shares of the room by (`Props::fill_weight`):
/// 1 when unset, and a non-finite or non-positive weight counts as 1, so a share is never negative or empty.
pub(crate) fn weight_of(common: &crate::contract::Common) -> f32 {
common.fill_weight.filter(|weight| weight.is_finite() && *weight > 0.0).unwrap_or(1.0)
}
/// What the child `id` of `ui`'s body that fills along `axis` takes there, with its least along it
/// (`layout_memory::fill_least`). Called once per such child and run.
fn main_fill(ui: &Ui, id: Id, axis: Axis, weight: f32) -> MainFill {
@@ -466,13 +474,15 @@ fn main_fill(ui: &Ui, id: Id, axis: Axis, weight: f32) -> MainFill {
MainFill::Room(layout_memory::fill_least(ui.ctx(), id, axis))
}
/// Counts one child that fills the main axis of the sharing body `body`, in the first sweep of its measuring run.
/// Counts one child that fills the main axis of the sharing body `body` with its weight, in the first sweep of its
/// measuring run.
fn count_fill(ctx: &egui::Context, body: Id, weight: f32) {
pass_state::with::<FillCounts, _>(ctx, |counts| *counts.0.entry(body).or_insert(0.0) += weight);
}
/// Counts the memoized view whose content fills the main axis of `ui`'s sharing body as one child that fills it, in the
/// first sweep of the body's measuring run (`counting_fills`), as a child shown there directly is counted.
/// Counts the memoized view whose content fills the main axis of `ui`'s sharing body as one child that fills it with
/// `weight`, the weight its filling content recorded (`take_view_fill`), in the first sweep of the body's measuring run
/// (`counting_fills`), as a child shown there directly is counted.
pub(crate) fn count_fill_view(ui: &Ui, weight: f32) {
if let Some((body, _)) = Env::of(ui).fill_body {
count_fill(ui.ctx(), body, weight);
@@ -484,14 +494,15 @@ pub(crate) fn open_view_fill(ctx: &egui::Context, view: Id) {
pass_state::with::<ViewFills, _>(ctx, |fills| fills.0.remove(&view));
}
/// The axis the content of the memoized view `view` filled in the run that just ended, as `fill_size` noted it; closes
/// the record.
/// The axis the content of the memoized view `view` filled in the run that just ended, with the filling child's weight,
/// as `fill_size` noted them; closes the record.
pub(crate) fn take_view_fill(ctx: &egui::Context, view: Id) -> Option<(Axis, f32)> {
pass_state::with::<ViewFills, _>(ctx, |fills| fills.0.remove(&view))
}
/// The share a child of `ui`'s body that fills along `axis` takes there, once its body knows it: the room the child
/// is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike.
/// The share of one weight a child of `ui`'s body that fills along `axis` takes there, once its body knows it: a child
/// of weight `w` is measured and shown in `w` times it along that axis, in the measuring run's second sweep and in the
/// real run alike.
pub(crate) fn fill_share(ui: &Ui, axis: Axis) -> Option<f32> {
let env = Env::of(ui);
env.fill_body.filter(|(_, along)| *along == axis).and(env.fill_share)
@@ -1065,7 +1076,7 @@ fn run_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo
child::block(ui, None, layout, |ui| {
let room = share_room(ui, axis);
let share = layout_memory::measured(&ctx, key)
.filter(|found| found.took.y >= 1.0 && room.is_finite())
.filter(|found| found.took.y > 0.0 && room.is_finite())
.map(|found| ((room - found.took.x) / found.took.y).max(0.0));
share_sweep(ui, &mut env.clone(), id, axis, share, &mut body)
})
@@ -1108,8 +1119,9 @@ fn share_sweep<R>(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option<
/// gives the children. Returns the last sweep's result and the rect it took, which the caller places.
///
/// The first sweep counts the children that fill at no extent and records what the others and the gaps took with the
/// number that fill. With a child that fills, a second sweep replaces it under the same ids: the others reuse what the
/// first recorded, and each child that fills is measured once, at its equal share of the rest.
/// sum of the weights of those that fill. With a child that fills, a second sweep replaces it under the same ids: the
/// others reuse what the first recorded, and each child that fills is measured once, at the rest divided by that sum
/// times its own weight.
fn measure_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Rect) {
let ctx = ui.ctx().clone();
let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui) -> R| {
+6 -5
View File
@@ -161,15 +161,15 @@ struct Entry {
/// What a run that showed a child measured: the extent it took, the key of the content it showed, the room it was
/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports), the flow of the body around
/// it (the default for a collection row) and the axis that body shares which a memoized view's content filled, which
/// makes the view one of the children that fill the body (`layout::fill_size`).
/// it (the default for a collection row) and the axis that body shares which a memoized view's content filled, with the
/// filling child's weight, which makes the view one of the children that fill the body (`layout::fill_size`).
#[derive(Clone, Copy, Debug)]
pub(crate) struct Measured {
pub(crate) size: Vec2,
pub(crate) key: Key,
pub(crate) room: Rect,
pub(crate) flow: Flow,
pub(crate) fills: Option<craft_behavior::Axis>,
pub(crate) fills: Option<(craft_behavior::Axis, f32)>,
}
/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, flow and environment,
@@ -460,8 +460,9 @@ pub(crate) fn shown(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, meas
}
/// The axis the content of the memoized view `id` filled in its last run of this kind (`sizing`), else of the other
/// kind: the run of this pass once one ran, else the kept one. `None` before any run showed it.
pub(crate) fn fills(ctx: &Context, id: Id, sizing: bool) -> Option<craft_behavior::Axis> {
/// kind, with the filling child's weight: the run of this pass once one ran, else the kept one. `None` before any run
/// showed it.
pub(crate) fn fills(ctx: &Context, id: Id, sizing: bool) -> Option<(craft_behavior::Axis, f32)> {
let (own, other) = (usize::from(!sizing), usize::from(sizing));
with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.sizes[own].or(entry.sizes[other])).and_then(|measured| measured.fills))
}
@@ -311,6 +311,54 @@ fn fill_children_measure_once_per_sweep() {
}
}
/// The rects of the two `Stretch`es that fill a 400-wide row after a probe 40 wide, with `weights` (`None` sets no
/// weight), and the settled fixture; `asked` counts their measures.
fn weighted(weights: [Option<f32>; 2], asked: Rc<[Asked; 2]>) -> ([Rect; 2], Fixture) {
let seen = Rc::new([RefCell::new(Seen::default()), RefCell::new(Seen::default())]);
let shown = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let fixed = RefCell::new(Seen::default());
Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("row").show(ui, |ui, _| {
Probe::new(&fixed).size(Vec2::new(40.0, LINE)).id_salt("fixed").show(ui);
for ((seen, asked), (weight, salt)) in shown.iter().zip(asked.iter()).zip(weights.into_iter().zip(LEAVES)) {
let leaf = Stretch::new(seen, asked).sizing(Sizing::FillWidth).id_salt(salt);
let leaf = if let Some(weight) = weight { leaf.fill_weight(weight) } else { leaf };
leaf.show(ui);
}
});
});
fixture.room(Vec2::new(400.0, 100.0)).settle();
let rects = [seen[0].borrow().rect, seen[1].borrow().rect];
(rects, fixture)
}
#[trial]
fn children_that_fill_share_the_room_by_their_weights() {
let fresh = || Rc::new([Asked::default(), Asked::default()]);
let ([even_a, even_b], _) = weighted([None, None], fresh());
let even = even_a.width() + even_b.width();
assert!((even_a.width() - even_b.width()).abs() < 1.0, "unweighted children share equally: {even_a:?}, {even_b:?}");
let asked = fresh();
let ([a, b], mut fixture) = weighted([Some(55.0), Some(45.0)], Rc::clone(&asked));
let dump = format!("{a:?}, {b:?}");
assert!((a.width() - b.width() * 55.0 / 45.0).abs() < 1.0, "weights 55 and 45 split the room 55 : 45: {dump}");
assert!((a.width() + b.width() - even).abs() < 1.0, "weighted children share the same room the unweighted ones do: {dump}");
assert!(a.max.x <= b.min.x + 0.5, "the second follows the first: {dump}");
for asked in asked.iter() {
asked.ideal.set(0);
asked.min.set(0);
}
fixture.idle(3);
assert!(asked.iter().all(|asked| asked.ideal.get() == 0 && asked.min.get() == 0), "a settled weighted row measures nothing again");
for weights in [[Some(0.0), Some(f32::NAN)], [Some(-3.0), Some(f32::INFINITY)], [Some(2.0), Some(2.0)]] {
let ([a, b], _) = weighted(weights, fresh());
let dump = format!("{weights:?}: {a:?}, {b:?} against {even_a:?}, {even_b:?}");
assert!((a.width() - even_a.width()).abs() < 1.0 && (b.width() - even_b.width()).abs() < 1.0, "the equal split: {dump}");
}
}
/// What fills the start of the `content_row` rig.
#[derive(Clone, Copy, Debug)]
enum First {
+9 -1
View File
@@ -199,7 +199,7 @@ pub struct Button<'a> {
/// Whether a command button shows its command's chord after the label.
#[prop]
chord: ButtonChord,
/// The kind of popup the button opens: AccessKit reports it.
/// The kind of popup the button opens: AccessKit reports it, and, while selected, it shows the on look.
#[prop(into)]
#[style_key]
popup: Option<PopupKind>,
@@ -306,6 +306,14 @@ impl Component for Button<'_> {
Some(tint) => ButtonStyle::tinted(cx, tint),
None => ButtonStyle::of(cx),
};
// A button that opens a popup shows the on look while selected, as a toggle does: a menu that picks a channel
// other than its default marks that it is set. A tinted face keeps its tint.
if key.popup.is_some() && key.tint.is_none() {
let (off, on) = (cx.variant_look(), face::on_parts(cx));
style.surface = face::on_surface(cx, &off, &on);
style.icon.color = style.icon.color.on(on.text.off);
style.text.color = style.text.color.on(on.text.off);
}
if key.arrangement == Arrangement::Stacked {
style.metrics = face::stacked_metrics(cx, &cx.variant_look());
}
+17
View File
@@ -185,6 +185,23 @@ fn icon_button_selected(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown.into()
}
/// A menu button that is on beside the same button off, as a view's channel menu shows a channel other than its
/// default: the on one takes a toggle's on look.
#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Variants", title = "Menu button on")]
fn a_menu_button_that_is_on(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let shown = Row::new().show(ui, |ui, _| {
for on in [true, false] {
Button::new("Red")
.trailing_icon(crate::controls::disclosure::DisclosureGlyph::menu_button())
.popup(PopupKind::Menu)
.selected(on)
.id_salt(if on { "on" } else { "off" })
.show(ui);
}
});
shown.into()
}
/// Icon buttons with a colour badge on their icon, enabled and then disabled: a disabled button dims each badge and
/// keeps its hue.
#[story(IconButton<'static>, covers = [], drive = Drive::Never, title = "Badge")]
+59 -18
View File
@@ -1,6 +1,8 @@
//! `Segmented`: one of a few options as a strip of segments. A leaf with a part per segment; each segment wears a
//! face that is flat and muted, with a hover fill, and takes the selection fill and edge while it is picked. The row is one Tab stop over its segments: arrows, Home and End move focus between them, Space,
//! Enter or a click picks the focused one.
//! With `SegmentedLayout::Wrap` the segments flow onto further lines in a room narrower than one row; they stay one Tab
//! stop, in reading order.
use crate::buttons::ActiveLook;
use crate::buttons::face::{self, FaceLook, FaceSpec};
@@ -12,7 +14,8 @@ use crate::runtime::env::Label;
use crate::style::{ComponentStyle, Flags, FocusLook, IconLook, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens};
use craft_behavior::{Flow, Metrics, NavShape, PartKey, PartRef, Roving, Sense, Value};
use craft_theme::{Rgba, Stateful, States};
use egui::{Rect, Vec2};
use egui::{Pos2, Rect, Vec2};
use std::ops::Range;
const SEGMENT: PartKey = PartKey::new("segment");
@@ -100,8 +103,17 @@ impl<T: Value + 'static> Component for Segmented<'_, T> {
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let widths = self.widths(cx);
let gaps = widths.len().saturating_sub(1) as f32;
Vec2::new(widths.iter().sum::<f32>() + cx.style.gap * gaps, cx.style.height)
let (gap, height) = (cx.style.gap, cx.style.height);
// A wrapping row's height follows the width it is offered; `parts` splits the rect it is given by the same rule.
let room = if self.layout == SegmentedLayout::Wrap { cx.column_room() } else { None };
let lines = match room {
Some(width) => rows(&widths, gap, width),
None => vec![0..widths.len()],
};
let width_of = |line: &Range<usize>| widths[line.clone()].iter().sum::<f32>() + gap * line.len().saturating_sub(1) as f32;
let widest = lines.iter().map(width_of).fold(0.0, f32::max);
let count = lines.len().max(1) as f32;
Vec2::new(widest, count * height + (count - 1.0) * gap)
}
fn sense(&self) -> Sense {
@@ -110,24 +122,33 @@ impl<T: Value + 'static> Component for Segmented<'_, T> {
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
let widths = self.widths(cx);
let gap = cx.style.gap;
let (gap, height) = (cx.style.gap, cx.style.height);
let current = self.position_of(cx.value());
let mut flow = Flow::new(rect, cx.flow.is_rtl());
for (at, (entry, width)) in self.entries.iter().zip(widths).enumerate() {
let (cell, rest) = flow.take_start(width);
flow = rest.take_start(gap).1;
let mut part = cx.part(Self::part(at), cell);
if entry.icon_spec().is_some() {
part = part.tooltip(entry.label().clone());
}
if !entry.is_enabled() {
continue;
}
let part = part.sense(Sense::CLICK | Sense::FOCUS).focusable();
if current == Some(at) {
part.flags(Flags::CHECKED).selected();
let lines = if self.layout == SegmentedLayout::Wrap { rows(&widths, gap, rect.width()) } else { vec![0..widths.len()] };
// One line spans the rect, as the row it measured; wrapped lines stand a control high, a gap apart.
let line_height = if lines.len() > 1 { height } else { rect.height() };
let rtl = cx.flow.is_rtl();
for (index, line) in lines.into_iter().enumerate() {
let top = rect.min.y + index as f32 * (height + gap);
let mut flow = Flow::new(Rect::from_min_size(Pos2::new(rect.min.x, top), Vec2::new(rect.width(), line_height)), rtl);
for at in line {
let entry = &self.entries[at];
let (cell, rest) = flow.take_start(widths[at]);
flow = rest.take_start(gap).1;
let mut part = cx.part(Self::part(at), cell);
if entry.icon_spec().is_some() {
part = part.tooltip(entry.label().clone());
}
if !entry.is_enabled() {
continue;
}
let part = part.sense(Sense::CLICK | Sense::FOCUS).focusable();
if current == Some(at) {
part.flags(Flags::CHECKED).selected();
}
}
}
// Parts are keyed by entry index, so the flat roving order is reading order across lines.
cx.roving(Roving::new(NavShape::Flat));
}
@@ -164,6 +185,26 @@ impl<T: Value + 'static> Component for Segmented<'_, T> {
}
}
/// The lines of a wrapping row: segments of `widths`, `gap` apart, fill a line of `width` in order, and the next that
/// does not fit starts a new one. A line holds at least one segment, so one wider than `width` takes a line alone.
fn rows(widths: &[f32], gap: f32, width: f32) -> Vec<Range<usize>> {
let mut lines: Vec<Range<usize>> = Vec::new();
let mut used = 0.0;
for (at, &segment) in widths.iter().enumerate() {
match lines.last_mut() {
Some(line) if used + gap + segment <= width => {
line.end = at + 1;
used += gap + segment;
}
_ => {
lines.push(at..at + 1);
used = segment;
}
}
}
lines
}
/// The style of one segment: no fill or edge until hovered or picked, then the theme's selection fill and edge.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
@@ -1,6 +1,6 @@
//! Stories of `Segmented`.
use super::Segmented;
use super::{Segmented, SegmentedLayout};
use crate::buttons::ActiveLook;
use crate::contract::{Entry, Props as _, Show as _, Validity};
use crate::runtime::env::{Message, with_env};
@@ -59,6 +59,22 @@ fn segmented_five(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
text_row(ui, data, 5, 2, ControlSize::Md)
}
/// Five segments that wrap in a room narrower than one row, as a narrow properties panel shows its subject chips: the
/// later segments flow onto further lines, a gap apart.
#[story(Segmented<'static, u8>, covers = [], drive = Drive::Custom(pick_add), group = "Text", title = "Wrap")]
fn segmented_wrap(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let entries = modes(5);
let (picked, picked_at) = data.value_at("mode", 0u8);
// design: allow[contract/allocate, literal-size/vec2](the story gives the row a stage narrower than one row to show it wrap)
let shown: StoryOutput = ui
.allocate_ui(egui::vec2(180.0, 200.0), |ui| {
Segmented::new("Combine (wrap)", picked_at.bind(&mut *picked), &entries).layout(SegmentedLayout::Wrap).show(ui)
})
.inner
.into();
shown.readout(format!("Selected: {}", MODES[usize::from(*picked)]))
}
#[story(Segmented<'static, u8>, covers = [], drive = Drive::Custom(pick_add), group = "Text", title = "Small")]
fn segmented_small(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
text_row(ui, data, 3, 0, ControlSize::Sm)
@@ -83,6 +83,23 @@ fn stack_fill_height(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
})
}
/// Two panels side by side that share a row's width 55 : 45 by their fill weights, as an information panel beside a
/// histogram.
#[story(Row, covers = [], title = "Shared by weight")]
fn a_row_shared_by_weight(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
outlined(ui, |ui| {
// design: allow[contract/allocate, literal-size/vec2](the story gives the row a fixed stage box to show its weighted split)
ui.allocate_ui(egui::vec2(400.0, 120.0), |ui| {
Row::new().fill().show(ui, |ui, _| {
Stack::new().fill().fill_weight(55.0).pad(Pad::Regular).show(ui, |ui, _| words(ui, 0..2));
Stack::new().fill().fill_weight(45.0).pad(Pad::Regular).show(ui, |ui, _| words(ui, 2..4));
})
})
.inner
.into()
})
}
/// The two width roles of a content-sized stack: a side menu held at its least width with short items, and a column
/// of settings whose paragraph breaks at the column's line length instead of widening it. The column also holds a
/// dialog's least width, wider than its line length: where a paragraph's lines break moves with the text size, and the
+3 -1
View File
@@ -5,7 +5,9 @@
//! While a menu is open the pointer moving onto another title switches to that menu, and Left and Right at the top
//! of the menu move to the previous and next one. Titles that do not fit go into a trailing "…" menu that holds them
//! as submenus, or all of them into one "Menu". Under `MenuPlacement::ScreenTop` the bar shows nothing: the OS menu
//! bar takes the same items.
//! bar takes the same items. A bar that belongs to a view (`in_view`) is always drawn in its window, with the same
//! hover switching, mnemonics and Tab stop; the app's F10, Alt and Alt+letter keys stay with the app menu, so the
//! caller turns `keyboard` off on it.
//!
//! Keys follow spec 9.7: Alt and a letter open the menu with that mnemonic (also while another is open). F10 or a
//! lone Alt closes an open menu; with none open it moves focus to the first title, and the next F10 or lone Alt, an
+10
View File
@@ -89,6 +89,16 @@ fn menu_bar_open(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
MenuBar::new("Main menu", titles()).show(ui).into()
}
/// A view's own menu bar (`in_view`): drawn in its window with its titles under every menu placement, also where the
/// app menu lives in the OS bar at the top of the screen. It leaves F10 and Alt to the app menu.
#[story(MenuBar<'static>, covers = [], drive = Drive::Custom(open_file))]
fn menu_bar_in_view(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
// PLAN: the sheet's stage env with `MenuPlacement::ScreenTop` has no mechanism: `Overrides` sets no shell and a
// story cannot install one (the placement comes from the viewport's `ShellInfo`), so the story shows the bar under
// the running platform's placement; a story-level shell (unowned, framework testing) would let it prove `ScreenTop`.
MenuBar::new("View menu", titles()).in_view(true).keyboard(false).show(ui).into()
}
/// Titles set closer (`MenuTitlePad::Control`), as an app sets it at its root for a bar whose menus share the line with
/// many controls.
#[story(MenuBar<'static>, covers = [], drive = Drive::Never)]
+1 -1
View File
@@ -28,7 +28,7 @@ pub(crate) mod pickers;
pub(crate) mod picture;
pub(crate) mod popover;
pub(crate) mod runtime;
pub(crate) mod segmented;
pub(crate) mod suite_rtl;
pub(crate) mod suite_rules;
pub(crate) mod suite_title;
+65
View File
@@ -0,0 +1,65 @@
//! `Segmented`'s layout: the default keeps its segments on one row; `SegmentedLayout::Wrap` flows them onto further
//! lines, a control high and `space.gap.item` apart, inside the room it is offered.
use craft_ui::choice::{Segmented, SegmentedLayout};
use craft_ui::contract::{Bind, Entry, Props as _, Show as _};
use craft_ui::testing::{Fixture, trial};
use egui::{Id, Rect, Vec2};
const NAMES: [&str; 5] = ["New", "Add", "Subtract", "Intersect", "Exclude"];
/// The room the trial offers: narrower than the five segments on one row.
const ROOM: f32 = 200.0;
/// The rects of the `Segmented` and of its segments in entry order, laid out by `layout` in a room `ROOM` wide, and
/// the item gap of the theme.
fn shown(layout: SegmentedLayout) -> (Rect, Vec<Rect>, f32) {
let id = Id::new("segmented layout");
let mut fixture = Fixture::new(move |ui| {
let entries: Vec<Entry<u8>> = (0..).zip(NAMES).map(|(at, name)| Entry::new(at, name)).collect();
let _ = Segmented::new("Combine", Bind::given(0_u8), &entries).layout(layout).id(id).show(ui);
});
fixture.room(Vec2::new(ROOM, 300.0)).settle();
let row = fixture.node_of(id).expect("the segmented row's node").rect;
let segments = NAMES.iter().map(|name| fixture.by_label(name).expect("a segment's node").rect).collect();
let gap = craft_ui::style::StyleCx::with_root(fixture.ctx(), |cx| cx.tokens.space.gap.item);
(row, segments, gap)
}
#[trial]
fn a_segmented_row_wraps_inside_its_room() {
let (row, segments, _) = shown(SegmentedLayout::Row);
let dump = format!("{row:?}: {segments:?}");
assert!(segments.iter().all(|segment| (segment.top() - segments[0].top()).abs() < 0.5), "the default stays one row: {dump}");
assert!(segments.iter().map(Rect::width).sum::<f32>() > ROOM, "premise: one row is wider than the room: {dump}");
let (row, segments, gap) = shown(SegmentedLayout::Wrap);
let dump = format!("{row:?}: {segments:?}");
assert!(segments.iter().all(|segment| row.expand(0.5).contains_rect(*segment)), "every segment lies inside the row: {dump}");
assert!(row.right() <= ROOM + 0.5, "the wrapped row stays inside its room: {dump}");
for (at, a) in segments.iter().enumerate() {
for b in &segments[at + 1..] {
assert!(!a.shrink(0.5).intersects(b.shrink(0.5)), "no two segments overlap: {a:?}, {b:?} in {dump}");
}
}
// The lines in reading order: entry order never steps back to an earlier line.
let mut lines: Vec<Rect> = Vec::new();
for segment in &segments {
match lines.last_mut() {
Some(line) if (segment.top() - line.top()).abs() < 0.5 => *line = line.union(*segment),
Some(line) => {
assert!(segment.top() > line.bottom(), "a later line lies below the one before: {dump}");
lines.push(*segment);
}
None => lines.push(*segment),
}
}
assert!(lines.len() > 1, "a room narrower than one row wraps the segments: {dump}");
for pair in lines.windows(2) {
let between = pair[1].top() - pair[0].bottom();
assert!((between - gap).abs() < 0.5, "lines stand the item gap apart ({between} against {gap}): {dump}");
assert!((pair[1].height() - pair[0].height()).abs() < 0.5, "every line is the control height: {dump}");
}
let last = lines.last().map_or(row.bottom(), Rect::bottom);
assert!((row.bottom() - last).abs() < 0.5, "the measured height ends at the last line, as the parts lay it out: {dump}");
}
+1 -1
View File
@@ -587,7 +587,7 @@ This section points to the component index. Examples and every state of each com
Fill propagates down a column whose width is given: a content-sized container (a `Stack::new()`) shown in a `Stack` given its width passes that width on, so a child that fills takes it, and the container with it. Where the width comes from content (a menu, popover or dialog body, a `Row`, a `Grid`, a fill container held in such a column) the column is a content column: it holds the children that fill, they never set its width, and they are shown across the width it settles on. A leaf declares that it fills with `fills()`; a container declares it with `Sizing`. A content-sized container may name a least width (`ContainerProps::least_width`) and a wrap width (`ContainerProps::wrap_width`) from size roles: its content is at least the one, and a wrapping text inside breaks its lines at the other where its room is wider, so a dialog opens at one width and only content that cannot wrap widens it. A host that shows arbitrary components (the gallery, a dialog body) offers them fill width with `fill_width()`, and a story that fills both axes takes its room from `testing::stage`, and a canvas story as tall as its content (a text being edited) from `testing::stage_fitting`.
Along a height its parent sizes from its content, a container that fills takes its content height, at most the room it is offered. Content taller than that room takes the room, and the children that fill share it, so a list scrolls above the bar under it. Inside a scrolling body the room is unbounded; a host offers a finite one with `room_height` (a gallery card offers the view's height). A `Stack` body that scrolls along y and is given its height shares its view: the children that fill its height take what the view leaves while the content is shorter than the view, and their least where it is longer, past which the body scrolls.
Along a height its parent sizes from its content, a container that fills takes its content height, at most the room it is offered. Content taller than that room takes the room, and the children that fill share it, so a list scrolls above the bar under it. Inside a scrolling body the room is unbounded; a host offers a finite one with `room_height` (a gallery card offers the view's height). A `Stack` body that scrolls along y and is given its height shares its view: the children that fill its height take what the view leaves while the content is shorter than the view, and their least where it is longer, past which the body scrolls. A child that fills the main axis of a `Stack` or `Row` may take `fill_weight(w)` shares of that room instead of one (two panels split 55 : 45); an unset, non-finite or non-positive weight is 1.
### 6.2 Index