look-ribbon-2: a ribbon's toggle buttons are flat at rest; a stacked label breaks at its own newline; a ribbon's stacked buttons keep two label lines and lay out from their top; trials and story

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Martin Ball
2026-11-19 13:53:41 +00:00
co-authored by Claude Opus 5.5
parent 1f43e0f81d
commit 718540f24b
5 changed files with 140 additions and 21 deletions
+41 -10
View File
@@ -1,7 +1,7 @@
//! What a push or toggle button shows: a leading icon (or spinner), a label and a trailing icon, centred in the
//! button unless it aligns them to an edge, and the look parts the buttons share.
use super::GroupLevel;
use super::{ControlPlace, GroupLevel};
use crate::contract::{Component, Cx, MeasureCx, PaintUi, Styled as _};
use crate::list::ThumbAspect;
use crate::primitives::{HAlign, IconSpec, TextLayout, TextRun};
@@ -22,16 +22,30 @@ pub(crate) struct FaceLook {
pub stacked_icon: f32,
/// How far under a stacked face's leading icon the split button's parts meet.
pub divide_gap: f32,
/// Whether a stacked face lays its block out from its top (`stacked_lines`): in a ribbon.
pub stacked_top: bool,
}
impl FaceLook {
/// The face look of the instance's variant: the control's gap and the stacked icon side.
pub(crate) fn of(cx: &StyleCx<'_>) -> FaceLook {
let control = cx.control();
FaceLook { gap: control.gap, stacked_icon: stacked_side(cx.tokens, control.icon), divide_gap: cx.tokens.space.gap.tight }
FaceLook {
gap: control.gap,
stacked_icon: stacked_side(cx.tokens, control.icon),
divide_gap: cx.tokens.space.gap.tight,
stacked_top: stacked_lines(cx.env::<ControlPlace>()) > 0,
}
}
}
/// The label lines a stacked face keeps room for whatever its label, laying its block out from its top: two in a
/// ribbon, where the large buttons share one height and their icons one line, a one-line label leaving its second line
/// empty, as the ribbon's large buttons always did; none elsewhere, where the face is as high as its content.
fn stacked_lines(place: ControlPlace) -> usize {
if place == ControlPlace::Ribbon { 2 } else { 0 }
}
/// The side of a stacked face's leading icon: the large icon, or the control's own icon when that is larger. The
/// style and the measure both take it from here, so the painted icon is the measured one.
pub(super) fn stacked_side(tokens: &UiTokens, control_icon: f32) -> f32 {
@@ -137,7 +151,8 @@ impl<'a> FaceSpec<'a> {
}
}
/// The lines of a stacked label: the label whole, or broken at its middle space when it has more than
/// The lines of a stacked label: broken where the label breaks its line itself (`"Page\nNumber"`, as the ribbon's
/// large buttons name the break), else whole, or broken at its middle space when it has more than
/// `ONE_LINE_CHARS` characters. The mnemonic stays on the character it marks.
fn lines(&self) -> Vec<TextRun<'a>> {
if self.label.is_empty() {
@@ -145,9 +160,16 @@ impl<'a> FaceSpec<'a> {
}
let label = self.label;
let whole = self.line(label, self.mnemonic);
let split = middle_space(label).filter(|_| label.chars().count() > ONE_LINE_CHARS).and_then(|at| label.split_at_checked(at));
let split = match label.split_once('\n') {
Some(lines) => Some(lines),
None => middle_space(label).filter(|_| label.chars().count() > ONE_LINE_CHARS).and_then(|at| label.split_at_checked(at)),
};
let Some((first, rest)) = split else { return vec![whole] };
let (first, second) = (first.trim_end(), rest.trim_start());
// A label that ends at its break keeps one line.
if second.is_empty() {
return vec![self.line(first, self.mnemonic.filter(|at| *at < first.chars().count()))];
}
// The characters before the second line: the first line and the spaces between.
let skipped = label.chars().count() - second.chars().count();
let (on_first, on_second) = match self.mnemonic {
@@ -184,8 +206,9 @@ struct Stack {
/// Lays a stacked face out in `area` from its lines' sizes: the leading icon of `lead_side` (a picture that high)
/// centred at the top, a gap,
/// then each line centred under it, the trailing icon of `side` after the last line at its reading end (on a row of
/// its own when there is no line). The block is centred vertically; `size` is what `measure` reports.
fn stack(spec: &FaceSpec<'_>, sides: (f32, f32), gap: f32, lines: &[Vec2], area: Rect, rtl: bool) -> Stack {
/// its own when there is no line). The block is centred vertically, or sits at the area's top when `top`
/// (`FaceLook::stacked_top`); `size` is the block's.
fn stack(spec: &FaceSpec<'_>, sides: (f32, f32), gap: f32, lines: &[Vec2], area: Rect, rtl: bool, top: bool) -> Stack {
let (lead_side, side) = sides;
let trail = spec.trail.is_some();
let last = lines.len().checked_sub(1);
@@ -203,7 +226,7 @@ fn stack(spec: &FaceSpec<'_>, sides: (f32, f32), gap: f32, lines: &[Vec2], area:
let width = rows.iter().map(|row| row.x).fold(lead_width, f32::max);
let size = Vec2::new(width, icon + under_icon + rows.iter().map(|row| row.y).sum::<f32>());
let middle = area.center().x;
let mut y = area.top() + (area.height() - size.y).max(0.0) / 2.0;
let mut y = if top { area.top() } else { area.top() + (area.height() - size.y).max(0.0) / 2.0 };
let lead = spec.leads().then(|| Rect::from_min_size(pos2(middle - lead_width / 2.0, y), Vec2::new(lead_width, lead_side)));
y += icon + under_icon;
let mut placed = Stack { size, lead, lines: Vec::new(), trail: None };
@@ -359,7 +382,15 @@ pub(crate) fn measure<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>)
let (side, lead_side) = (cx.icon(), stacked_side(cx.tokens, cx.icon()));
let lines = spec.lines();
let sizes = stacked_sizes(cx, spec, &lines, cx.room.unwrap_or(f32::INFINITY), side);
return stack(spec, (lead_side, side), cx.gap(), &sizes, Rect::ZERO, false).size;
let size = stack(spec, (lead_side, side), cx.gap(), &sizes, Rect::ZERO, false, false).size;
// Room for the lines the place keeps (`stacked_lines`) under the icon, whatever the label's own count.
let keep = stacked_lines(cx.env.get::<ControlPlace>());
if keep <= lines.len() {
return size;
}
let line = cx.layout_at(&spec.line("Ag", None), f32::INFINITY).size().y;
let icon = if spec.leads() { lead_side + cx.gap() } else { 0.0 };
return Vec2::new(size.x, size.y.max(icon + keep as f32 * line.max(if spec.trail.is_some() { side } else { 0.0 })));
}
let icon = cx.icon();
let fixed = spec.icons_width(icon, icon) + cx.gap() * spec.gaps() as f32;
@@ -484,7 +515,7 @@ fn paint_stacked<C: Component>(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextLook
let layouts: Vec<TextLayout> =
colored.iter().enumerate().map(|(i, run)| draw.layout(run, line_room(spec, i + 1 == count, area.width(), side, look.gap))).collect();
let sizes: Vec<Vec2> = layouts.iter().map(TextLayout::size).collect();
let placed = stack(spec, (look.stacked_icon, side), look.gap, &sizes, area, cx.flow.is_rtl());
let placed = stack(spec, (look.stacked_icon, side), look.gap, &sizes, area, cx.flow.is_rtl(), look.stacked_top);
if let (Some(lead), Some(slot)) = (spec.lead, placed.lead)
&& !spec.loading
{
@@ -506,7 +537,7 @@ fn stacked_in<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>, look: &F
let count = lines.len();
let sizes: Vec<Vec2> =
lines.iter().enumerate().map(|(i, run)| cx.layout_at(run, line_room(spec, i + 1 == count, area.width(), side, look.gap)).size()).collect();
stack(spec, (look.stacked_icon, side), look.gap, &sizes, area, rtl)
stack(spec, (look.stacked_icon, side), look.gap, &sizes, area, rtl, look.stacked_top)
}
/// Where a stacked split button's parts meet in `area`: halfway down the gap under the face's leading icon, so the
+4 -3
View File
@@ -37,9 +37,10 @@ pub enum GroupLevel {
/// Where controls are shown. A ribbon group sets `Ribbon` for its content (and for its collapsed button and the
/// popover that holds its content), and styles keyed on the env follow it:
///
/// - a `Button` or `SplitButton` that asks for no variant (or for the default `Variant::SECONDARY`) draws flat at
/// rest, as the ghost variant: no edge and no fill until the pointer is over it or presses it; a flat button's
/// sides take the control's padding (`space.pad.control`), not its corner round;
/// - a `Button`, `SplitButton` or `ToggleButton` that asks for no variant (or for the default `Variant::SECONDARY`)
/// draws flat at rest, as the ghost variant: no edge and no fill until the pointer is over it or presses it, and a
/// toggle shows the on plate while on; a flat button's sides take the control's padding (`space.pad.control`), not
/// its corner round;
/// - a `ComboBox` is as wide as its widest option and its chevron, not a field length, and a font picker is a short
/// field (`size.length.short`) whichever family it shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, EnvValue)]
+34
View File
@@ -249,6 +249,40 @@ fn toggle_button_stacked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
shown.into()
}
/// Stacked buttons in a ribbon group: flat at rest, one height for a one-line label and a label that names its break
/// (`"Page\nNumber"`, its chevron on the second line), icons on one line, and toggles flat off and on the plate on.
#[story(ToggleButton<'static>, covers = [], drive = Drive::Never, title = "Stacked in a ribbon")]
fn toggle_button_stacked_in_ribbon(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let shown = with_env(
ui,
|overrides| {
overrides.values.set(super::ControlPlace::Ribbon);
},
|ui| {
Row::new().show(ui, |ui, _| {
Button::new("Pictures").icon(IconId::new("image")).arrangement(Arrangement::Stacked).id_salt("pictures").show(ui);
Button::new("Page\nNumber")
.icon(IconId::new("copy"))
.trailing_icon(IconId::new("chevron_down"))
.arrangement(Arrangement::Stacked)
.id_salt("page number")
.show(ui);
ToggleButton::new("Track\nChanges", Bind::bound(data.value("track", false)))
.icon(IconId::new("eye"))
.arrangement(Arrangement::Stacked)
.id_salt("track")
.show(ui);
ToggleButton::new("Select", Bind::bound(data.value("select", true)))
.icon(IconId::new("eye"))
.arrangement(Arrangement::Stacked)
.id_salt("select")
.show(ui);
})
},
);
shown.into()
}
/// Rests the pointer on the toggle, clicks it and stays: its output reports the click while the pointer stays.
fn click_and_stay(fixture: &mut Fixture) {
if let Some(toggle) = fixture.by_label("Snap to grid") {
@@ -138,14 +138,10 @@ impl Component for ToggleButton<'_> {
}
fn style(cx: &StyleCx<'_>, key: ToggleButtonStyleKey) -> ToggleButtonStyle {
// An icon-only toggle draws as an icon button: the ghost square, with the on plate while on.
let ghost;
let cx = if key.icon_only {
ghost = cx.with_variant(Variant::GHOST);
&ghost
} else {
cx
};
// An icon-only toggle draws as an icon button: the ghost square, with the on plate while on. A labelled one in a
// ribbon is flat at rest as the ribbon's push buttons are (`placed`): no edge until the pointer is over it, and
// the on plate while on.
let cx = &if key.icon_only { cx.with_variant(Variant::GHOST) } else { super::placed(cx) };
let (off, on) = (cx.variant_look(), face::on_parts(cx));
let (mut text, mut icon) = face::ink(cx);
let (mut surface, metrics) = if key.icon_only {
+57
View File
@@ -91,6 +91,42 @@ fn a_stacked_label_stays_inside_the_stacked_height_in_every_density() {
}
}
/// A stacked label breaks where it names its break (`"Page\nNumber"`), whatever its length, and each part shows
/// whole on its own line: the line break is not elided into the first line.
#[trial]
fn a_stacked_label_breaks_at_its_own_line_break() {
for kind in [Kind::Button, Kind::Toggle, Kind::Split] {
let (control, lines) = stacked(kind, "Page\nNumber", ControlSize::Md);
assert_eq!(lines.len(), 2, "{kind:?}: the label breaks at its newline");
assert!(lines[1].min.y >= lines[0].max.y - 0.5, "{kind:?}: the second part is under the first");
for line in &lines {
assert!(control.expand(0.5).contains_rect(*line), "{kind:?}: the line {line:?} lies inside {control:?}");
}
}
}
/// In a ribbon, stacked buttons share one height whether their labels take one line or two, and lay out from their
/// tops, so their icons and first lines sit on one line across the row, as the ribbon's large buttons did.
#[trial]
fn a_ribbons_stacked_buttons_share_one_height_and_one_first_line() {
let ids = Rc::new(RefCell::new(Vec::<Id>::new()));
let seen = Rc::clone(&ids);
let mut fixture = Fixture::new(move |ui| {
in_ribbon(ui, |ui| {
let one = Button::new("Pictures").icon(IconId::new("copy")).arrangement(Arrangement::Stacked).show(ui).response.id;
let two = Button::new("Page\nNumber").icon(IconId::new("copy")).arrangement(Arrangement::Stacked).show(ui).response.id;
*seen.borrow_mut() = vec![one, two];
});
});
fixture.settle();
let rects: Vec<Rect> = ids.borrow().iter().filter_map(|id| fixture.node_of(*id).map(|node| node.rect)).collect();
assert_eq!(rects.len(), 2, "both buttons show");
assert!((rects[0].height() - rects[1].height()).abs() < 0.5, "one height for one and two lines: {rects:?}");
let top = |text: &str| fixture.texts().iter().find(|run| run.text == text).map_or(f32::NAN, |run| run.rect.min.y);
let (one, two) = (top("Pictures") - rects[0].min.y, top("Page") - rects[1].min.y);
assert!((one - two).abs() < 0.5, "the first lines sit as far under each top: {one} against {two}");
}
/// A fixture showing one toggle, the hover reports of each pass of a frame, and a switch that reruns the next
/// frame's pass.
struct HoverTrial {
@@ -386,6 +422,27 @@ fn a_ribbons_buttons_are_flat_at_rest_unless_they_ask_for_a_variant() {
});
assert_eq!(ribbon, ghost, "a ribbon split button draws the ghost surface");
assert!(narrow < wide - 0.5, "a ribbon's flat split button sits close: {narrow} against {wide}");
// A labelled toggle is flat at rest too, with no outlined capsule: the ghost surface, which shows the on plate
// while on.
let toggle = std::any::type_name::<ToggleButton<'static>>();
let (ribbon, narrow) = seen(toggle, "Track Changes", |ui| {
in_ribbon(ui, |ui| {
let mut on = false;
let _ = ToggleButton::new("Track Changes", Bind::bound(&mut on)).show(ui);
});
});
let (ghost, wide) = seen(toggle, "Track Changes", |ui| {
let mut on = false;
let _ = ToggleButton::new("Track Changes", Bind::bound(&mut on)).variant(Variant::GHOST).show(ui);
});
let (standard, _) = seen(toggle, "Track Changes", |ui| {
let mut on = false;
let _ = ToggleButton::new("Track Changes", Bind::bound(&mut on)).show(ui);
});
assert_eq!(ribbon, ghost, "a ribbon toggle draws the ghost surface");
assert_ne!(standard, ghost, "outside a ribbon a toggle keeps its outlined default");
assert!(narrow < wide - 0.5, "a ribbon's flat toggle sits close: {narrow} against {wide}");
}
/// In a ribbon a combo box is as wide as its widest option and its chevron, not a field length.