Merge branch 'red/ribbon-look' into area/ribbon-fw

This commit is contained in:
Martin Ball
2026-11-19 13:31:56 +00:00
15 changed files with 422 additions and 51 deletions
+8 -2
View File
@@ -18,7 +18,7 @@ use craft_ui::contract::{
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
};
use craft_ui::buttons::IconButton;
use craft_ui::buttons::{ControlPlace, IconButton};
use craft_ui::list::{ThumbSize, TrailingPart};
use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun};
use craft_ui::runtime::env::{EnvView, Label};
@@ -588,8 +588,11 @@ impl Component for FontPicker<'_> {
type Style = craft_ui::text::FieldStyle;
type Output = FontPickerOutput;
/// A field; in a ribbon (`ControlPlace::Ribbon`) at its shortest width (`size.length.short`), as a ribbon's font
/// box is.
fn style(cx: &craft_ui::style::StyleCx<'_>, _: FontPickerStyleKey) -> craft_ui::text::FieldStyle {
craft_ui::text::FieldStyle::at(cx)
let field = craft_ui::text::FieldStyle::at(cx);
if cx.env::<ControlPlace>() == ControlPlace::Ribbon { field.shortest() } else { field }
}
/// The wheel steps the family through the list.
@@ -598,9 +601,12 @@ impl Component for FontPicker<'_> {
}
/// The width of the longest family names in common use, so the field keeps its size whichever family is picked.
/// In a ribbon the style alone sets its width (`FieldStyle::shortest`): a longer name scrolls
/// in the field, as in a word processor's font box.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let current = cx.value().map_or("", String::as_str);
let widest = [NAME_SAMPLE, current].into_iter().map(|text| cx.field_text(&TextRun::new(text))).fold(Vec2::ZERO, Vec2::max);
let widest = if cx.env.get::<ControlPlace>() == ControlPlace::Ribbon { Vec2::new(0.0, widest.y) } else { widest };
let name = cx.words::<FontPickerWords>().list.clone();
let note = self.missing_note(current, &cx.words::<MissingFontsWords>());
Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, note.is_some())), widest.y)
+35 -1
View File
@@ -14,7 +14,8 @@ use craft_font_manager::picker::{
use craft_font_manager::{Catalog, FontEnv};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::env::Label;
use craft_ui::buttons::ControlPlace;
use craft_ui::runtime::env::{Label, with_env};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, Room, trial};
@@ -287,4 +288,37 @@ fn an_action_row_is_reported_not_committed_and_a_missing_family_shows_the_note_n
assert!(fx.part_rect(picker, PartKey::new("missing")).is_none(), "an installed family has no mark");
}
/// The width of a plain picker over `family`, in a ribbon group's place or not.
fn picker_width(family: &'static str, ribbon: bool) -> f32 {
let catalog = catalog_of(&[INTER_REGULAR]);
let mut fx = Fixture::new(move |ui| {
let mut family = family.to_owned();
let mut show = |ui: &mut egui::Ui| {
let _ = FontPicker::new("Font family", Bind::bound(&mut family), &catalog).kind(FontPickerKind::Plain).show(ui);
};
if ribbon {
with_env(
ui,
|overrides| {
overrides.values.set(ControlPlace::Ribbon);
},
show,
);
} else {
show(ui);
}
});
fx.in_room(Room::Window);
fx.settle();
fx.by_label("Font family").expect("the picker").rect.width()
}
/// In a ribbon the font box is a short field, narrower than in a form, and keeps its width whichever family it shows.
#[trial]
fn a_ribbons_font_box_is_short_and_keeps_its_width() {
let (ribbon, standard) = (picker_width("Inter", true), picker_width("Inter", false));
assert!(ribbon < standard - 0.5, "the ribbon's font box is narrower: {ribbon} against {standard}");
let long = picker_width("Source Sans Pro Semibold Condensed Extra", true);
assert!((long - ribbon).abs() < 0.5, "a long family name leaves its width: {long} against {ribbon}");
}
+22 -4
View File
@@ -32,6 +32,7 @@ use egui::{Id, Pos2, Rect, Response, Ui, Vec2, vec2};
pub use craft_ui::buttons::GroupLevel;
pub use gallery::{Gallery, GalleryFace, GalleryItem, GalleryMore, GalleryOutput};
pub use group::RibbonGroup;
use group::BodyHeight;
pub use plan::{GroupWidths, plan};
craft_ui::words! {
@@ -261,15 +262,24 @@ fn show_row<T: Clone + Eq + Hash + Send + Sync + Debug + 'static>(
let distance = cx.style::<Region>().map_or(0.0, |style| style.slide);
let lead = gap.clamp(-1.0, 1.0) * side * distance;
let chevron = cx.style::<Region>().map_or(0.0, |style| style.chevron);
let least = cx.style::<Region>().map_or(0.0, |style| style.body);
// The row moves through the slide container's own offset, which places its body on a layer of its own.
let shown = Region::slide(lead)
.show(ui, |ui, _| {
// The titles sit under the tallest content of the last pass; a change shows in the next frame.
let slot = base.with("ribbon.body");
let last = with_session(ui.ctx(), slot, |kept: &mut BodyHeight| kept.0);
let row = Row::new().scroll(Scroll::horizontal()).fill_width().show(ui, |ui, _| {
let mut row = RibbonRow { ui, base, groups: Vec::new() };
let mut row = RibbonRow { ui, base, groups: Vec::new(), body: last.max(least), tallest: 0.0 };
body(&mut row, key);
row.groups
(row.groups, row.tallest)
});
(row.output.id, row.output.rect, row.inner.unwrap_or_default())
let (groups, tallest) = row.inner.unwrap_or_default();
if tallest > 0.0 && (tallest - last).abs() >= 0.5 {
with_session(ui.ctx(), slot, |kept: &mut BodyHeight| kept.0 = tallest);
ui.ctx().request_repaint();
}
(row.output.id, row.output.rect, groups)
})
.inner;
if let Some((owner, view, groups)) = shown {
@@ -350,6 +360,10 @@ pub struct RibbonRow<'a> {
base: Id,
/// The rect of each group this run of the row showed, in order: the units the edge chevrons step by.
groups: Vec<Rect>,
/// The height under each open group's top at which its title row sits: the tallest content of the last pass.
body: f32,
/// The tallest open group content of this run, every level the row measured included.
tallest: f32,
}
/// What the ribbon reports for a pass.
@@ -386,6 +400,9 @@ struct RegionStyle {
slide: f32,
/// The width of an edge chevron: a hit target's.
chevron: f32,
/// The least height of the group row's body, under which each group's title sits: three controls stacked with the
/// row gap between them, the ribbon's three rows of small buttons. Taller content lowers every title with it.
body: f32,
}
/// What a row region reports.
@@ -443,7 +460,8 @@ impl Component for Region {
type Output = RegionOutput;
fn style(cx: &StyleCx<'_>, _: RegionStyleKey) -> RegionStyle {
RegionStyle { metrics: Metrics::new(), slide: cx.tokens.motion.slide as f32, chevron: cx.tokens.size.hit.target }
let body = 3.0 * cx.control().height + 2.0 * cx.tokens.space.gap.row;
RegionStyle { metrics: Metrics::new(), slide: cx.tokens.motion.slide as f32, chevron: cx.tokens.size.hit.target, body }
}
fn sense(&self) -> Sense {
+96 -26
View File
@@ -16,11 +16,11 @@ use craft_ui::contract::{
use craft_ui::display::{Picture, PictureSize};
use craft_ui::list::{ThumbAspect, ThumbSize};
use craft_ui::primitives::textures::{Revision, ThumbSource, Thumbnails};
use craft_ui::primitives::{ContentPainterCx, PaintShape};
use craft_ui::primitives::{ContentPainterCx, HAlign, PaintShape, TextRun};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::focus::KeyUse;
use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleColor, StyleCx};
use craft_ui::tile_grid::{Tile, TileGrid};
use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleColor, StyleCx, TypeRole};
use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use egui::{ColorImage, CornerRadius, Rect, Response, Ui, Vec2};
use super::GroupLevel;
@@ -54,6 +54,8 @@ craft_ui::words! {
/// - The up and down buttons (and the Up and Down keys on the strip) move the shown tiles by the count shown; the
/// shown run never runs past the last full run, so no tile is empty, and it falls back when the items shrink.
/// - More opens the whole list as a grid, runs a command, or opens the app's own body.
/// - Each tile's picture is [`aspect`](Gallery::aspect) times as wide as the medium thumbnail is high (square unless
/// set), and with `CaptionPlace::Below` the tile names its item under the picture (a style gallery's 'Normal').
#[must_use = "show the gallery with `show`"]
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(overlay, probe(Gallery<'static, usize>))]
@@ -65,6 +67,10 @@ pub struct Gallery<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
full: u8,
compact: u8,
more: GalleryMore<'a>,
/// The width of each tile's picture as a multiple of its height.
aspect: ThumbAspect,
/// Where a tile shows its item's name: `Below` the picture, else nowhere.
caption: CaptionPlace,
/// Each shown tile's rect.
laid: Vec<Rect>,
picked: Option<K>,
@@ -94,6 +100,8 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
full: 1,
compact: 1,
more: GalleryMore::Grid,
aspect: ThumbAspect::SQUARE,
caption: CaptionPlace::None,
laid: Vec::new(),
picked: None,
menu: None,
@@ -114,6 +122,25 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
self
}
/// The width of each tile's picture as a multiple of its height, the medium thumbnail's (`size.thumb.md`): a wide
/// sample (a paragraph style's first letters) fills a wide tile instead of shrinking into a square one.
pub fn aspect(mut self, aspect: ThumbAspect) -> Self {
self.aspect = aspect;
self
}
/// Where each tile shows its item's name: `CaptionPlace::Below` names it under the picture, in the caption role;
/// `None` (the default) and `Start` show no name. The name stays each tile's accessible name either way.
pub fn caption(mut self, caption: CaptionPlace) -> Self {
self.caption = caption;
self
}
/// Whether the tiles name their items under the pictures.
fn captioned(&self) -> bool {
self.caption == CaptionPlace::Below
}
/// The tiles the level shows at most.
fn visible(&self, level: GroupLevel) -> usize {
usize::from(if level == GroupLevel::Compact { self.compact } else { self.full }).max(1)
@@ -134,7 +161,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
fn sizes(&self, cx: &MeasureCx<'_, Self>) -> Sizes {
let words = cx.env.words::<GalleryWords>();
let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()));
Sizes { tile: cx.face(GalleryTile::blank()), button, gap: cx.gap() }
Sizes { tile: cx.face(GalleryTile::blank(self.aspect, self.captioned())), button, gap: cx.gap() }
}
}
@@ -172,28 +199,30 @@ pub enum GalleryFace<'a> {
Paint(&'a dyn Fn(&ContentPainterCx, Rect)),
}
/// The size every tile's picture has, so a tile measures the same with and without its picture.
fn thumb(picture: Picture<'_>) -> Picture<'_> {
picture.extent(PictureSize::Thumb(ThumbSize::Medium))
/// The size every tile's picture has, `aspect` times as wide as high, so a tile measures the same with and without
/// its picture.
fn thumb(picture: Picture<'_>, aspect: ThumbAspect) -> Picture<'_> {
picture.extent(PictureSize::Thumb(ThumbSize::Medium)).aspect(aspect)
}
/// A picture that paints nothing, for measuring a tile.
fn blank_picture() -> Picture<'static> {
thumb(Picture::painter(Label::default(), ThumbAspect::SQUARE, |_: &ContentPainterCx<'_>, _: Rect| {}))
fn blank_picture(aspect: ThumbAspect) -> Picture<'static> {
thumb(Picture::painter(Label::default(), aspect, |_: &ContentPainterCx<'_>, _: Rect| {}), aspect)
}
impl<'a> GalleryFace<'a> {
/// The picture this face shows. It is decoration: the tile that holds it carries the name.
fn picture(&self) -> Picture<'a> {
/// The picture this face shows, `aspect` times as wide as high. It is decoration: the tile that holds it carries
/// the name.
fn picture(&self, aspect: ThumbAspect) -> Picture<'a> {
let picture = match self {
GalleryFace::Image { key, revision, image } => Picture::new(Label::default(), *key, *image).revision(*revision),
GalleryFace::Rendered { key, thumbnails, source } => Picture::rendered(Label::default(), *key, *thumbnails, *source),
GalleryFace::Paint(paint) => {
let paint = *paint;
Picture::painter(Label::default(), ThumbAspect::SQUARE, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect))
Picture::painter(Label::default(), aspect, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect))
}
};
thumb(picture)
thumb(picture, aspect)
}
}
@@ -257,11 +286,11 @@ struct GridResult {
/// The whole list as a grid of the same faces; a click or Enter picks, and a context request is forwarded. The
/// grid sizes its columns from the room it is given.
fn grid<K>(ui: &mut Ui, label: &Label, items: &[GalleryItem<'_, K>], current: Option<usize>) -> GridResult {
fn grid<K>(ui: &mut Ui, label: &Label, items: &[GalleryItem<'_, K>], current: Option<usize>, aspect: ThumbAspect) -> GridResult {
let selection = Selection::new(current.into_iter().collect(), current, current);
let grid = TileGrid::<usize>::new(label.clone()).select(SelectMode::Single).selection(Bind::given(selection));
let out = grid.show_items(ui, &Indexes(items.len()), &mut |key, _| match items.get(*key) {
Some(item) => Tile::new(item.label.clone()).picture(ThumbAspect::SQUARE, item.face.picture()),
Some(item) => Tile::new(item.label.clone()).picture(aspect, item.face.picture(aspect)),
None => Tile::new(Label::default()),
});
let mut result = GridResult::default();
@@ -299,9 +328,16 @@ struct GalleryTileStyle {
fill: StyleColor,
/// The current tile's edge.
edge: StyleColor,
/// The ink of the item's name under the picture, in a captioned gallery.
caption: StyleColor,
/// Between the picture and the caption.
gap: f32,
/// The picture's height: the medium thumbnail's (`size.thumb.md`), as `thumb` sizes it.
thumb: f32,
}
/// The face a tile part wears: its picture inside the tile's selection look.
/// The face a tile part wears: its picture, and in a captioned gallery the item's name under it, inside the tile's
/// selection look.
#[derive(craft_ui::contract::Component)]
#[component(unregistered)]
struct GalleryTile<'a> {
@@ -311,20 +347,27 @@ struct GalleryTile<'a> {
picture: Option<Picture<'a>>,
/// Whether the tile is the gallery's current item.
selected: bool,
/// The width of the picture as a multiple of its height.
aspect: ThumbAspect,
/// The item's name under the picture; `None` in a gallery without captions.
caption: Option<Label>,
}
impl<'a> GalleryTile<'a> {
/// A tile that shows `picture`.
fn of(picture: Picture<'a>, selected: bool) -> Self {
GalleryTile { common: Common::new(), picture: Some(picture), selected }
/// A tile that shows `picture`, `aspect` times as wide as high, with `caption` under it when set.
fn of(picture: Picture<'a>, selected: bool, aspect: ThumbAspect, caption: Option<Label>) -> Self {
GalleryTile { common: Common::new(), picture: Some(picture), selected, aspect, caption }
}
/// A tile with no picture, for measuring.
fn blank() -> Self {
GalleryTile { common: Common::new(), picture: None, selected: false }
/// A tile with no picture, for measuring; a `captioned` one keeps a line for its caption.
fn blank(aspect: ThumbAspect, captioned: bool) -> Self {
GalleryTile { common: Common::new(), picture: None, selected: false, aspect, caption: captioned.then(Label::default) }
}
}
/// The caption's type role.
const CAPTION: TypeRole = TypeRole::Caption;
impl Component for GalleryTile<'_> {
const DISABLED: DisabledLook = DisabledLook::Faded;
const ROLE: Role = Role::IMAGE;
@@ -344,11 +387,23 @@ impl Component for GalleryTile<'_> {
stroke: cx.tokens.stroke.thin,
fill: cx.color(colors.state.selected),
edge: cx.color(colors.line.control_edge),
caption: cx.color(colors.text.normal),
gap: cx.tokens.space.gap.tight,
thumb: cx.tokens.size.thumb.md,
}
}
/// The picture, and in a captioned gallery the gap and one caption line under it. The caption is as wide as the
/// picture: a longer name elides.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
cx.face(blank_picture())
let picture = cx.face(blank_picture(self.aspect));
match self.caption {
Some(_) => {
let line = cx.layout(&TextRun::new("Ag").role(CAPTION)).size().y;
Vec2::new(picture.x, picture.y + cx.style.gap + line)
}
None => picture,
}
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
@@ -362,9 +417,22 @@ impl Component for GalleryTile<'_> {
draw.fill(&PaintShape::Rect(outer, CornerRadius::ZERO), cx.style.edge);
draw.fill(&PaintShape::Rect(outer.shrink(cx.style.stroke), CornerRadius::ZERO), cx.style.fill);
}
// A captioned tile keeps the picture's height at the top and shows the name in the rest under it.
let (area, caption) = match self.caption {
Some(_) => {
let picture = Rect::from_min_size(area.min, Vec2::new(area.width(), cx.style.thumb.min(area.height())));
let top = (picture.max.y + cx.style.gap).min(area.max.y);
(picture, Some(Rect::from_min_max(egui::pos2(area.min.x, top), area.max)))
}
None => (area, None),
};
if let Some(picture) = self.picture.take() {
let _ = ui.child("picture", area, picture);
}
if let (Some(rect), Some(name)) = (caption, self.caption.as_ref()) {
let run = TextRun::new(name.as_str()).role(CAPTION).color(cx.style.caption).align(HAlign::Center).elide();
let _ = ui.draw().text(rect, &run);
}
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
@@ -482,14 +550,14 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K>
}
let popup = cx.popup("more");
let name = cx.label();
let (items, current) = (self.items, self.current_at());
let (items, current, aspect) = (self.items, self.current_at(), self.aspect);
let more = &mut self.more;
let shown = ui.show(popup, Overlay::popover(), |ui, _| match more {
GalleryMore::Body(body) => {
(**body)(ui);
GridResult::default()
}
_ => grid(ui, &name, items, current),
_ => grid(ui, &name, items, current, aspect),
});
let Some(result) = shown else { return };
if let Some(item) = result.picked.and_then(|at| items.get(at)) {
@@ -534,7 +602,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K>
let current = self.current_at();
for at in 0..visible.min(len) {
if let Some(item) = self.items.get(start + at) {
ui.face(TILE.at(at as u64), GalleryTile::of(item.face.picture(), current == Some(start + at)));
let caption = self.captioned().then(|| item.label.clone());
let tile = GalleryTile::of(item.face.picture(self.aspect), current == Some(start + at), self.aspect, caption);
ui.face(TILE.at(at as u64), tile);
}
}
ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0));
+21
View File
@@ -6,7 +6,9 @@ use craft_host::InlineJobs;
use craft_ui::contract::Show as _;
use craft_ui::primitives::textures::Revision;
use craft_ui::primitives::{FakeThumbSource, Thumbnails, ThumbnailOptions};
use craft_ui::list::ThumbAspect;
use craft_ui::runtime::env::{Label, with_env};
use craft_ui::tile_grid::CaptionPlace;
use craft_ui::testing::pictures::sample_picture;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use egui::Ui;
@@ -46,6 +48,25 @@ fn gallery(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
pictured(ui)
}
/// A style gallery: wide samples, two to one, each named under its picture.
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)]
fn gallery_captioned(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let images: Vec<Box<dyn Fn() -> egui::ColorImage>> =
(0..COUNT).map(|at| Box::new(move || sample_picture(at as u64, [96, 48])) as Box<dyn Fn() -> egui::ColorImage>).collect();
let items: Vec<GalleryItem<'_, usize>> = images
.iter()
.enumerate()
.map(|(at, image)| GalleryItem { key: at, label: name(at), face: GalleryFace::Image { key: at as u64, revision: Revision::default(), image: &**image } })
.collect();
let current = 2;
Gallery::new("Styles", &items, Some(&current))
.tiles(6, 3)
.aspect(ThumbAspect::new(2, 1))
.caption(CaptionPlace::Below)
.show(ui)
.into()
}
#[story(Gallery<'static, usize>, covers = [], drive = Drive::Never)]
fn gallery_compact(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
with_env(
+36 -12
View File
@@ -4,7 +4,7 @@ use std::hash::Hash;
use craft_behavior::IconId;
use craft_keymap::CommandRef;
use craft_ui::buttons::{Arrangement, Button, IconButton};
use craft_ui::buttons::{Arrangement, Button, ControlPlace, IconButton};
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Trigger};
use craft_ui::display::{Divider, Shade, Text};
use craft_ui::layout::levelled_unit;
@@ -14,7 +14,7 @@ use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Env, Label, with_env};
use craft_ui::runtime::memory::key_salt;
use craft_ui::style::TypeRole;
use egui::{Id, Rect, Ui};
use egui::{Id, Rect, Ui, Vec2};
use super::{GroupLevel, RibbonRow};
@@ -51,10 +51,16 @@ impl<'a> RibbonGroup<'a> {
self
}
/// The group's content over its title row; the title row carries the launcher.
fn open(&self, ui: &mut Ui, add: &mut dyn FnMut(&mut Ui)) {
/// The group's content over its title row; the title row carries the launcher. The title row sits `body` under the
/// content's top whatever the content's height, so every group's title shares one line at the foot of the row; a
/// taller content pushes it down. Returns the content's height, which sets `body` for the row's next pass.
fn open(&self, ui: &mut Ui, add: &mut dyn FnMut(&mut Ui), body: f32) -> f32 {
let mut took = 0.0;
Stack::new().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| add(ui));
took = Row::new().show(ui, |ui, _| add(ui)).output.rect.height();
// Every group places this spacer, an empty one too, so each has the same gaps above its title.
let rest = if (body - took).is_finite() { (body - took).max(0.0) } else { 0.0 };
craft_ui::layout::place_in_flow(ui, Vec2::new(0.0, rest));
Row::new().show(ui, |ui, _| {
Text::new(self.title.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
if let Some(command) = &self.launcher {
@@ -64,6 +70,7 @@ impl<'a> RibbonGroup<'a> {
}
});
});
took
}
/// One button with the group's icon and title; its popover holds the content at the full level. A press in a
@@ -84,6 +91,7 @@ impl<'a> RibbonGroup<'a> {
ui,
|overrides| {
overrides.values.set(GroupLevel::Full);
overrides.values.set(ControlPlace::Ribbon);
},
|ui| {
Row::new().show(ui, |ui, _| add(ui));
@@ -93,24 +101,32 @@ impl<'a> RibbonGroup<'a> {
}
/// The group as the row shows it at `level`: one container `id`, a group node named by the title (a labelled
/// `Row` reports `Role::GROUP`), holding the body and the divider after it. Returns the rect it took.
fn unit(&self, ui: &mut Ui, id: Id, add: &mut dyn FnMut(&mut Ui), level: GroupLevel) -> Rect {
Row::new()
/// `Row` reports `Role::GROUP`), holding the body and the divider after it. An open group's title sits `body`
/// under its top (`open`). Returns the rect it took and the height of its open content (none when collapsed).
fn unit(&self, ui: &mut Ui, id: Id, add: &mut dyn FnMut(&mut Ui), level: GroupLevel, body: f32) -> (Rect, Option<f32>) {
let mut content = None;
let rect = Row::new()
.id(id)
.label(self.title.clone())
.show(ui, |ui, _| {
if level == GroupLevel::Collapsed {
self.collapsed(ui, add);
} else {
self.open(ui, add);
content = Some(self.open(ui, add, body));
}
Divider::vertical().show(ui);
})
.output
.rect
.rect;
(rect, content)
}
}
/// The height of the tallest open group content the ribbon's row showed in its last pass: the line every group's
/// title sits under. Kept in the ribbon's session memory.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct BodyHeight(pub(super) f32);
impl RibbonRow<'_> {
/// Adds `group` to the row, at the level the row's fit gives it; `add` fills its content.
///
@@ -122,17 +138,25 @@ impl RibbonRow<'_> {
pub fn group(&mut self, group: RibbonGroup<'_>, mut add: impl FnMut(&mut Ui)) -> &mut Self {
let id = self.base.with(("ribbon.group", group.key));
let mut shown = None;
let body = self.body;
let mut tallest = self.tallest;
levelled_unit(self.ui, id, LEVELS.len(), |ui, at| {
let level = LEVELS.get(at).copied().unwrap_or(GroupLevel::Collapsed);
let rect = with_env(
// A ribbon's controls take the ribbon's look: flat buttons, fields as long as the ribbon's.
let (rect, content) = with_env(
ui,
|overrides| {
overrides.values.set(level);
overrides.values.set(ControlPlace::Ribbon);
},
|ui| group.unit(ui, id, &mut add, level),
|ui| group.unit(ui, id, &mut add, level, body),
);
if let Some(content) = content.filter(|height| height.is_finite()) {
tallest = tallest.max(content);
}
shown = Some(rect);
});
self.tallest = tallest;
if let Some(rect) = shown {
self.groups.push(rect);
}
+32 -3
View File
@@ -1,5 +1,5 @@
//! The ribbon: the fit rule, keyed group levels, a collapsed group's popover, the tab-change slide, the run model and
//! the ribbon's own context menu.
//! The ribbon: the fit rule, keyed group levels, a collapsed group's popover, the tab-change slide, the run model, the
//! line group titles share and the ribbon's own context menu.
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -10,7 +10,8 @@ use craft_behavior::{IconId, MotionMode};
use craft_keymap::CommandRef;
use craft_menu::{GroupLevel, GroupWidths, Ribbon, RibbonGroup, RibbonMenuRequest, RibbonRow, RibbonTab, plan};
use craft_ui::buttons::{Arrangement, Button, SplitButton};
use craft_ui::contract::{Bind, BodyCx, Entry, Props as _, Show as _};
use craft_ui::contract::{Bind, BodyCx, Entry, Props as _, Show as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::menu::MenuItem;
use craft_ui::runtime::env::{Direction, Env};
use craft_ui::runtime::inspect::{Element, Recorded};
@@ -302,6 +303,34 @@ fn a_settled_ribbon_runs_each_group_body_once() {
assert!(last_pass_measuring_runs(fixture.ctx()).is_empty(), "a pass with unchanged inputs runs no measuring run");
}
/// Every open group's title sits on one line at the foot of the row whatever its content's height: a group of one
/// button, a group of three stacked rows and a group of one stacked button.
#[trial]
fn every_open_groups_title_sits_on_one_line() {
let mut fixture = Fixture::new(|ui| {
let tabs = [RibbonTab::new(0_usize, "Home")];
let _ = Ribbon::new("Ribbon", &tabs, Bind::given(0_usize)).show(ui, |row, _| {
row.group(RibbonGroup::new("short", "Short", IconId::new("list").into()), |ui| {
Button::new("One").show(ui);
});
row.group(RibbonGroup::new("rows", "Rows", IconId::new("list").into()), |ui| {
Stack::new().show(ui, |ui, _| {
for label in ["First", "Second", "Third"] {
Button::new(label).show(ui);
}
});
});
group(row, "big", "Big", &["Large"]);
});
});
fixture.room(vec2(900.0, 400.0));
fixture.settle();
let baseline = |title: &str| fixture.texts().iter().find(|run| run.text == title).map_or(f32::NAN, |run| run.baseline);
let (short, rows, big) = (baseline("Short"), baseline("Rows"), baseline("Big"));
assert!((short - rows).abs() < 0.5, "a one-button group's title is on the line of a three-row group's: {short} against {rows}");
assert!((big - rows).abs() < 0.5, "a stacked button group's title is on the same line: {big} against {rows}");
}
/// Presses and releases the secondary button at `at`, a frame each.
fn right_click(fixture: &mut Fixture, at: Pos2) {
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
+32
View File
@@ -5,7 +5,9 @@ use std::rc::Rc;
use craft_menu::{Gallery, GalleryFace, GalleryItem, GroupLevel};
use craft_ui::contract::Show as _;
use craft_ui::list::ThumbAspect;
use craft_ui::primitives::ContentPainterCx;
use craft_ui::tile_grid::CaptionPlace;
use craft_ui::runtime::env::{Label, with_env};
use craft_ui::testing::{Fixture, trial};
use egui::Rect;
@@ -68,3 +70,33 @@ fn the_tile_count_follows_the_group_level_and_stepping_stays_in_range_when_the_i
fixture.settle();
assert_eq!(*picks.borrow(), vec![1], "a click on a tile picks its key");
}
/// The tiles' rects and the painted texts of a gallery of three, square and uncaptioned or two to one and named under
/// each picture.
fn tiles(wide: bool) -> (Vec<Rect>, Vec<String>) {
let mut fixture = Fixture::new(move |ui| {
let paint = |_: &ContentPainterCx, _: Rect| {};
let items: Vec<GalleryItem<'_, usize>> =
(0..3).map(|at| GalleryItem { key: at, label: Label::from(format!("Tile {at}")), face: GalleryFace::Paint(&paint) }).collect();
let gallery = Gallery::new("Styles", &items, None).tiles(3, 3);
let gallery = if wide { gallery.aspect(ThumbAspect::new(2, 1)).caption(CaptionPlace::Below) } else { gallery };
let _ = gallery.show(ui);
});
fixture.settle();
let rects = (0..3).filter_map(|at| fixture.by_label(&format!("Tile {at}")).map(|tile| tile.rect)).collect();
(rects, fixture.texts().iter().map(|run| run.text.clone()).collect())
}
/// A style gallery's tiles are twice as wide as a square one's and name their items under the pictures; a plain
/// gallery's tiles are square and show no names.
#[trial]
fn a_wide_captioned_gallery_names_its_tiles_under_wide_pictures() {
let (square, plain) = tiles(false);
let (wide, named) = tiles(true);
assert_eq!((square.len(), wide.len()), (3, 3), "every tile shows");
let (square, wide) = (square[0], wide[0]);
assert!(wide.width() > 1.5 * square.width(), "a two to one tile is wider: {wide:?} against {square:?}");
assert!(wide.height() > square.height() + 0.5, "a captioned tile keeps a line for its name: {wide:?} against {square:?}");
assert!(named.iter().any(|text| text == "Tile 0"), "a captioned tile paints its name: {named:?}");
assert!(!plain.iter().any(|text| text == "Tile 0"), "a plain tile paints no name: {plain:?}");
}
+1
View File
@@ -240,6 +240,7 @@ impl Component for Button<'_> {
type Output = ButtonOutput;
fn style(cx: &StyleCx<'_>, key: ButtonStyleKey) -> ButtonStyle {
let cx = &super::placed(cx);
let mut style = match key.tint {
Some(tint) => ButtonStyle::tinted(cx, tint),
None => ButtonStyle::of(cx),
+4 -1
View File
@@ -247,7 +247,10 @@ fn stacked_sizes<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>, lines
pub(super) fn metrics(cx: &StyleCx<'_>, parts: &VariantParts) -> Metrics {
let control = cx.control();
let round = f32::from(parts.radius.nw).min(control.height / 2.0);
Metrics::new().padding(Insets::horizontal(control.pad_x.max(round + control.gap))).min_size(Vec2::new(0.0, control.height)).gap(control.gap)
// The sides clear the corner round, so an edge never crosses the label. A ribbon's flat button has no edge at rest
// (`ControlPlace::Ribbon`): its sides take the control's padding, as a ribbon's controls sit close.
let side = if super::flat_in_ribbon(cx) { control.pad_x } else { control.pad_x.max(round + control.gap) };
Metrics::new().padding(Insets::horizontal(side)).min_size(Vec2::new(0.0, control.height)).gap(control.gap)
}
/// The metrics of a stacked face: `metrics`, with the control's gap above and below the stack, so its height is the
+34
View File
@@ -33,3 +33,37 @@ pub enum GroupLevel {
/// The group is collapsed into one button.
Collapsed,
}
/// 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 `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)]
#[env(style)]
#[non_exhaustive]
pub enum ControlPlace {
/// Anywhere but a ribbon: each control's own look and length.
#[default]
Standard,
/// In a ribbon group.
Ribbon,
}
/// The style context a push or split button draws in: in a ribbon (`ControlPlace::Ribbon`) the default variant
/// becomes the ghost one, so the button is flat at rest; any other variant, and any other place, stays as it is.
pub(crate) fn placed<'a>(cx: &crate::style::StyleCx<'a>) -> crate::style::StyleCx<'a> {
if cx.variant == craft_theme::Variant::SECONDARY && cx.env::<ControlPlace>() == ControlPlace::Ribbon {
cx.with_variant(craft_theme::Variant::GHOST)
} else {
*cx
}
}
/// Whether a button styled in `cx` is a ribbon's flat button: the ghost variant in a ribbon (`ControlPlace::Ribbon`).
pub(crate) fn flat_in_ribbon(cx: &crate::style::StyleCx<'_>) -> bool {
cx.variant == craft_theme::Variant::GHOST && cx.env::<ControlPlace>() == ControlPlace::Ribbon
}
@@ -154,6 +154,7 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
type Output = SplitOutput<T>;
fn style(cx: &StyleCx<'_>, key: SplitButtonStyleKey<T>) -> SplitButtonStyle {
let cx = &super::placed(cx);
let parts = cx.variant_look();
let metrics = face::metrics_of(cx, &parts, key.arrangement);
let mut surface = face::surface(cx, &parts);
+3 -1
View File
@@ -166,8 +166,10 @@ impl Component for ComboBox<'_> {
type Style = crate::text::FieldStyle;
type Output = ComboBoxOutput;
/// A field; in a ribbon (`ControlPlace::Ribbon`) sized by its options alone, as a ribbon's font size box is.
fn style(cx: &crate::style::StyleCx<'_>, _: ComboBoxStyleKey) -> crate::text::FieldStyle {
crate::text::FieldStyle::at(cx)
let field = crate::text::FieldStyle::at(cx);
if cx.env::<crate::buttons::ControlPlace>() == crate::buttons::ControlPlace::Ribbon { field.sized_by_content() } else { field }
}
/// The wheel steps the text through the options.
+8
View File
@@ -74,6 +74,14 @@ impl FieldStyle {
self
}
/// The style of a field with no field length to widen it past its shortest width (`size.length.short`): a
/// ribbon's font box, which keeps that width whichever family it shows, as a word processor's does.
#[must_use]
pub fn shortest(mut self) -> FieldStyle {
self.metrics = self.metrics.ideal_width(self.metrics.min_size.x);
self
}
/// The field's padding, gap and minimum size.
pub fn metrics(&self) -> Metrics {
self.metrics
+89 -1
View File
@@ -4,9 +4,11 @@
use craft_behavior::{IconId, PartKey};
use craft_theme::ControlSize;
use craft_ui::buttons::{Arrangement, Button, GroupLevel, SplitButton, SplitMenu, ToggleButton};
use craft_theme::Variant;
use craft_ui::buttons::{Arrangement, Button, ControlPlace, GroupLevel, SplitButton, SplitMenu, ToggleButton};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Role, Show as _};
use craft_ui::pickers::ComboBox;
use craft_ui::display::Picture;
use craft_ui::list::ThumbAspect;
use craft_ui::runtime::commands::CommandState;
@@ -325,3 +327,89 @@ fn a_click_on_a_buttons_picture_activates_the_button_which_stays_one_access_node
assert!(fixture.tree().children_of(button.node).is_empty(), "the picture adds no node under the button");
assert!(fixture.by_role(Role::IMAGE).is_empty(), "the picture is not a node of its own");
}
/// The surface of the first style of `type_name` resolved when `show` runs alone, and the width of the control
/// named `name`.
fn seen(type_name: &str, name: &str, show: impl Fn(&mut Ui) + 'static) -> (Option<craft_ui::style::SurfaceLook>, f32) {
let mut fixture = Fixture::new(move |ui| show(ui));
fixture.settle();
let style = fixture.styles_of(type_name).into_iter().next().expect("the control resolved its style");
(style.looks.surface.clone(), fixture.by_label(name).expect("the control").rect.width())
}
/// Shows `show` where a ribbon group shows its content.
fn in_ribbon(ui: &mut Ui, show: impl FnOnce(&mut Ui)) {
with_env(
ui,
|overrides| {
overrides.values.set(ControlPlace::Ribbon);
},
show,
);
}
/// In a ribbon a push or split button that asks for no variant is flat at rest: it draws the ghost surface, and its
/// sides take the control's padding, so it is narrower than a ghost button elsewhere. Anywhere else a button keeps its
/// outlined default, and in a ribbon a variant it asks for stays.
#[trial]
fn a_ribbons_buttons_are_flat_at_rest_unless_they_ask_for_a_variant() {
let button = std::any::type_name::<Button<'static>>();
let (ribbon, narrow) = seen(button, "Copy", |ui| {
in_ribbon(ui, |ui| {
let _ = Button::new("Copy").show(ui);
});
});
let (ghost, wide) = seen(button, "Copy", |ui| {
let _ = Button::new("Copy").variant(Variant::GHOST).show(ui);
});
let (standard, _) = seen(button, "Copy", |ui| {
let _ = Button::new("Copy").show(ui);
});
let (primary, _) = seen(button, "Copy", |ui| {
in_ribbon(ui, |ui| {
let _ = Button::new("Copy").variant(Variant::PRIMARY).show(ui);
});
});
assert!(ghost.is_some(), "a button has a surface");
assert_eq!(ribbon, ghost, "a ribbon button draws the ghost surface");
assert_ne!(standard, ghost, "outside a ribbon the default look stays");
assert_ne!(primary, ghost, "a variant asked for in a ribbon stays");
assert!(narrow < wide - 0.5, "a ribbon's flat button sits close: {narrow} against {wide}");
let split = std::any::type_name::<SplitButton<'static, usize>>();
let (ribbon, narrow) = seen(split, "Paste", |ui| {
let entries = [Entry::new(1_usize, "Keep text only")];
in_ribbon(ui, |ui| {
let _ = SplitButton::new("Paste", &entries).show(ui);
});
});
let (ghost, wide) = seen(split, "Paste", |ui| {
let entries = [Entry::new(1_usize, "Keep text only")];
let _ = SplitButton::new("Paste", &entries).variant(Variant::GHOST).show(ui);
});
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}");
}
/// In a ribbon a combo box is as wide as its widest option and its chevron, not a field length.
#[trial]
fn a_ribbons_combo_box_is_as_wide_as_its_options() {
let width = |ribbon: bool| {
let mut fixture = Fixture::new(move |ui| {
let options = [Entry::new("8".to_owned(), "8"), Entry::new("72".to_owned(), "72")];
let mut size = "11".to_owned();
let mut show = |ui: &mut Ui| {
let _ = ComboBox::new("Font Size", Bind::bound(&mut size), &options).show(ui);
};
if ribbon {
in_ribbon(ui, show);
} else {
show(ui);
}
});
fixture.settle();
fixture.by_label("Font Size").expect("the combo box").rect.width()
};
let (ribbon, standard) = (width(true), width(false));
assert!(ribbon < standard / 2.0, "the ribbon's combo box fits two digits and its chevron: {ribbon} against {standard}");
}