landing merge: batch 2 red 1 into the merged framework

# Conflicts:
#	crates/ui-contract/src/contract/body/hooks.rs
#	crates/ui-contract/src/contract/body/size.rs
#	crates/ui-contract/src/contract/run/typed.rs
This commit is contained in:
Dylan M. Taylor committed 2026-11-28 17:49:19 -05:00
commit 83d9bb2241
26 files changed
+432 -37

No files matched your search

+3
View File
@@ -75,6 +75,8 @@ pub(super) struct BodyHooks<'b> {
rules: regions::RuleBands,
/// The least width of the content, from `ContainerProps::least_width`.
least_width: f32,
/// The most width of the content, from `ContainerProps::most_width`; unbounded without one.
most_width: f32,
/// How far the widest region wants to exceed the width the room allows, from this pass's measure.
overflow: f32,
/// The room the mount offers, in which a content-sized body runs.
@@ -207,6 +209,7 @@ impl<'b> BodyHooks<'b> {
header_gap: 0.0,
rules: regions::RuleBands::default(),
least_width: 0.0,
most_width: f32::INFINITY,
overflow: 0.0,
room: Vec2::ZERO,
view_room: None,
+13 -5
View File
@@ -5,7 +5,8 @@ use super::open::open_now;
use super::placement::{Placement, measure_layer, overlay_of, shown_placement};
use super::regions::{
LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_body, footer_in_end, footer_rule_under,
gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_bracket, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line,
gap_of, header_gap_of, label_extra_of, least_of, most_of, pad_of, paint_bracket, paint_edge_rule, paint_rules, rect_of, shared_labels,
shared_line,
};
use super::reorder::REORDER_BAND;
use super::scroll::{
@@ -464,9 +465,6 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
if plan.real {
crate::runtime::focus::end_body(&plan.ctx, plan.id);
}
if plan.real && props.end.is_some() {
self.end_step(comp, ui, cx, &mut plan);
}
} else {
// A collapsed body keeps its last full size in layout memory, so opening it again places by that size
// and asks for no discard pass.
@@ -476,6 +474,14 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
}
}
self.close_label(&mut plan);
// The end region's controls are not the label's: the real run shows them once the label scope closed, as the
// measuring run did before it opened.
if plan.real && plan.is_open && props.end.is_some() {
self.end_step(comp, ui, cx, &mut plan);
if props.label.is_some() {
scope::name_the_container(&plan.ctx, plan.id);
}
}
// B4 footer: under the control column of a label-scoped container, which starts where the label step put
// the control.
if props.footer.is_some() {
@@ -623,6 +629,7 @@ impl BodyHooks<'_> {
self.after_rule = start == Some(true);
self.rules = RuleBands::of(props, env, crate::runtime::egui::scale::pixels_per_point(&ctx), start);
self.least_width = least_of(&env.tokens, props.least_width);
self.most_width = most_of(&env.tokens, props.most_width);
let quiet = stage.is_peek() || crate::runtime::measure::active(&ctx);
if !matches!(props.mount, Mount::Inline | Mount::Pane(_))
&& let Some(why) = if quiet { crate::runtime::overlay::peek_close(&ctx, id) } else { crate::runtime::overlay::take_close(&ctx, id) }
@@ -1957,6 +1964,7 @@ impl BodyHooks<'_> {
self.after_rule = start == Some(true);
self.rules = RuleBands::of(&props, at.env, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx()), start);
self.least_width = least_of(&at.env.tokens, props.least_width);
self.most_width = most_of(&at.env.tokens, props.most_width);
self.room = match at.width {
Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)),
None => self.mount_room(&props, (at.ui, at.place), id, at.at, at.scx.tokens),
@@ -2088,7 +2096,7 @@ impl BodyHooks<'_> {
// The least width holds in the measure a parent places it by, as in its own extent (`wanted_width`): a row
// measuring a side menu among its children gave it only its content's width, so the menu shrank to its widest
// row's name.
let took = Vec2::new(took.x.max(self.least_width + pad.x), took.y);
let took = Vec2::new(took.x.max(self.least_width + pad.x).min(self.most_width + pad.x), took.y);
self.overflow = (took.x - self.room.x).max(0.0);
// A body wider than the room overflows it, or scrolls along it; either way the container keeps to the room.
Vec2::new(took.x.min(self.room.x), if vertical { took.y.min(self.room.y) } else { took.y })
@@ -161,6 +161,10 @@ pub(super) fn least_of(tokens: &UiTokens, least: Option<LeastWidth>) -> f32 {
least.map_or(0.0, |least| least.points(tokens.tokens()))
}
pub(super) fn most_of(tokens: &UiTokens, most: Option<LeastWidth>) -> f32 {
most.map_or(f32::INFINITY, |most| most.points(tokens.tokens()))
}
pub(super) fn rect_of(parts: [f32; 4]) -> Rect {
Rect::from_min_max(Pos2::new(parts[0], parts[1]), Pos2::new(parts[2], parts[3]))
}
+3 -2
View File
@@ -298,7 +298,7 @@ impl<'b> BodyHooks<'b> {
pub(super) fn wanted_width(&self, props: &ContainerProps) -> Option<f32> {
self.measured_body.map(|body| {
let (header, end) = (self.measured_header.unwrap_or(Vec2::ZERO), self.measured_end.unwrap_or(Vec2::ZERO));
self.regions_size(props, body, header, self.measured_footer, end).x.max(self.least_width)
self.regions_size(props, body, header, self.measured_footer, end).x.max(self.least_width).min(self.most_width)
})
}
@@ -365,7 +365,8 @@ impl<'b> BodyHooks<'b> {
let y = shares_view.then(|| crate::layout::view_room(ui, env, craft_behavior::Axis::Y)).flatten().unwrap_or(room.y);
// A body that fills the height of the row line it stands on runs in that line.
let y = self.line_height(props, env, at).unwrap_or(y);
Vec2::new(cap.map_or(room.x, |cap| room.x.min(cap)), props.room_height.unwrap_or(y))
let most = props.most_height.map(|crate::contract::MostHeight::Share(share)| y * share);
Vec2::new(cap.map_or(room.x, |cap| room.x.min(cap)), props.room_height.or(most).unwrap_or(y))
}
},
}
@@ -236,6 +236,15 @@ impl LeastWidth {
}
}
/// The most height of a container's body, as a share of the room its flow offers.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum MostHeight {
/// This share (0 to 1) of the flow's room height: a row of panels under a picture takes its content height, at
/// most this share, so a short view keeps showing the picture.
Share(f32),
}
/// A size role that sets the line length of the paragraphs in a container whose width comes from its content: a
/// wrapping text breaks its lines there when its room is wider, and content wider than it still widens the container.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -889,6 +898,9 @@ pub struct ContainerProps {
/// as a scrolling list is as tall as its rows until they outgrow the room. A host that shows content of either
/// kind at a definite room (a story in a gallery card) sets it.
pub room_height: Option<f32>,
/// The room height as a share of the flow's, when `room_height` is unset: the body offers its children at most
/// that share, and takes their content height up to it.
pub most_height: Option<MostHeight>,
/// How the body lays out its children.
pub layout: BodyLayout,
/// A header region.
@@ -914,6 +926,8 @@ pub struct ContainerProps {
pub body_gap: Gap,
/// The least width of the content, from a size role; the content may be wider.
pub least_width: Option<LeastWidth>,
/// The most width of the content of a container sized from its content, from a size role; wider content is cut to it.
pub most_width: Option<LeastWidth>,
/// The least height of an unwrapped `Row` body's line, in points: the line is at least this high, as if a child of
/// more than one line this high stood in it, so the children that fill the line's height take at least it. Other
/// layouts ignore it.
@@ -990,6 +1004,7 @@ impl ContainerProps {
&& self.sizing == other.sizing
&& self.content_in_bar == other.content_in_bar
&& self.room_height == other.room_height
&& self.most_height == other.most_height
&& self.fit_rank == other.fit_rank
&& self.layout == other.layout
&& self.header == other.header
@@ -1000,6 +1015,7 @@ impl ContainerProps {
&& self.collapse == other.collapse
&& self.body_gap == other.body_gap
&& self.least_width == other.least_width
&& self.most_width == other.most_width
&& self.least_height == other.least_height
&& self.wrap_width == other.wrap_width
&& self.child_size == other.child_size
@@ -1023,6 +1039,7 @@ impl ContainerProps {
sizing: Sizing::Content,
content_in_bar: false,
room_height: None,
most_height: None,
layout: BodyLayout::Stack,
header: None,
scroll: None,
@@ -1035,6 +1052,7 @@ impl ContainerProps {
collapse: None,
body_gap: Gap::Row,
least_width: None,
most_width: None,
least_height: None,
wrap_width: None,
edge_rule: false,
@@ -1104,6 +1122,18 @@ impl ContainerProps {
self
}
/// The most height of the body as a share of the flow's room ([`most_height`](Self::most_height)).
pub const fn most_height(mut self, most: MostHeight) -> Self {
self.most_height = Some(most);
self
}
/// The most width of a content-sized body's content ([`most_width`](Self::most_width)).
pub const fn most_width(mut self, most: LeastWidth) -> Self {
self.most_width = Some(most);
self
}
/// How the body lays out its children.
pub fn layout(mut self, layout: BodyLayout) -> Self {
self.layout = layout;
+13 -9
View File
@@ -659,13 +659,14 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
}
}
/// Where a drop kind at `place` would take a drop at `at` (the collection's layer space), with its mark.
/// Where a drop kind at `place` would take a drop at `at` (the collection's layer space; `screen` is the same point
/// on screen), with its mark.
fn kind_spot(
&self,
layout: &C::ItemLayout,
(rect, offset, rtl): (Rect, ScrollPos, bool),
place: DropPlace,
at: Pos2,
(screen, at): (Pos2, Pos2),
spot_side: f32,
) -> Option<(DropAt<C::Key>, DropMark)> {
match place {
@@ -687,7 +688,9 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
Some((DropAt::Spot { over, at: own }, DropMark::Into(mark)))
}
DropPlace::Onto => {
let over = (at.y >= rect.min.y).then(|| layout.hit(Self::logical(layout, rect, rtl, at), offset)).flatten()?;
// Below the header is read on screen: under a body transform an item's layer point can lie above the
// rows' rect.
let over = (screen.y >= rect.min.y).then(|| layout.hit(Self::logical(layout, rect, rtl, at), offset)).flatten()?;
if !self.source.enabled(over) {
return None;
}
@@ -697,10 +700,10 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
}
}
/// Whether `at` lies over the middle of a row, between the top and bottom shares where a drop lands before or
/// after it.
fn over_middle(&self, layout: &C::ItemLayout, (rect, offset, rtl): (Rect, ScrollPos, bool), at: Pos2) -> bool {
let Some(over) = (at.y >= rect.min.y).then(|| layout.hit(Self::logical(layout, rect, rtl, at), offset)).flatten() else { return false };
/// Whether `at` (layer space; `screen` on screen) lies over the middle of a row, between the top and bottom shares
/// where a drop lands before or after it.
fn over_middle(&self, layout: &C::ItemLayout, (rect, offset, rtl): (Rect, ScrollPos, bool), (screen, at): (Pos2, Pos2)) -> bool {
let Some(over) = (screen.y >= rect.min.y).then(|| layout.hit(Self::logical(layout, rect, rtl, at), offset)).flatten() else { return false };
let row = self.screen(layout, rect, over, offset, rtl);
let from_top = if row.height() > 0.0 { (at.y - row.min.y) / row.height() } else { 0.0 };
(reorder::GROUP_EDGE..1.0 - reorder::GROUP_EDGE).contains(&from_top)
@@ -725,10 +728,11 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
let Some((payload, at)) = cx.core.dragging_of(kind.payload()) else { continue };
let point = xf.map_or(at, |map| map.to_layer(at));
let onto_too = || drops.iter().any(|other| matches!(other.place(), DropPlace::Onto) && other.payload() == kind.payload());
if matches!(kind.place(), DropPlace::Between) && onto_too() && self.over_middle(layout, place, point) {
if matches!(kind.place(), DropPlace::Between) && onto_too() && self.over_middle(layout, place, (at, point)) {
continue;
}
let Some((at, mark)) = self.kind_spot(layout, place, kind.place(), point, spot_side).filter(|(at, _)| kind.accepts(&*payload, at)) else {
let Some((at, mark)) = self.kind_spot(layout, place, kind.place(), (at, point), spot_side).filter(|(at, _)| kind.accepts(&*payload, at))
else {
continue;
};
if !own {
+1 -1
View File
@@ -70,7 +70,7 @@ pub use container::InBar;
pub use container::InMenu;
pub use container::{
BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion,
LeastWidth, Mount, MoveBandCursor, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator,
LeastWidth, MostHeight, Mount,MoveBandCursor, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator,
SectionRhythm, ShellPane, Sizing, ThemeScope, WrapWidth,
};
pub use craft_tracked::{PlainData, Revision, Tracked};
@@ -747,6 +747,12 @@ pub(crate) fn carried_name(ctx: &Context, container: Id) -> Option<String> {
store::peek_clone::<String>(ctx, carried_slot(container))
}
/// `container` shows controls of its own beside its label's one control (its end region's): its node keeps the label
/// as its name too, so the group of them is named. Called after the label scope closed.
pub(crate) fn name_the_container(ctx: &Context, container: Id) {
let _ = store::take::<String>(ctx, carried_slot(container));
}
/// The slot of a container's carried label name; it goes with the scope's owner.
fn carried_slot(container: Id) -> Id {
sub(container, "carried_name")
+17 -12
View File
@@ -198,27 +198,32 @@ pub(crate) fn show_body_layer<R>(ctx: &Context, body_layer: BodyLayer, body: imp
ctx.set_transform_layer(layer, transform);
ctx.set_sublayer(parent, layer);
let shown = transform.inverse() * clip;
// The area sits where the body shows (its clip, anywhere in the layer's space for a view far from the document's
// origin): egui senses an area's background over its rect, and that widget, topmost under the pointer, hides every
// widget of the layers below. The body itself starts at its own top left.
let inner = egui::Area::new(layer.id)
.fade_in(false)
.order(layer.order)
.pivot(egui::Align2::LEFT_TOP)
.fixed_pos(at)
.fixed_pos(shown.min)
.constrain(false)
.sense(egui::Sense::hover())
.show(ctx, |ui| {
if let Some(forward) = forward {
let id = crate::runtime::memory::sub(forward.root, "transform");
ui.interact(transform.inverse() * forward.rect, id, forward.sense);
super::access::hide(ctx, id);
crate::runtime::pointer::record_body_layer(ctx, layer, parent, forward.root);
}
ui.set_clip_rect(shown);
body(ui)
ui.scope_builder(egui::UiBuilder::new().max_rect(Rect::from_min_size(at, shown.size())), |ui| {
if let Some(forward) = forward {
let id = crate::runtime::memory::sub(forward.root, "transform");
ui.interact(transform.inverse() * forward.rect, id, forward.sense);
super::access::hide(ctx, id);
crate::runtime::pointer::record_body_layer(ctx, layer, parent, forward.root);
}
ui.set_clip_rect(shown);
body(ui)
})
.inner
})
.inner;
// egui finds a layer under the pointer by its area's rect, which starts at the area's left-top: here the body's
// origin, while the body shows only in its clip, which can lie anywhere in the layer's space (a view far from the
// document's origin). The area takes the clip as its rect, so the layer is found exactly where it shows.
// egui finds a layer under the pointer by its area's rect, which it sizes from the content: the area takes the
// clip as its rect, so the layer is found exactly where it shows.
if let Some(state) = egui::AreaState::load(ctx, layer.id) {
let state = egui::AreaState { pivot_pos: Some(shown.min), pivot: egui::Align2::LEFT_TOP, size: Some(shown.size()), ..state };
ctx.memory_mut(|memory| memory.areas_mut().set_state(layer, state));
+1
View File
@@ -397,6 +397,7 @@ impl<'a> StyleCx<'a> {
Ink::OnPanel => c.normal,
Ink::OnDark => c.on_strong,
Ink::Accent => self.tokens.color.accent.text,
Ink::Muted => c.muted,
})
}
+3
View File
@@ -21,6 +21,9 @@ pub enum Ink {
OnDark,
/// Accent-coloured text on panels and sunken surfaces: a prominent readout.
Accent,
/// The secondary text colour on panels and sunken surfaces: a glyph that marks its neighbour without drawing the
/// eye, such as a sampler's eyedropper beside its swatch.
Muted,
}
/// The key of everything a style depends on besides its own key: tokens, direction, scale, the OS, the window's
+1
View File
@@ -315,6 +315,7 @@ pub fn ink_color(tokens: &UiTokens, ink: super::key::Ink) -> Color32 {
super::key::Ink::OnPanel => text.normal,
super::key::Ink::OnDark => text.on_strong,
super::key::Ink::Accent => tokens.color.accent.text,
super::key::Ink::Muted => text.muted,
})
}
+5 -3
View File
@@ -73,7 +73,7 @@ impl Shot {
/// Whether the layout reflowed from `base` to `grown`: two texts lie beside each other in `base` and one above the
/// other in `grown`, as a label that moves above its control. The texts are `(text, rect)` in paint order; a text
/// shown several times pairs its nth occurrence in one with its nth in the other, and a text one of them lacks pairs
/// with nothing. A reflow can shorten the layout, so the growth check leaves the height out.
/// with nothing. A reflow can shorten the layout along one axis, so the growth check asks growth along one only.
pub fn reflowed(base: &[(&str, Rect)], grown: &[(&str, Rect)]) -> bool {
let stacked = |a: Rect, b: Rect| a.max.y <= b.min.y || b.max.y <= a.min.y;
let occurrence = |runs: &[(&str, Rect)], at: usize| runs[..at].iter().filter(|(text, _)| *text == runs[at].0).count();
@@ -127,9 +127,11 @@ fn text_size_from(story: &Story, base: Shot) -> Result<(), String> {
for (name, grown) in &variants {
let size = after(grown);
let slack = if *name == "scale 2" { SCALE_LAYOUT_SLACK } else { 0.0 };
// A label that moves from beside to above its control reflows the field, and that can shorten it.
// A reflow trades one axis for the other: a label that moves above its control can shorten the field, and
// segments that wrap onto more lines can narrow their widest line. Either way the story grows along one axis.
let moved = reflowed(&base.whole_texts(), &grown.whole_texts());
if !(grows_with(before.x - slack, size.x) && (moved || grows_with(before.y - slack, size.y))) {
let (wider, taller) = (grows_with(before.x - slack, size.x), grows_with(before.y - slack, size.y));
if !(if moved { wider || taller } else { wider && taller }) {
return Err(format!("{}: under {name} the size went from {before:?} to {size:?}", story.name));
}
for run in base.runs.iter().filter(|run| !run.elided && !run.text.trim().is_empty() && base.keeps(run.rect, run.clip)) {
@@ -361,6 +361,80 @@ fn a_drop_in_a_free_layout_reports_its_spot_and_the_empty_space_its_screen_point
assert!(menu.iter().any(|at| (*at - activated[0]).length() < SAME), "the point a secondary click there reports: {menu:?}");
}
/// An item panned into view from above the board's top left (a negative y in the items' own space) takes an `Onto`
/// drop where it shows: the drop is below the board's top on screen, though its point in the board's layer is above.
#[trial]
fn an_onto_drop_reaches_an_item_panned_in_from_above_the_origin() {
let pan = Vec2::new(0.0, 100.0);
let words = Words::flat(&["a", "b", "c"]);
let (rows, board_at) = (Shown::default(), Shown::default());
let events = RefCell::new(Events::new());
let mut frames = Frames::new();
let items = vec![Rect::from_min_size(Pos2::new(0.0, 0.0), Vec2::splat(40.0)), Rect::from_min_size(Pos2::new(150.0, -60.0), Vec2::splat(40.0))];
let mut show = |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(150.0, 100.0)), |ui| {
let _ = List::new(SelectMode::Single).reorder().id_salt("rows").show_items(ui, &words, &mut |key, cx| {
rows.note(*key, cx.rect);
Row::new()
});
});
in_region(ui, Rect::from_min_size(Pos2::new(200.0, 10.0), Vec2::new(400.0, 300.0)), |ui| {
let onto = DropKind::new(DropPlace::Onto, |_: &ListDrag<usize>, _: &DropAt<usize>| true);
let board = Board::new(items.clone()).takes_drop(onto).transformed(CanvasTransform::new(1.0, pan));
let out = board.id_salt("board").show_items(ui, &Count(2), &mut |key, cx| {
board_at.note(*key, cx.rect);
Row::new()
});
events.borrow_mut().extend(out.events);
});
};
frames.idle(3, &mut show);
// The item's place in the board's untransformed layer, and where the pan shows it.
let layer = board_at.rect(1).center();
let to = layer + pan;
assert!(layer.y < board_at.rect(0).min.y && to.y > board_at.rect(0).min.y, "the item lies above the rows' top only in the layer");
let from = rows.rect(0).center();
frames.frame(vec![moved(from)], &mut show);
frames.frame(vec![press(from)], &mut show);
for step in 1..=4 {
frames.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))], &mut show);
}
frames.idle(1, &mut show);
frames.frame(vec![release(to)], &mut show);
frames.idle(2, &mut show);
let got: Vec<DropAt<usize>> =
events.borrow().iter().filter_map(|event| if let CollectionEvent::Dropped { at, .. } = event { Some(at.clone()) } else { None }).collect();
assert_eq!(got, [DropAt::Onto(1)], "the drop lands onto the item where it shows");
}
/// A widget beside a panned board takes its click: the board's layer covers only where the board shows, not the place
/// the pan moved its content to.
#[trial]
fn a_widget_beside_a_panned_board_takes_its_click() {
let clicked = Cell::new(false);
let beside = Shown::default();
let mut frames = Frames::new();
let mut show = |ui: &mut Ui| {
in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(200.0, 200.0)), |ui| {
let board = Board::new(three_items()).transformed(CanvasTransform::new(1.0, Vec2::new(300.0, 0.0)));
let _ = board.id_salt("board").show_items(ui, &Count(3), &mut |_, _| Row::new());
});
// Where the pan moves the board's content to, right of the board.
in_region(ui, Rect::from_min_size(Pos2::new(320.0, 10.0), Vec2::new(150.0, 40.0)), |ui| {
let response = ui.button("Beside");
beside.note(0, response.rect);
clicked.set(clicked.get() | response.clicked());
});
};
frames.idle(3, &mut show);
let at = beside.rect(0).center();
frames.frame(vec![moved(at)], &mut show);
frames.frame(vec![press(at)], &mut show);
frames.frame(vec![release(at)], &mut show);
frames.idle(1, &mut show);
assert!(clicked.get(), "the button beside the board took the click");
}
/// What the `Move` events of a run were: begins, updates, commits with their offset, and cancels.
#[derive(Debug, Default, PartialEq)]
struct Moves {
@@ -4,6 +4,7 @@ use super::Icon;
use crate::contract::{Props as _, Show as _, ShowContainer as _};
use crate::layout_components::Grid;
use crate::primitives::IconSpec;
use crate::style::Ink;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_behavior::{ColumnWidth, IconId};
use craft_theme::ControlSize;
@@ -15,6 +16,18 @@ fn icon(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Icon::new(IconSpec::svg(IconId::new("settings"))).label("Settings").show(ui).into()
}
/// An icon in the panel's ink beside one in the muted ink, which marks its neighbour without drawing the eye.
#[story(Icon<'static>, covers = [], drive = Drive::Never)]
fn icon_muted(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content; 2];
Grid::new(COLUMNS)
.show(ui, |ui, _| {
Icon::new(IconSpec::svg(IconId::new("eyedropper"))).id_salt("panel").show(ui);
Icon::new(IconSpec::svg(IconId::new("eyedropper")).ink(Ink::Muted)).id_salt("muted").show(ui);
})
.into()
}
/// Six icons at each control size (an icon's side is its control size's icon side), then one in each tone.
#[story(Icon<'static>, covers = [], drive = Drive::Never)]
fn icon_sizes(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+16 -1
View File
@@ -3,7 +3,7 @@
use crate::contract::{
Access, BodyCx, Bracket, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme,
LeastWidth, Pad, PadEdges, Role, Scroll, Sizing, ThemeScope, WrapWidth,
LeastWidth, MostHeight, Pad, PadEdges, Role, Scroll, Sizing, ThemeScope, WrapWidth,
};
use crate::layout::{BodyLayout, CellAlign, GridFit, RowAlign};
use crate::style::{ComponentStyle, StyleCx};
@@ -288,6 +288,14 @@ impl<'a> Stack<'a> {
self
}
/// The width of the stack's content from the size role `width`, neither more nor less: a stack sized from its
/// content beside a picture (a scene browser, `LeastWidth::SideMenu`) keeps that width whatever its rows hold.
#[must_use]
pub fn width(mut self, width: LeastWidth) -> Self {
self.props = self.props.least_width(width).most_width(width);
self
}
/// The line length `wrap` of the paragraphs in a stack sized from its content: a wrapping text breaks its lines
/// there instead of widening the stack (a Print page's settings column, `WrapWidth::Column`).
#[must_use]
@@ -345,6 +353,13 @@ impl Row {
self
}
/// The row offers its children at most `most` of the room its flow offers, and takes their content height up to
/// it: a row of panels under a picture (`MostHeight::Share(0.5)`) leaves a short view the rest for the picture.
pub fn most_height(mut self, most: MostHeight) -> Self {
self.props = self.props.most_height(most);
self
}
/// Links the labelled rows of the first child to the child after them (width and height to their chain): that
/// child sits halfway between the first and the last row's controls, and `Bracket::Linked` draws the bracket
/// from the controls to it.
@@ -1,7 +1,7 @@
//! Stories of the layout components `Row`, `Stack` and `Grid`.
use super::{Grid, Row, Stack};
use crate::contract::{Bind, Bracket, Gap, LeastWidth, Pad, Props as _, Show as _, ShowContainer as _, Sizing, WrapWidth};
use crate::contract::{Bind, Bracket, Gap, LeastWidth, MostHeight, Pad, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, WrapWidth};
use crate::display::Text;
use crate::form::{Field, FieldGroup};
use crate::layout::{CellAlign, GridFit, empty_cell};
@@ -100,6 +100,45 @@ fn a_row_shared_by_weight(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
})
}
/// A row of panels under a picture with a most height of half the room: few rows take their content height, many stop
/// at half the room and scroll, and the picture above keeps the rest.
#[story(Row, covers = [], title = "Most height")]
fn row_most_height(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let repeats = *data.choice("rows", 1usize, &[("Few", 1), ("Many", 4)]);
outlined(ui, |ui| {
// design: allow[contract/allocate, literal-size/vec2](the story gives the row a fixed stage box to show its most height)
ui.allocate_ui(egui::vec2(360.0, 200.0), |ui| {
Stack::new().fill().show(ui, |ui, _| {
Stack::new().fill().pad(Pad::Regular).show(ui, |ui, _| words(ui, 0..1));
Row::new().fill_width().most_height(MostHeight::Share(0.5)).show(ui, |ui, _| {
Stack::new().fill().scroll(Scroll::vertical()).pad(Pad::Regular).show(ui, |ui, _| {
for repeat in 0..repeats {
ui.push_id(repeat, |ui| words(ui, 0..4));
}
});
});
})
})
.inner
.into()
})
}
/// A stack held at a width role whatever it holds: a scene browser beside a picture, its long row cut to the width.
#[story(Stack<'static>, covers = [], title = "Width")]
fn stack_width(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
outlined(ui, |ui| {
Stack::new()
.width(LeastWidth::SideMenu)
.pad(Pad::Regular)
.show(ui, |ui, _| {
words(ui, 0..1);
let _ = Text::new("Environment lighting from a captured sky, turned to the light's angle").show(ui);
})
.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
+2 -3
View File
@@ -93,9 +93,8 @@ fn menu_bar_open(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
/// 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`.
// The story shows the running platform's placement; the trial
// `a_views_own_bar_shows_its_titles_where_the_app_menu_lives_in_the_os_bar` runs the bar under macOS's.
MenuBar::new("View menu", titles()).in_view(true).keyboard(false).show(ui).into()
}
+23
View File
@@ -409,6 +409,29 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
.label(label)
}
/// The side of a card's picture at the grid's zoom, from its style in the env of `ui`: the side a host asks its
/// pictures at, so a thumbnail is made at the size the cells show it.
pub fn cell_picture_side(&self, ui: &Ui) -> f32 {
let style = self.sizes_in(ui);
self.picture_side(&style, None, style.around.get(self.caption, self.detail_line))
}
/// The width the grid takes to show one column of its cards at their size, from its style in the env of `ui`: the
/// least width of a pane that holds the grid, under which its cards shrink.
pub fn column_width(&self, ui: &Ui) -> f32 {
let style = self.sizes_in(ui);
let aspect = if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 };
let around = style.around.get(self.caption, self.detail_line);
style.card(self.picture_side(&style, None, around), aspect, around).x + 2.0 * style.spacing(self.caption).inset
}
/// The grid's sizes in the env of `ui`.
fn sizes_in(&self, ui: &Ui) -> GridSizes {
let env = crate::runtime::env::Env::of(ui);
let cx = StyleCx::of_env(ui.ctx(), &env);
GridSizes::of(&cx, self.card, self.card_text, self.items.row_height, self.regular_card_padding, self.action_place)
}
/// The size of the tiles: a factor the host holds, or one the grid steps itself through a binding.
#[must_use]
pub fn zoom(mut self, mut zoom: GridZoom<'a>) -> Self {
+53
View File
@@ -0,0 +1,53 @@
//! `Icon`'s inks: the muted ink paints a glyph dimmer than the panel's ink.
use craft_behavior::IconId;
use craft_ui::contract::{Props as _, Show as _};
use craft_ui::display::Icon;
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::Env;
use craft_ui::style::Ink;
use craft_ui::testing::{Fixture, trial};
use egui::{Color32, Rect, Vec2};
use std::cell::Cell;
use std::rc::Rc;
/// Regression: an icon asked for the muted ink painted in the panel's text colour, so a glyph meant to sit back beside
/// its subject (a sampler's eyedropper beside its swatch) drew the eye as much as the subject.
#[trial]
fn a_muted_icon_paints_in_the_muted_text_colour_and_a_plain_one_in_the_normal() {
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING, Color32::TRANSPARENT, Color32::TRANSPARENT)));
let held = seen.clone();
let mut fixture = Fixture::new(move |ui| {
let text = Env::of(ui).tokens.tokens().color.text;
let color = |[r, g, b, a]: [u8; 4]| Color32::from_rgba_unmultiplied(r, g, b, a);
let plain = Icon::new(IconSpec::svg(IconId::new("settings"))).id_salt("plain").show(ui).rect;
let muted = Icon::new(IconSpec::svg(IconId::new("settings")).ink(Ink::Muted)).id_salt("muted").show(ui).rect;
held.set((plain, muted, color(text.normal.0), color(text.muted.0)));
});
fixture.room(Vec2::new(200.0, 200.0));
fixture.settle();
let (plain, muted, normal, dim) = seen.get();
assert_ne!(normal, dim, "the themes the fixture uses tell the muted ink from the normal one");
let shapes = fixture.frame_shapes();
let tints = |rect: Rect| -> Vec<Color32> {
let mut tints: Vec<Color32> = shapes
.iter()
.filter_map(|shape| match shape {
egui::Shape::Mesh(mesh) if rect.contains(mesh.calc_bounds().center()) => {
Some(mesh.vertices.iter().map(|vertex| vertex.color).collect::<Vec<_>>())
}
_ => None,
})
.flatten()
.filter(|color| color.a() > 0)
.collect();
tints.dedup();
tints
};
let (plain_tints, muted_tints) = (tints(plain), tints(muted));
assert!(
!plain_tints.is_empty() && plain_tints.iter().all(|tint| *tint == normal),
"a plain icon paints in text.normal {normal:?}: {plain_tints:?}"
);
assert!(!muted_tints.is_empty() && muted_tints.iter().all(|tint| *tint == dim), "a muted icon paints in text.muted {dim:?}: {muted_tints:?}");
}
+1
View File
@@ -6,6 +6,7 @@ pub(crate) mod fill_share;
pub(crate) mod fonts;
pub(crate) mod grid_labels;
pub(crate) mod grid_least;
pub(crate) mod most_height;
pub(crate) mod nested;
pub(crate) mod room_height;
pub(crate) mod row_line;
@@ -0,0 +1,44 @@
//! A row with a most height (`MostHeight::Share`) takes its content height while its content fits the share of the
//! room its flow offers, and stops at that share when its content is taller: a 2D view's panel row leaves the rest of a
//! short view to the picture.
use craft_ui::buttons::Button;
use craft_ui::contract::{MostHeight, Scroll, Show as _, ShowContainer as _};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Vec2};
use std::cell::Cell;
use std::rc::Rc;
const ROOM: Vec2 = Vec2::new(400.0, 600.0);
const SHARE: f32 = 0.25;
/// The rect of a row of most height `SHARE` holding a scrolling stack of `rows` buttons, from the last real run.
fn row(rows: usize) -> Rect {
let seen = Rc::new(Cell::new(Rect::NOTHING));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
Stack::new().fill().show(ui, |ui, _| {
let shown = Row::new().fill_width().most_height(MostHeight::Share(SHARE)).show(ui, |ui, _| {
Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
for row in 0..rows {
Button::new(format!("Row {row}")).show(ui);
}
});
});
if !ui.is_sizing_pass() {
out.set(shown.output.rect);
}
});
});
fixture.room(ROOM).settle();
seen.get()
}
#[trial]
fn a_rows_most_height_is_its_content_height_up_to_a_share_of_the_room() {
let (short, tall) = (row(1), row(40));
assert!(short.height() > 0.0 && tall.height() > 0.0, "both rows show: {short:?}, {tall:?}");
assert!(short.height() < tall.height(), "a row whose content fits takes its content height: {short:?} against {tall:?}");
assert!(tall.height() <= ROOM.y * SHARE + 0.5, "a taller content stops at the share of the room: {tall:?}");
}
@@ -44,6 +44,18 @@ fn a_stacks_least_width_holds_it_wider_than_narrow_content() {
assert!(menu.width() > plain.width() + 60.0, "the side menu's least width holds it wider: {menu:?} against {plain:?}");
}
/// A stack given a width role is that wide with narrow content and with a paragraph that would widen it to the room: a
/// scene browser beside a 3D view keeps its width.
#[trial]
fn a_stacks_width_role_holds_it_at_that_width_with_narrow_and_wide_content() {
let (menu, _) = shown(|| Stack::new().least_width(LeastWidth::SideMenu), false);
let (narrow, _) = shown(|| Stack::new().width(LeastWidth::SideMenu), false);
let (wide, _) = shown(|| Stack::new().width(LeastWidth::SideMenu), true);
assert!(menu != Rect::NOTHING && narrow != Rect::NOTHING && wide != Rect::NOTHING, "the stacks showed");
assert!((narrow.width() - menu.width()).abs() < 0.5, "narrow content takes the role's width: {narrow:?} against {menu:?}");
assert!((wide.width() - narrow.width()).abs() < 0.5, "a long paragraph does not widen the stack past the role: {wide:?} against {narrow:?}");
}
/// In a row beside a page that fills, a full-height side menu keeps its least width: the row places its children by
/// their measure, and that measure held only the menu's content (a File page's rail came out at its widest name).
#[trial]
+1
View File
@@ -17,6 +17,7 @@ pub(crate) mod focus_ring;
pub(crate) mod form;
pub(crate) mod graph;
pub(crate) mod graph_annotations;
pub(crate) mod icon_ink;
pub(crate) mod keys;
pub(crate) mod label;
pub(crate) mod layer;
+17
View File
@@ -52,6 +52,23 @@ impl Rig {
}
}
/// Regression: a view's own bar (`in_view`) followed the app menu's placement, so where the app menu lives in the OS
/// bar at the top of the screen (macOS) it showed nothing, as the app menu's bar rightly does there.
#[trial]
fn a_views_own_bar_shows_its_titles_where_the_app_menu_lives_in_the_os_bar() {
for in_view in [false, true] {
let mut fixture = Fixture::new(move |ui| {
let titles = vec![MenuTitle::new("&File", |ui| {
MenuItem::new("&New").show(ui);
})];
MenuBar::new("Menu", titles).in_view(in_view).keyboard(false).show(ui);
});
fixture.os(Os::Mac);
fixture.settle();
assert_eq!(fixture.by_label("File").is_some(), in_view, "in_view {in_view}: the bar shows its titles only as a view's own bar");
}
}
#[trial]
fn help_search_ignores_accents_and_matches_the_english_label_and_the_path() {
let mut rig = rig(Direction::Ltr);
@@ -118,6 +118,42 @@ fn a_grid_in_a_measured_stack_keeps_its_rows_and_what_follows_them() {
assert!(clicked.get(), "the button under the grid takes a click");
}
/// Regression: a host had no size of the grid's cells, so it sized a pane around the grid or asked for its pictures
/// from a guess. In a column `column_width` wide the grid shows one column of cards whose pictures are
/// `cell_picture_side`; a narrower column shrinks them.
#[craft_ui::testing::trial]
fn a_column_of_the_grids_column_width_holds_one_card_at_its_picture_side() {
let shown = Shown::shared();
let sizes = Rc::new(Cell::new((0.0_f32, 0.0_f32)));
let (held, held_sizes) = (shown.clone(), sizes.clone());
let mut fixture = Fixture::new(move |ui| {
let keys: Vec<usize> = (0..4).collect();
let source = keyed(&keys, |key: &usize| *key);
held.borrow_mut().tiles.clear();
let grid = TileGrid::new("Library").zoom(GridZoom::Fixed(1.5));
held_sizes.set((grid.column_width(ui), grid.cell_picture_side(ui)));
let _ = grid.show_items(ui, &source, &mut |key, icx| {
held.borrow_mut().tiles.insert(*key, icx.rect);
Tile::new(format!("Tile {key}")).thumb(ThumbAspect::SQUARE, |_, _| {})
});
});
fixture.room(Vec2::new(800.0, 2000.0));
fixture.settle();
let (column, side) = sizes.get();
assert!(column > side && side > 0.0, "a column holds a card's picture and what the tile adds: {column} {side}");
fixture.room(Vec2::new(column, 2000.0));
fixture.settle();
let (first, second) = (shown.borrow().tile(0), shown.borrow().tile(1));
assert!(second.top() >= first.bottom(), "one card per row: {first:?} {second:?}");
assert!(first.width() >= side - EPS, "the card keeps its picture side: {first:?} {side}");
fixture.room(Vec2::new(column - 2.0 * GAP, 2000.0));
fixture.settle();
let narrow = shown.borrow().tile(0);
assert!(narrow.width() < first.width(), "a narrower column shrinks the card: {narrow:?} {first:?}");
}
/// Tiles of the shown grids: enough rows to scroll several views.
const TILES: usize = 120;