ribbon-w3: net change of 6 commits

- ribbon-w3: written by an agent
- ribbon-w3: finished by an agent
- ribbon-w3: finished by an agent
- ribbon-w3: finished by an agent
- ribbon-w3: finished by an agent
- ribbon-w3: finished by an agent
This commit is contained in:
Martin Ball committed 2026-11-18 21:02:54 +00:00
1 parent 9dd16ce7ba
commit 8a045594dd
22 files changed
+1138 -57

No files matched your search

+286 -26
View File
@@ -3,24 +3,42 @@
mod gallery;
mod group;
mod plan;
#[cfg(feature = "screen-testing")]
mod stories;
use std::borrow::Cow;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;
use std::sync::Arc;
use craft_behavior::{CanvasTransform, EditEvent, IconId, Metrics, Mixed, SelectionChange, Sense, keyed};
use craft_keymap::CommandRef;
use craft_ui::contract::Bind;
use craft_ui::runtime::env::Label;
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Access, Bind, CollectionEvent, Common, Component, Container, ContainerProps, Cx, NoValue, Outcome, Props as _, Role, Scroll,
Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked, scroll_step,
};
use craft_ui::layout_components::Row;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::inspect;
use craft_ui::tabs::{StripEnd, TabRole};
use egui::{Id, Pos2, Rect, Ui};
use craft_ui::runtime::motion::{Animate as _, spec};
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::tabs::{StripEnd, Tab, TabKind, TabRole, TabStrip, TabStripOutput};
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;
pub use plan::{GroupWidths, plan};
craft_ui::words! {
/// The words of the ribbon's own controls.
struct RibbonWords {
scroll_left: "ribbon.scrollLeft" = "Scroll left";
scroll_right: "ribbon.scrollRight" = "Scroll right";
}
}
/// The ribbon: a [`TabKind::Ribbon`](craft_ui::tabs::TabKind) strip over a scrolling group row,
/// with minimise and context requests. The strip and the row show inside one inspected region
/// (`inspect::record`), whose record ([`RibbonOutput::controls`]) gives each control's rect and
@@ -28,58 +46,213 @@ pub use plan::{GroupWidths, plan};
/// relative to the old one (mirrored in right-to-left), through one `Tween`; with reduce motion the
/// new content shows at rest.
#[must_use = "show the ribbon with `show`"]
#[derive(craft_ui::contract::Pattern)]
#[pattern(probe(Ribbon<'static, usize>))]
pub struct Ribbon<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> {
stub: PhantomData<(&'a (), T)>,
label: Label,
tabs: &'a [RibbonTab<T>],
shown: Bind<'a, T>,
trailing: &'a [StripEnd<'a>],
minimised: Option<Bind<'a, bool>>,
}
impl<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> Ribbon<'a, T> {
/// A ribbon named `label` over `tabs`, showing the tab `shown` binds.
pub fn new(label: impl Into<Label>, tabs: &'a [RibbonTab<T>], shown: Bind<'a, T>) -> Self {
let _ = (label.into(), tabs, shown);
todo!("rb.R11")
Ribbon { label: label.into(), tabs, shown, trailing: &[], minimised: None }
}
/// Items at the end of the tab strip.
pub fn end(self, items: &'a [StripEnd<'a>]) -> Self {
let _ = (self, items);
todo!("rb.R11")
/// Items at the reading end of the tab strip, after the tabs.
pub fn trailing(mut self, items: &'a [StripEnd<'a>]) -> Self {
self.trailing = items;
self
}
/// Whether the group row is minimised, bound to the app's state.
pub fn minimised(self, minimised: Bind<'a, bool>) -> Self {
let _ = (self, minimised);
todo!("rb.R11")
/// Whether the group row is minimised, bound to the app's state. A double click on a tab toggles it through a
/// write-through binding.
pub fn minimised(mut self, minimised: Bind<'a, bool>) -> Self {
self.minimised = Some(minimised);
self
}
/// The key of the tab shown: the binding's, else the first tab's.
fn current(&mut self) -> Option<T> {
let bound = self.shown.reborrow().get().and_then(|value| value.same().cloned());
bound.or_else(|| self.tabs.first().map(|tab| tab.key.clone()))
}
/// Shows the strip and the group row of the shown tab; `body` fills the row for that tab.
pub fn show(self, ui: &mut Ui, body: impl FnMut(&mut RibbonRow<'_>, &T)) -> RibbonOutput<T> {
let _ = (self, ui, body);
todo!("rb.R11")
///
/// The tab a click picks comes back in [`RibbonOutput::shown`]; the app applies it to its own state. A request
/// the pass's input made (a context menu, a double click) is reported in the pass that received that input: the
/// framework records it in that pass's real run only, so a second pass of the frame reports none.
pub fn show(mut self, ui: &mut Ui, mut body: impl FnMut(&mut RibbonRow<'_>, &T)) -> RibbonOutput<T> {
let current = self.current();
let minimised = self.minimised.as_mut().and_then(|bind| bind.reborrow().get()).and_then(|value| value.same().copied()).unwrap_or(false);
let id = ui.id().with(self.label.as_str());
let tabs = self.tabs;
let trailing = self.trailing;
let strip_label = self.label.clone();
let label_of = |key: &T| tabs.iter().find(|tab| tab.key == *key).map_or(Label::Empty, |tab| tab.label.clone());
let role_of = |key: &T| tabs.iter().find(|tab| tab.key == *key).map_or(TabRole::Standard, |tab| tab.role);
let ((strip, region), controls) = inspect::record(ui, id, |ui| {
let strip: Option<TabStripOutput<T>> = (!tabs.is_empty()).then(|| {
let keys: Vec<T> = tabs.iter().map(|tab| tab.key.clone()).collect();
let source = keyed(&keys, |key: &T| key.clone()).with_text(|key: &T| Cow::Owned(label_of(key).as_str().to_owned()));
let strip: TabStrip<'_, T> = TabStrip::new(strip_label).kind(TabKind::Ribbon).roles(role_of);
// PLAN: `TabStrip::trailing(&[StripEnd])` is rb.R3 (ribbon-w1) and is not in this tree yet; this call compiles once it lands.
let mut strip = strip.trailing(trailing);
if let Some(key) = current.clone() {
strip = strip.shown(key);
}
strip.show_items(ui, &source, &mut |key: &T, _| Tab::new(label_of(key)).role(role_of(key)))
});
let region = match (&current, minimised) {
(Some(key), false) => Some(show_row(ui, id, tabs, key, &mut body)),
_ => None,
};
(strip, region)
});
let mut chosen: Option<T> = None;
let mut toggle = false;
let mut picked: Option<T> = None;
let mut menu: Option<RibbonMenuRequest> = None;
let mut strip_rect: Option<Rect> = None;
if let Some(strip) = strip {
for event in &strip.response.events {
match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => chosen = keys.last().cloned().or(chosen),
CollectionEvent::Activate(_) if strip.response.activation_clicks == 2 => toggle = true,
_ => {}
}
}
let response: &Response = &strip.response.response;
strip_rect = Some(response.rect);
picked = strip.picked;
menu = strip.menu.map(|request| RibbonMenuRequest { command: None, at: request.at, opener: response.id });
}
if toggle && let Some(bind) = self.minimised.as_mut() {
let _ = bind.reborrow().apply(&EditEvent::set(Mixed::Same(minimised), !minimised, Arc::from("ribbon.minimise"), None));
}
if let Some(request) = region.as_ref().and_then(|region| row_request(region, controls.as_deref())) {
menu = Some(request);
}
RibbonOutput { shown: chosen.or(current), picked, menu, controls, tabs: strip_rect }
}
}
/// Shows the group row of the tab `key` in the region that senses its context requests. The row slides in from the
/// side the tab lies on relative to the tab shown before, and a row wider than the room scrolls, with an edge chevron
/// on each side that has groups out of view.
fn show_row<T: Clone + Eq + Hash + Send + Sync + Debug + 'static>(
ui: &mut Ui,
base: Id,
tabs: &[RibbonTab<T>],
key: &T,
body: &mut impl FnMut(&mut RibbonRow<'_>, &T),
) -> RegionOutput {
let place = tabs.iter().position(|tab| tab.key == *key).unwrap_or(0) as f32;
Region::new()
.show(ui, |ui, cx| {
// The tab's place is the tween: it starts at the previous tab's place, which the motion's memory holds, and
// the gap to the target is how far the row still has to travel, on the side the new tab lies on. Under
// reduce motion the tween is at its target at once, so the row shows at rest.
let gap = place - cx.anim("place", place, spec::MOVE);
let side = if cx.env.direction().is_rtl() { -1.0 } else { 1.0 };
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);
// 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, _| {
let row = Row::new().scroll(Scroll::horizontal()).fill_width().show(ui, |ui, _| {
let mut row = RibbonRow { ui, base, groups: Vec::new() };
body(&mut row, key);
row.groups
});
(row.output.id, row.output.rect, row.inner.unwrap_or_default())
})
.inner;
if let Some((owner, view, groups)) = shown {
chevrons(ui, owner, view, &groups, chevron, lead);
}
})
.output
}
/// The edge chevrons of a row `view` whose `groups` do not all show: one at each edge that has a group past it, each
/// stepping the scrolling body `owner` by one group toward its side (`contract::scroll_step`). `view` and `groups` are
/// in the points of the row's layer, which the slide offsets by `lead`; the chevrons sit at the edges as they show.
/// `width` is a chevron's width.
fn chevrons(ui: &mut Ui, owner: Id, view: Rect, groups: &[Rect], width: f32, lead: f32) {
// Half a point past the edge counts as inside: less than a pixel shows at any scale.
let left = groups.iter().any(|group| group.min.x < view.min.x - 0.5);
let right = groups.iter().any(|group| group.max.x > view.max.x + 0.5);
let words = Env::of(ui).words::<RibbonWords>();
let edges = view.translate(vec2(lead, 0.0));
let size = Vec2::new(width, view.height());
for (on, right_side, icon, name) in
[(left, false, "chevron_left", words.scroll_left.clone()), (right, true, "chevron_right", words.scroll_right.clone())]
{
if !on {
continue;
}
let at = if right_side { Rect::from_min_size(Pos2::new(edges.max.x - width, edges.min.y), size) } else { Rect::from_min_size(edges.min, size) };
let button = IconButton::new(IconId::new(icon)).label(name).focusable(false).show_at(ui, at);
if clicked(&button.response) {
scroll_step(ui.ctx(), owner, view, groups, right_side);
}
}
}
/// The context request of the group row, from the framework's requests of this pass: the deepest control of the
/// ribbon's record with a bound command that asked (a secondary click on it, or the Menu key or Shift+F10 while it
/// held focus), else the region itself when its background asked. A request on a tab is the strip's.
fn row_request(region: &RegionOutput, recorded: Option<&inspect::Recorded>) -> Option<RibbonMenuRequest> {
let control = recorded.and_then(|recorded| {
region
.requests
.iter()
.filter_map(|(asked, rect)| {
recorded.elements.iter().find(|element| element.id == *asked && element.part.is_none() && element.command.is_some()).map(|element| (element, *rect))
})
.max_by_key(|(element, _)| element.depth)
});
match control {
Some((element, rect)) => Some(RibbonMenuRequest { command: element.command.clone(), at: rect.left_bottom(), opener: element.id }),
None => region.own.map(|rect| RibbonMenuRequest { command: None, at: rect.left_bottom(), opener: region.response.id }),
}
}
/// One tab of the ribbon.
pub struct RibbonTab<T> {
stub: PhantomData<(T, TabRole)>,
key: T,
label: Label,
role: TabRole,
}
impl<T> RibbonTab<T> {
/// A plain tab named `label` that `key` identifies.
pub fn new(key: T, label: impl Into<Label>) -> Self {
let _ = (key, label.into());
todo!("rb.R11")
RibbonTab { key, label: label.into(), role: TabRole::Standard }
}
/// Makes the tab a contextual one: it shows only while its context is on.
pub fn contextual(self) -> Self {
let _ = self;
todo!("rb.R11")
pub fn contextual(mut self) -> Self {
self.role = TabRole::Contextual;
self
}
}
/// The row of groups the ribbon's body fills for the shown tab.
pub struct RibbonRow<'a> {
stub: PhantomData<&'a mut Ui>,
ui: &'a mut Ui,
/// The ribbon's id: each group's id is made under it, so it stays the same in every sweep of the row.
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>,
}
/// What the ribbon reports for a pass.
@@ -105,3 +278,90 @@ pub struct RibbonMenuRequest {
/// The element the menu returns focus to.
pub opener: Id,
}
/// The style of the row's regions: the slide distance and the edge chevrons' width.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
struct RegionStyle {
#[style(metrics)]
metrics: Metrics,
/// How far the row travels as a tab change slides it in (`motion.slide`).
slide: f32,
/// The width of an edge chevron: a hit target's.
chevron: f32,
}
/// What a row region reports.
struct RegionOutput {
response: Response,
/// The region's own context request of this pass (a secondary click on its background), at this rect.
own: Option<Rect>,
/// Every context request of this pass made by the time the region finished, those of its controls among them.
requests: Vec<(Id, Rect)>,
}
impl Outcome for RegionOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
fn unshown(response: Response) -> Option<Self> {
Some(RegionOutput { response, own: None, requests: Vec::new() })
}
}
/// A region of the group row: the outer one takes the ribbon's width, senses secondary presses on its surface and
/// reports the context requests of its controls (`Cx::context_requests`); the inner one (`slide`) shows the row
/// through its offset while a tab change slides it in.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(container, unregistered)]
struct Region {
#[common]
common: Common,
#[container]
props: ContainerProps,
/// Whether the region senses context presses on its surface.
senses: bool,
}
impl Region {
/// The outer region.
fn new() -> Self {
Region { common: Common::new(), props: ContainerProps::new().sizing(Sizing::FillWidth), senses: true }
}
/// The inner region, its body offset by `lead` along x.
fn slide(lead: f32) -> Self {
let props = ContainerProps::new().sizing(Sizing::FillWidth).transform(CanvasTransform::new(1.0, vec2(lead, 0.0)));
Region { common: Common::new(), props, senses: false }
}
}
impl Component for Region {
const ROLE: Role = Role::GROUP;
const ALT_ROLES: &'static [Role] = &[Role::None];
type Style = RegionStyle;
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 }
}
fn sense(&self) -> Sense {
if self.senses { Sense::SURFACE | Sense::CONTEXT_CLICK } else { Sense::empty() }
}
/// The region only lays out the groups: it is no node of its own.
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
access.role(Role::None);
}
fn finish(self, cx: Cx<'_, Self>) -> RegionOutput {
let requests = if self.senses { cx.context_requests() } else { Vec::new() };
let own = requests.iter().find(|(asked, _)| *asked == cx.id).map(|(_, rect)| *rect);
RegionOutput { response: cx.response.clone(), own, requests }
}
}
impl Container for Region {}
+106 -14
View File
@@ -1,40 +1,132 @@
//! `RibbonGroup`: a titled group of controls in the ribbon's row.
use std::hash::Hash;
use std::marker::PhantomData;
use craft_behavior::IconId;
use craft_keymap::CommandRef;
use craft_ui::buttons::{Arrangement, Button, 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;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::popover::Popover;
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::Label;
use egui::Ui;
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 super::RibbonRow;
use super::{GroupLevel, RibbonRow};
craft_ui::words! {
/// The words of a ribbon group.
struct GroupWords {
launcher: template "ribbon.launcher" = "{title} settings";
}
}
/// The levels a group shows at, widest first: the order the row's levelled units report their widths in.
pub(super) const LEVELS: [GroupLevel; 3] = [GroupLevel::Full, GroupLevel::Compact, GroupLevel::Collapsed];
/// A group of the ribbon: a title, an icon for its collapsed form, and an optional launcher. Each
/// group sets its `GroupLevel` for its content; groups are access nodes (role group, named by
/// their title), and a collapsed group opens a popover.
pub struct RibbonGroup<'a> {
stub: PhantomData<&'a ()>,
/// The group's identity: it keeps levels apart where titles repeat.
key: u64,
title: Label,
icon: IconSpec<'a>,
launcher: Option<CommandRef>,
}
impl<'a> RibbonGroup<'a> {
/// A group identified by `key`, titled `title`, with `icon` on its collapsed button.
pub fn new(key: impl Hash, title: impl Into<Label>, icon: IconSpec<'a>) -> Self {
let _ = (key, title.into(), icon);
todo!("rb.R12")
RibbonGroup { key: key_salt(&key), title: title.into(), icon, launcher: None }
}
/// The command of the group's dialog launcher.
pub fn launcher(self, command: impl Into<CommandRef>) -> Self {
let _ = (self, command.into());
todo!("rb.R12")
pub fn launcher(mut self, command: impl Into<CommandRef>) -> Self {
self.launcher = Some(command.into());
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)) {
Stack::new().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| add(ui));
Row::new().show(ui, |ui, _| {
Text::new(self.title.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
if let Some(command) = &self.launcher {
let words = Env::of(ui).words::<GroupWords>();
let name = words.launcher.fill(&[("title", self.title.as_str())]);
IconButton::command(IconId::new("launcher"), command.clone()).label(name).show(ui);
}
});
});
}
/// One button with the group's icon and title; its popover holds the content at the full level. A press in a
/// popup the content opens does not close the popover: the overlay family keeps it open.
fn collapsed(&self, ui: &mut Ui, add: &mut dyn FnMut(&mut Ui)) {
let button = Button::new(self.title.clone()).icon(self.icon.clone()).arrangement(Arrangement::Stacked).show(ui);
Popover::new(self.title.clone(), Bind::kept()).overlay(|overlay| overlay.opened_by(&button.response, Trigger::Click)).show(ui, |ui, _| {
with_env(
ui,
|overrides| {
overrides.values.set(GroupLevel::Full);
},
|ui| {
Row::new().show(ui, |ui, _| add(ui));
},
);
});
}
/// 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()
.id(id)
.label(self.title.clone())
.show(ui, |ui, _| {
if level == GroupLevel::Collapsed {
self.collapsed(ui, add);
} else {
self.open(ui, add);
}
Divider::vertical().show(ui);
})
.output
.rect
}
}
impl RibbonRow<'_> {
/// Adds `group` to the row, fitting it by production's rule; `add` fills its content.
pub fn group(&mut self, group: RibbonGroup<'_>, add: impl FnMut(&mut Ui)) -> &mut Self {
let _ = (group, add);
todo!("rb.R12")
/// Adds `group` to the row, at the level the row's fit gives it; `add` fills its content.
///
/// The group is a levelled unit of the row (`layout::levelled_unit`): when the row measures (its room or its
/// content changed), it runs `add` once at each level to measure the group, and gives each group its level by
/// production's rule ([`plan`](super::plan)); a pass in which nothing the row measures changed shows each group
/// once, at its kept level. So `add` must be free of side effects in a measuring run, as every row body is: it
/// reads the outputs of the controls it shows, and the framework reports those in the real run only.
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;
levelled_unit(self.ui, id, LEVELS.len(), |ui, at| {
let level = LEVELS.get(at).copied().unwrap_or(GroupLevel::Collapsed);
let rect = with_env(
ui,
|overrides| {
overrides.values.set(level);
},
|ui| group.unit(ui, id, &mut add, level),
);
shown = Some(rect);
});
if let Some(rect) = shown {
self.groups.push(rect);
}
self
}
}
+8 -3
View File
@@ -1,6 +1,7 @@
//! The fit rule: how much of each group shows at each width.
use super::GroupLevel;
use super::group::LEVELS;
/// The widths of one group at each of its levels.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
@@ -13,8 +14,12 @@ pub struct GroupWidths {
pub collapsed: f32,
}
/// The level of each group for `available` width, by production's fit rule.
/// The level of each group for `available` width, by the rule of a row's levelled units
/// (`craft_ui::layout::plan_levels`), which the ribbon's row applies to its groups. Groups shrink from the end: first
/// each to compact, then each to collapsed, stopping as soon as the row fits. Then, from the start, each group takes
/// back a level while the row still fits: shrinking a wide group can free room an earlier group no longer needed to
/// give up. A width that is not a number never fits, so it gives nothing back.
pub fn plan(widths: &[GroupWidths], available: f32) -> Vec<GroupLevel> {
let _ = (widths, available);
todo!("rb.R12")
let units: Vec<Vec<f32>> = widths.iter().map(|group| vec![group.full, group.compact, group.collapsed]).collect();
craft_ui::layout::plan_levels(&units, available).into_iter().map(|at| LEVELS.get(at).copied().unwrap_or(GroupLevel::Collapsed)).collect()
}
+149
View File
@@ -0,0 +1,149 @@
//! Stories of the ribbon over a small model: three tabs of four groups each.
use craft_behavior::IconId;
use craft_keymap::CommandRef;
use craft_ui::buttons::{Arrangement, Button};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::env::{Direction, Env, with_env};
use craft_ui::tabs::StripEnd;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use egui::Ui;
use super::{Ribbon, RibbonGroup, RibbonRow, RibbonTab};
/// The group titles of each tab.
const GROUPS: [[&str; 4]; 3] =
[["Clipboard", "Font", "Paragraph", "Styles"], ["Pages", "Tables", "Illustrations", "Links"], ["Views", "Show", "Zoom", "Window"]];
/// The buttons of every group.
const BUTTONS: [&str; 3] = ["Large action", "Another action", "Third action"];
/// The widths the stories hold the ribbon to: the groups' compact form, their collapsed form, and a row that
/// scrolls even with every group collapsed.
const COMPACT_ROOM: f32 = 640.0;
const COLLAPSED_ROOM: f32 = 380.0;
const SCROLLED_ROOM: f32 = 160.0;
/// What a story changes about the ribbon.
#[derive(Clone, Copy, Default)]
struct Setup {
/// The width the ribbon is held to; its natural width without one.
room: Option<f32>,
/// The ribbon starts minimised.
minimised: bool,
/// A contextual tab shows after the plain ones.
contextual: bool,
/// An item shows at the end of the strip.
end: bool,
/// The ribbon reads right to left.
rtl: bool,
}
/// The groups of `tab`.
fn groups(row: &mut RibbonRow<'_>, tab: &usize) {
for (at, title) in GROUPS[*tab % GROUPS.len()].iter().enumerate() {
let icon = IconId::new("list");
row.group(RibbonGroup::new((*tab, at), *title, icon.into()), |ui| {
for label in BUTTONS {
Button::new(label).icon(IconId::new("list")).arrangement(Arrangement::Stacked).show(ui);
}
});
}
}
/// Shows the ribbon as `setup` says and applies the tab it reports.
fn show(ui: &mut Ui, data: &mut StoryData, setup: Setup) -> StoryOutput {
let shown = data.value("shown", 0_usize);
let mut tabs = vec![RibbonTab::new(0_usize, "Home"), RibbonTab::new(1, "Insert"), RibbonTab::new(2, "View")];
if setup.contextual {
tabs.push(RibbonTab::new(3, "Picture").contextual());
}
let items = [StripEnd::command("Share", IconId::new("link").into(), CommandRef::new("ribbon.share"))];
let mut ribbon = Ribbon::new("Ribbon", &tabs, Bind::given(*shown));
if setup.end {
ribbon = ribbon.trailing(&items);
}
if setup.minimised {
ribbon = ribbon.minimised(Bind::given(true));
}
let direction = if setup.rtl { Direction::Rtl } else { Env::of(ui).direction };
let out = with_env(
ui,
|overrides| {
overrides.direction = Some(direction);
},
|ui| match setup.room {
Some(room) => craft_ui::testing::memory::scoped(ui, |ui| {
ui.set_max_width(room);
ribbon.show(ui, groups)
}),
None => ribbon.show(ui, groups),
},
);
if let Some(next) = out.shown {
*shown = next;
}
StoryOutput::default()
}
#[story(Ribbon<'static, usize>, covers = [Default], drive = Drive::Never)]
fn ribbon(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup::default())
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Never)]
fn ribbon_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { room: Some(COMPACT_ROOM), ..Setup::default() })
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Never)]
fn ribbon_collapsed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { room: Some(COLLAPSED_ROOM), ..Setup::default() })
}
fn open_group(fixture: &mut Fixture) {
if let Some(group) = fixture.by_label(GROUPS[0][0]) {
fixture.click(&group);
}
}
#[story(Ribbon<'static, usize>, covers = [Open], drive = Drive::Custom(open_group))]
fn ribbon_collapsed_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { room: Some(COLLAPSED_ROOM), ..Setup::default() })
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Never)]
fn ribbon_scrolled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { room: Some(SCROLLED_ROOM), ..Setup::default() })
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Never)]
fn ribbon_rtl(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { room: Some(COMPACT_ROOM), rtl: true, ..Setup::default() })
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Never)]
fn ribbon_minimised(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { minimised: true, ..Setup::default() })
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Never)]
fn ribbon_contextual_tab(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { contextual: true, ..Setup::default() })
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Never)]
fn ribbon_end_items_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { room: Some(SCROLLED_ROOM), end: true, ..Setup::default() })
}
fn pick_last_tab(fixture: &mut Fixture) {
if let Some(tab) = fixture.by_label("View") {
fixture.click(&tab);
}
}
#[story(Ribbon<'static, usize>, covers = [], drive = Drive::Custom(pick_last_tab))]
fn ribbon_tab_change(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup::default())
}
+3
View File
@@ -1,8 +1,11 @@
//! The integration binary of craft-menu: every test is a registered trial.
mod keytips;
mod layout;
mod mnemonic;
mod native;
mod ribbon;
mod ribbon_gallery;
mod sample;
mod shortcuts;
+329
View File
@@ -0,0 +1,329 @@
//! The ribbon: the fit rule, keyed group levels, a collapsed group's popover, the tab-change slide and the run model.
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use craft_behavior::{IconId, MotionMode};
use craft_keymap::CommandRef;
use craft_menu::{GroupLevel, GroupWidths, Ribbon, RibbonGroup, RibbonRow, RibbonTab, plan};
use craft_ui::buttons::{Arrangement, Button, SplitButton};
use craft_ui::contract::{Bind, Entry, Props as _, Show as _};
use craft_ui::runtime::env::{Direction, Env};
use craft_ui::testing::{Fixture, is_measuring, last_pass_measuring_runs, trial};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2};
/// How collapsed a level is: 0 full, 1 compact, 2 collapsed.
fn rank(level: GroupLevel) -> u8 {
match level {
GroupLevel::Full => 0,
GroupLevel::Compact => 1,
_ => 2,
}
}
/// The width of `group` at `level`.
fn width_at(group: &GroupWidths, level: GroupLevel) -> f32 {
match rank(level) {
0 => group.full,
1 => group.compact,
_ => group.collapsed,
}
}
/// The width of the row with each group at its level.
fn total(widths: &[GroupWidths], levels: &[GroupLevel]) -> f32 {
widths.iter().zip(levels).map(|(group, level)| width_at(group, *level)).sum()
}
/// The width of `group` one level wider than `level`.
fn wider(group: &GroupWidths, level: GroupLevel) -> f32 {
if rank(level) == 2 { group.compact } else { group.full }
}
/// The fit shrinks the groups from the end, first to compact and then to collapsed, stopping as soon as the row
/// fits, and then gives a level back from the start while the row still fits.
#[trial]
fn the_plan_compacts_then_collapses_from_the_end_and_gives_back_from_the_start() {
let even = [GroupWidths { full: 100.0, compact: 80.0, collapsed: 40.0 }; 4];
let mut last_collapsed = 0;
for available in (0..=40).rev().map(|step| step as f32 * 10.0) {
let levels = plan(&even, available);
let collapsed: u8 = levels.iter().map(|level| rank(*level)).sum();
assert!(collapsed >= last_collapsed, "a narrower row never shows more of a group ({available})");
last_collapsed = collapsed;
if available >= 160.0 {
assert!(total(&even, &levels) <= available, "the row fits whenever it can ({available})");
} else {
assert!(levels.iter().all(|level| rank(*level) == 2), "a row nothing fits in shows every group collapsed ({available})");
}
assert!(levels.windows(2).all(|pair| rank(pair[0]) <= rank(pair[1])), "the groups at the end give up first ({available}): {levels:?}");
for (group, level) in even.iter().zip(&levels) {
if rank(*level) > 0 {
let given_back = total(&even, &levels) - width_at(group, *level) + wider(group, *level);
assert!(given_back > available, "nothing more can be given back ({available})");
}
}
}
let roomy = plan(&even, 400.0);
assert!(roomy.iter().all(|level| rank(*level) == 0), "a row that fits shows every group in full");
// A wide group that shrinks frees room: the groups the shrinking passed over give back what they gave up.
let uneven = [
GroupWidths { full: 300.0, compact: 250.0, collapsed: 60.0 },
GroupWidths { full: 500.0, compact: 500.0, collapsed: 60.0 },
GroupWidths { full: 60.0, compact: 60.0, collapsed: 60.0 },
GroupWidths { full: 60.0, compact: 60.0, collapsed: 60.0 },
];
let levels = plan(&uneven, 800.0);
assert!(total(&uneven, &levels) <= 800.0, "the row fits");
assert_eq!(levels.iter().map(|level| rank(*level)).collect::<Vec<_>>(), vec![0, 2, 0, 0], "only the wide group stays collapsed");
}
/// A group named `title` whose content is `labels` as stacked buttons.
fn group(row: &mut RibbonRow<'_>, key: &'static str, title: &'static str, labels: &[&'static str]) {
row.group(RibbonGroup::new(key, title, IconId::new("list").into()), |ui| {
for label in labels {
Button::new(*label).arrangement(Arrangement::Stacked).show(ui);
}
});
}
const WIDE: [&str; 12] = ["Alpha1", "Alpha2", "Alpha3", "Alpha4", "Alpha5", "Alpha6", "Alpha7", "Alpha8", "Alpha9", "Alpha10", "Alpha11", "Alpha12"];
/// Two groups with one title, shown in either order, each keep their own level: the wide one collapses, the narrow
/// one stays whole, and re-ordering does not swap them.
#[trial]
fn groups_with_the_same_title_keep_their_own_level() {
let swapped = Rc::new(Cell::new(false));
let flag = swapped.clone();
let mut fixture = Fixture::new(move |ui| {
let tabs = [RibbonTab::new(0_usize, "Home")];
let _ = Ribbon::new("Ribbon", &tabs, Bind::given(0_usize)).show(ui, |row, _| {
if flag.get() {
group(row, "narrow", "Group", &["Only"]);
group(row, "wide", "Group", &WIDE);
} else {
group(row, "wide", "Group", &WIDE);
group(row, "narrow", "Group", &["Only"]);
}
});
});
fixture.room(vec2(420.0, 300.0));
fixture.settle();
assert!(fixture.by_label("Alpha1").is_none(), "the wide group is collapsed");
assert!(fixture.by_label("Only").is_some(), "the narrow group of the same title stays whole");
swapped.set(true);
fixture.settle();
assert!(fixture.by_label("Alpha1").is_none(), "the wide group stays collapsed after the groups swap places");
assert!(fixture.by_label("Only").is_some(), "the narrow group stays whole after the groups swap places");
}
/// A collapsed group opens a popover; a menu opened from a split button inside it and a pick from that menu leave
/// the popover open, and a press outside closes it.
#[trial]
fn a_collapsed_groups_popover_stays_open_while_a_child_popup_is_used() {
let picked: Rc<RefCell<Vec<usize>>> = Rc::new(RefCell::new(Vec::new()));
let seen = picked.clone();
let mut fixture = Fixture::new(move |ui| {
let tabs = [RibbonTab::new(0_usize, "Home")];
let entries = [Entry::new(1_usize, "Keep text only"), Entry::new(2, "Paste values")];
let _ = Ribbon::new("Ribbon", &tabs, Bind::given(0_usize)).show(ui, |row, _| {
row.group(RibbonGroup::new("clip", "Clipboard", IconId::new("list").into()), |ui| {
if let Some(entry) = SplitButton::new("Paste", &entries).show(ui).chosen {
seen.borrow_mut().push(entry);
}
});
group(row, "wide", "Wide", &WIDE);
});
});
fixture.room(vec2(260.0, 300.0));
fixture.settle();
assert!(fixture.by_label("Paste").is_none(), "the group is collapsed");
let button = fixture.by_label("Clipboard").expect("the collapsed group's button");
fixture.click(&button).idle(3);
assert!(fixture.by_label("Paste").is_some(), "the button opens the group's popover");
fixture.key(Key::ArrowDown, Modifiers::ALT).idle(3);
fixture.key(Key::Enter, Modifiers::NONE).idle(3);
assert_eq!(picked.borrow().clone(), vec![1], "the split button's menu picked its first row");
assert!(fixture.by_label("Paste").is_some(), "the group's popover is still open after a pick from a menu opened inside it");
fixture.click_at(Pos2::new(255.0, 295.0)).idle(3);
assert!(fixture.by_label("Paste").is_none(), "a press outside closes the popover");
}
/// The painted x of the group titled `title`, once the fixture has run a frame.
fn group_x(fixture: &Fixture, title: &str) -> f32 {
fixture.by_label(title).map_or(f32::NAN, |target| target.rect.left())
}
/// A ribbon of three tabs with one group each, showing the tab `shown` holds.
fn slide_rig(shown: &Rc<Cell<usize>>, direction: Direction, motion: MotionMode) -> Fixture {
let state = shown.clone();
let mut fixture = Fixture::new(move |ui| {
let tabs = [RibbonTab::new(0_usize, "One"), RibbonTab::new(1, "Two"), RibbonTab::new(2, "Three")];
let out = Ribbon::new("Ribbon", &tabs, Bind::given(state.get())).show(ui, |row, tab| match tab {
0 => group(row, "a", "Alpha", &["First"]),
1 => group(row, "b", "Beta", &["Second"]),
_ => group(row, "c", "Gamma", &["Third"]),
});
if let Some(next) = out.shown {
state.set(next);
}
});
fixture.direction(direction).motion(motion).room(vec2(600.0, 300.0));
fixture.settle();
fixture
}
/// The x of the group of tab `to` on the first frame it shows after a click on its tab while tab `from` showed, and
/// at rest. The click's release reports the tab through `RibbonOutput::shown`; the rig applies it, so the frame after
/// the release (the click's idle frame) is the first that shows the new row.
fn slide(direction: Direction, motion: MotionMode, from: usize, to: usize) -> (f32, f32) {
let shown = Rc::new(Cell::new(from));
let mut fixture = slide_rig(&shown, direction, motion);
let tab = fixture.by_label(["One", "Two", "Three"][to]).expect("the tab to change to");
fixture.click(&tab);
assert_eq!(shown.get(), to, "the click on the tab showed it");
let title = ["Alpha", "Beta", "Gamma"][to];
let first = group_x(&fixture, title);
fixture.idle(120);
(first, group_x(&fixture, title))
}
/// A tab change slides the new group row in from the side of the new tab (mirrored in right-to-left) and reaches
/// rest; with reduced motion the row is at rest on the first frame.
#[trial]
fn a_tab_change_slides_the_row_in_from_the_new_tabs_side_and_shows_at_rest_under_reduced_motion() {
let (first, rest) = slide(Direction::Ltr, MotionMode::Full, 0, 2);
assert!(first > rest + 1.0, "a later tab's row starts toward the end side: {first} vs {rest}");
let (first, rest) = slide(Direction::Ltr, MotionMode::Full, 2, 0);
assert!(first < rest - 1.0, "an earlier tab's row starts toward the start side: {first} vs {rest}");
let (first, rest) = slide(Direction::Rtl, MotionMode::Full, 0, 2);
assert!(first < rest - 1.0, "under right-to-left the sides mirror: {first} vs {rest}");
let (first, rest) = slide(Direction::Rtl, MotionMode::Full, 2, 0);
assert!(first > rest + 1.0, "under right-to-left the sides mirror: {first} vs {rest}");
let (first, rest) = slide(Direction::Ltr, MotionMode::Reduced, 0, 2);
assert!((first - rest).abs() < 0.5, "with reduced motion the row shows at rest at once: {first} vs {rest}");
}
/// What each group's content did, by the group's key: how many times it ran in a measuring run since the counts were
/// cleared, and the level its last real run showed it at.
type Runs = Rc<RefCell<HashMap<&'static str, (u32, GroupLevel)>>>;
/// A group like [`group`] whose content counts its runs in `runs`.
fn counted(row: &mut RibbonRow<'_>, runs: &Runs, key: &'static str, labels: [&'static str; 2]) {
let runs = runs.clone();
row.group(RibbonGroup::new(key, key, IconId::new("list").into()), move |ui| {
let level = Env::of(ui).get::<GroupLevel>();
let measuring = is_measuring(ui.ctx());
let mut runs = runs.borrow_mut();
let entry = runs.entry(key).or_insert((0, level));
if measuring {
entry.0 += 1;
} else {
entry.1 = level;
}
for label in labels {
Button::new(label).arrangement(Arrangement::Stacked).show(ui);
}
});
}
/// The measuring runs of `key`'s content since the counts were cleared.
fn measured(runs: &Runs, key: &str) -> u32 {
runs.borrow().get(key).map_or(0, |(count, _)| *count)
}
/// The level `key`'s group last showed at.
fn level(runs: &Runs, key: &str) -> GroupLevel {
runs.borrow().get(key).map_or(GroupLevel::Full, |(_, level)| *level)
}
/// Clears the measuring counts, keeping the levels.
fn clear(runs: &Runs) {
for (count, _) in runs.borrow_mut().values_mut() {
*count = 0;
}
}
const KEYS: [&str; 4] = ["one", "two", "three", "four"];
/// Count trial of the run model: a settled ribbon runs no group's content in a measuring run (each shows once, at its
/// kept level), and narrowing the room until one group changes level runs only that group's content to measure it.
#[trial]
fn a_settled_ribbon_runs_no_group_body_again_and_a_level_change_runs_only_that_group() {
let runs: Runs = Rc::new(RefCell::new(HashMap::new()));
let seen = runs.clone();
let mut fixture = Fixture::new(move |ui| {
let tabs = [RibbonTab::new(0_usize, "Home")];
let _ = Ribbon::new("Ribbon", &tabs, Bind::given(0_usize)).show(ui, |row, _| {
counted(row, &seen, "one", ["Alpha", "Beta"]);
counted(row, &seen, "two", ["Gamma", "Delta"]);
counted(row, &seen, "three", ["Epsilon", "Zeta"]);
counted(row, &seen, "four", ["Eta", "Theta"]);
});
});
let mut room = 900.0;
fixture.room(vec2(room, 300.0));
fixture.settle();
assert!(KEYS.iter().all(|key| level(&runs, key) == GroupLevel::Full), "every group shows in full in a wide room");
clear(&runs);
fixture.idle(1);
assert!(KEYS.iter().all(|key| measured(&runs, key) == 0), "a pass with unchanged inputs measures no group: {:?}", runs.borrow());
assert!(last_pass_measuring_runs(fixture.ctx()).is_empty(), "a pass with unchanged inputs runs no measuring run");
// Narrow the room a step at a time until a group changes level; the fit gives way from the end, so it is the last.
loop {
room -= 10.0;
assert!(room > 100.0, "narrowing the room changes some group's level");
clear(&runs);
fixture.room(vec2(room, 300.0));
fixture.idle(1);
if level(&runs, "four") != GroupLevel::Full {
break;
}
}
assert!(KEYS[..3].iter().all(|key| level(&runs, key) == GroupLevel::Full), "only the last group gave way");
assert!(measured(&runs, "four") > 0, "the group that changed level ran its content to measure it");
assert!(
KEYS[..3].iter().all(|key| measured(&runs, key) == 0),
"the groups that kept their level ran no content to measure: {:?}",
runs.borrow()
);
}
/// 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 };
fixture.frame(vec![Event::PointerMoved(at), button(true)]);
fixture.frame(vec![button(false)]);
fixture.idle(1);
}
/// A right click on a ribbon control reaches the row's region, which asks for the menu with the control's bound
/// command and returns focus to it; a right click on a tab asks for the tab's menu, with no command.
#[trial]
fn a_right_click_on_a_control_asks_for_its_menu_with_its_command() {
let menus: Rc<RefCell<Vec<Option<CommandRef>>>> = Rc::new(RefCell::new(Vec::new()));
let seen = menus.clone();
let mut fixture = Fixture::new(move |ui| {
let tabs = [RibbonTab::new(0_usize, "Home"), RibbonTab::new(1, "Insert")];
let out = Ribbon::new("Ribbon", &tabs, Bind::given(0_usize)).show(ui, |row, _| {
row.group(RibbonGroup::new("clip", "Clipboard", IconId::new("list").into()), |ui| {
Button::new("Paste").command(CommandRef::new("edit.paste")).arrangement(Arrangement::Stacked).show(ui);
});
});
if let Some(menu) = out.menu {
seen.borrow_mut().push(menu.command);
}
});
fixture.room(vec2(600.0, 300.0));
fixture.settle();
let paste = fixture.by_label("Paste").expect("the control");
right_click(&mut fixture, paste.rect.center());
assert_eq!(menus.borrow().clone(), vec![Some(CommandRef::new("edit.paste"))], "the control's request carries its command");
menus.borrow_mut().clear();
let tab = fixture.by_label("Insert").expect("a tab");
right_click(&mut fixture, tab.rect.center());
assert_eq!(menus.borrow().clone(), vec![None], "a tab's request carries no command");
}
+3 -1
View File
@@ -266,7 +266,9 @@ fn easing(e: Easing) -> &'static str {
}
fn motion_lines(out: &mut Lines, m: &MotionTokens) {
let MotionTokens { hover, open, r#move, caret, outline, reduced } = m;
// PLAN: `motion.slide` is not dumped: a dump line changes every golden file under `tests/dumps/tokens`, which need
// regenerating with the line `out.line("motion.slide", slide)` added below; owner: the lead (a blessed rerun).
let MotionTokens { hover, open, r#move, caret, outline, slide: _, reduced } = m;
for (k, motion) in [("hover", hover), ("open", open), ("move", r#move), ("caret", caret), ("outline", outline)] {
let Motion { millis, easing: e } = motion;
out.line(&format!("motion.{k}.millis"), millis);
+1
View File
@@ -219,6 +219,7 @@ fn resolve_concrete(theme: &ThemeDef, appearance: Appearance, app: Option<&AppId
r#move: motion(move_),
caret: motion_ms(values::MOTION_CARET_MS, values::MOTION_CARET_EASING),
outline: motion_ms(values::MOTION_OUTLINE_MS, values::MOTION_OUTLINE_EASING),
slide: values::MOTION_SLIDE_PT,
reduced: appearance.reduced_motion,
},
};
+4
View File
@@ -138,6 +138,10 @@ pub struct MotionTokens {
pub caret: Motion,
/// A selection outline gliding to its new cells (`motion.outline`).
pub outline: Motion,
/// How far content that a switch brings in (a ribbon's group row on a tab change) travels as it slides into place,
/// in whole points (`motion.slide`). Whole points keep the group `Eq` and `Hash`; reduced motion zeroes the time,
/// not the distance.
pub slide: u32,
/// The appearance asks for reduced motion: every duration above is zero.
pub reduced: bool,
}
+3
View File
@@ -481,3 +481,6 @@ pub const MOTION_OUTLINE_MS: u32 = 120;
/// Easing of a selection outline's glide. GridCraft's `ease_out` is `1 - (1 - t)^3` (0.875 at the
/// half way); `Standard` reaches 0.878 there and is the closest of the three curves.
pub const MOTION_OUTLINE_EASING: Easing = Easing::Standard;
/// How far switched content slides in, in points (WordCraft's ribbon `CONTENT_SWITCH_SLIDE`, 14 points).
pub const MOTION_SLIDE_PT: u32 = 14;
@@ -284,6 +284,14 @@ impl<C: Component> Cx<'_, C> {
crate::runtime::keys::context_request(&self.core.ctx, self.core.id).is_some()
}
/// The context requests made in this pass so far, in order: each component asked and the rect its menu opens at
/// (its part's, when it was made at one). A container reads in `finish` those its body's components made, which
/// ran before it finished: a secondary click or the Menu key on a child reaches the region around it this way,
/// whatever the child does with its own request.
pub fn context_requests(&self) -> Vec<(Id, Rect)> {
crate::runtime::keys::context_requests(&self.core.ctx)
}
/// Names the member of this container's roving group (`ContainerProps.roving`) that Tab arrives at; the
/// first member when none is named.
pub fn roving_arrival(&mut self, member: Id) {
+1
View File
@@ -124,6 +124,7 @@ pub(crate) use run::measure_under;
#[cfg(feature = "testing")]
pub(crate) use steps::queue_reveal;
pub(crate) use steps::{child_reveal, peek_reveal, queue_child_reveal, take_reveal};
pub use steps::scroll_step;
pub(crate) use steps::{draft, keeping_ids};
/// Adds the runtime to `ctx`: `runtime::install` with the overlay host's ghost-layer painter in the end hook.
+1
View File
@@ -37,6 +37,7 @@ pub(crate) use report::{ReportIn, report, report_inert, report_parts, validity_o
#[cfg(feature = "testing")]
pub(crate) use scroll_owner::queue_reveal;
pub(crate) use scroll_owner::{child_reveal, peek_reveal, queue_child_reveal, reveal_move, scroll_moves, take_reveal};
pub use scroll_owner::scroll_step;
pub(crate) use sense::{part_state, register_wheel};
pub(crate) use settle::settle;
pub(crate) use state::{register_reset, state, value_flags};
@@ -58,6 +58,24 @@ pub(crate) fn take_reveal(ctx: &Context, owner: Id) -> Option<Rect> {
})
}
/// Steps the scrolling body `owner` by one of its units: toward the right of the screen (`right`) or the left. `view`
/// is the rect the body shows this pass and `units` the rects of the units its content is made of (a ribbon's groups),
/// in any order. The step brings the nearest unit that lies past the view's edge on that side whole into view, by the
/// least move that shows it, at the owner's next pass, as a reveal does. Returns whether there was such a unit: at the
/// end of the content nothing moves. Half a point past the edge counts as inside: less than a pixel shows at any scale.
pub fn scroll_step(ctx: &Context, owner: Id, view: Rect, units: &[Rect], right: bool) -> bool {
let past = |unit: &&Rect| if right { unit.max.x > view.max.x + 0.5 } else { unit.min.x < view.min.x - 0.5 };
let nearest = if right {
units.iter().filter(past).min_by(|a, b| a.min.x.total_cmp(&b.min.x))
} else {
units.iter().filter(past).max_by(|a, b| a.max.x.total_cmp(&b.max.x))
};
let Some(unit) = nearest else { return false };
pass_state::with::<Reveals, _>(ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(*unit) }));
repaint::request(ctx);
true
}
/// Queues a reveal request for `owner`.
#[cfg(feature = "testing")]
pub(crate) fn queue_reveal(ctx: &Context, owner: Id, rect: Rect) {
+133 -9
View File
@@ -250,7 +250,8 @@ pub(crate) fn counting_fills(ui: &Ui, axis: Axis) -> bool {
/// What a unit of a shrinking row reported in the first sweep: its id, the width it took there, the width it asks for
/// in no room, the least at which its content shows whole and the least it shrinks to, and whether its content is
/// made to be cut (`Component::cut_first`). A body unit reports what it took as all three; the row asks it for its
/// least (`Shrink::Least`) only when the row is short.
/// least (`Shrink::Least`) only when the row is short. A levelled unit (`levelled_unit`) reports its width at each of
/// its levels, widest first, in `levels`; a continuous unit leaves it empty.
struct Reported {
leaf: Id,
took: f32,
@@ -258,6 +259,7 @@ struct Reported {
whole: f32,
body: bool,
cut_first: bool,
levels: Vec<f32>,
}
/// The widths of a unit of a row that shrinks to fit: the width it asks for and the least it narrows to.
@@ -290,10 +292,114 @@ pub(crate) struct LeastReports(IdMap<IdMap<f32>>);
pub(crate) fn report_shrink(ctx: &egui::Context, row: Id, leaf: Id, took: f32, ideal: f32, whole_least: Option<(f32, f32)>, cut_first: bool) {
let (whole, least) = whole_least.map_or((ideal, ideal), |(whole, least)| (whole.min(ideal), least.min(ideal)));
let widths = ShrinkUnit { ideal, least: least.min(whole) };
let leaf = Reported { leaf, took, widths, whole, body: whole_least.is_none(), cut_first };
let leaf = Reported { leaf, took, widths, whole, body: whole_least.is_none(), cut_first, levels: Vec::new() };
pass_state::with::<ShrinkReports, _>(ctx, |reports| reports.0.entry(row).or_default().push(leaf));
}
/// Reports the widths of the levelled unit `unit` of the row `row` that counts them, one per level, widest first. The
/// unit took the first (widest) in the counting sweep.
fn report_levels(ctx: &egui::Context, row: Id, unit: Id, levels: Vec<f32>) {
let ideal = levels.first().copied().unwrap_or_default();
let least = levels.last().copied().unwrap_or_default().min(ideal);
let leaf = Reported { leaf: unit, took: ideal, widths: ShrinkUnit { ideal, least }, whole: ideal, body: false, cut_first: false, levels };
pass_state::with::<ShrinkReports, _>(ctx, |reports| reports.0.entry(row).or_default().push(leaf));
}
/// The level of each unit of a row whose units show in discrete levels, for `room`. `units` holds each unit's width
/// at each of its levels, widest (level 0) first. The units give way from the end: first each steps down to its level
/// 1, then each to its level 2, and so on, stopping as soon as the row fits. Then, from the start, each unit takes back
/// a level while the row still fits: stepping a wide unit down can free room an earlier unit no longer needed to give
/// up. A unit with fewer levels stays at its last. A width that is not a number never fits, so it gives nothing back.
///
/// Worked through for units `[300, 250, 60]`, `[500, 500, 60]`, `[60]`, `[60]` in 800: the total 920 does not fit;
/// stepping to level 1 from the end leaves 870, still too wide; stepping to level 2 from the end reaches the second
/// unit (60), and the row fits at 430. Giving back from the start: the first unit takes level 0 (480); the second
/// cannot (920 > 800). The levels are `[0, 2, 0, 0]`.
pub fn plan_levels(units: &[Vec<f32>], room: f32) -> Vec<usize> {
let width = |unit: &[f32], level: usize| unit.get(level).or(unit.last()).copied().unwrap_or_default();
let deepest = units.iter().map(|unit| unit.len().saturating_sub(1)).max().unwrap_or_default();
let mut levels = vec![0; units.len()];
let mut total: f32 = units.iter().map(|unit| width(unit, 0)).sum();
for target in 1..=deepest {
for (unit, level) in units.iter().zip(levels.iter_mut()).rev() {
if total <= room {
break;
}
if target < unit.len() {
total += width(unit, target) - width(unit, *level);
*level = target;
}
}
}
for (unit, level) in units.iter().zip(levels.iter_mut()) {
while *level > 0 {
let next = total + width(unit, *level - 1) - width(unit, *level);
if !next.is_finite() || next > room {
break;
}
total = next;
*level -= 1;
}
}
levels
}
/// Shows `show`, one unit of the unwrapped `Row` body around it that fits in discrete levels (a ribbon group: full,
/// compact, collapsed), at the level the row's shrink step gave it. `levels` is how many levels the unit has; `show`
/// shows it at a level from 0 (the widest) to `levels - 1`, and must be free of side effects in a measuring run, as
/// every row body is: the row's counting sweep runs it once per level to measure each, in an invisible sizing pass.
/// `key` names the unit within its row and stays the same in every pass.
///
/// The row gives its levelled units their levels before its continuous units narrow (`plan_levels`, in the room the
/// continuous units leave at their least), and the continuous units narrow by their own rule in what is left. The level
/// is kept with the row's measuring run, so a pass without one (nothing the row measures changed) shows each unit once,
/// at its kept level. Outside a shrinking row the unit shows at level 0.
pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(&mut Ui, usize)) {
let ctx = ui.ctx().clone();
let shrink = Env::of(ui).shrink;
// The unit's content is no unit of the row: it runs in a room of its own.
let own_room = Env::of(ui).derive_local(|scoped| scoped.start_room());
match shrink {
Some(Shrink::Count(row)) => {
let rtl = Env::of(ui).direction.is_rtl();
let mut widths = Vec::with_capacity(levels);
let mut widest = Vec2::ZERO;
for level in 0..levels.max(1) {
let installed = Env::install_for(ui, own_room.clone());
let (_, took) = crate::runtime::egui::sizing::run_sized(ui, f32::INFINITY, child::column_layout(rtl), |ui| show(ui, level));
Env::restore(&ctx, installed);
if level == 0 {
widest = took;
}
widths.push(took.x);
}
// The counting sweep places the unit at its widest; the row sweeps again at the levels it gives.
alloc::space(ui, widest);
report_levels(&ctx, row, key, widths);
}
// The probe for the leasts of body units asks nothing of a levelled unit: its least is its last level.
Some(Shrink::Least(_)) => {}
Some(Shrink::Apply(row)) => {
let level = level_of(&ctx, row, key).min(levels.saturating_sub(1));
let installed = Env::install_for(ui, own_room);
show(ui, level);
Env::restore(&ctx, installed);
}
Some(Shrink::Fit) | None => {
let installed = Env::install_for(ui, own_room);
show(ui, 0);
Env::restore(&ctx, installed);
}
}
}
/// The level the shrink step of the row `row` gave its levelled unit `unit`: 0 without a record. The record keeps the
/// level as the measure's height, which a row's shrink record has no other use for.
fn level_of(ctx: &egui::Context, row: Id, unit: Id) -> usize {
// A level is a small whole number written as `level as f32`: the cast back is exact.
layout_memory::shrink(ctx, shrink_key(row, unit)).map_or(0, |(found, _)| found.took.y.max(0.0) as usize)
}
/// Reports the least width of the body unit `body` of the row `row` that asks for it.
pub(crate) fn report_least(ctx: &egui::Context, row: Id, body: Id, least: f32) {
pass_state::with::<LeastReports, _>(ctx, |reports| {
@@ -485,23 +591,41 @@ fn run_shrinking<R>(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) ->
let room = shrink_room(ui);
let order = if Env::of(ui).values.get::<InBar>().0 { ShrinkOrder::FromEnd } else { ShrinkOrder::Even };
let (drops, gap) = (view_room(ui, Axis::X).is_none(), ui.spacing().item_spacing.x);
// Records the width each unit gets, and returns whether one took another width in the first sweep.
// Records the width each unit gets, and returns whether one took another width in the first sweep. The levelled
// units take their levels first, in the room the continuous units leave at their least; the continuous units then
// narrow by their own rule with the levelled units' widths held. A row without levelled units holds nothing more.
let settle = |leaves: &[Reported], fixed: f32| {
let units: Vec<ShrinkUnit> = leaves.iter().map(|leaf| leaf.widths).collect();
let whole: Vec<f32> = leaves.iter().map(|leaf| leaf.whole).collect();
let first: Vec<bool> = leaves.iter().map(|leaf| leaf.cut_first).collect();
let (levelled, continuous): (Vec<&Reported>, Vec<&Reported>) = leaves.iter().partition(|leaf| !leaf.levels.is_empty());
let units: Vec<ShrinkUnit> = continuous.iter().map(|leaf| leaf.widths).collect();
let whole: Vec<f32> = continuous.iter().map(|leaf| leaf.whole).collect();
let first: Vec<bool> = continuous.iter().map(|leaf| leaf.cut_first).collect();
let level_widths: Vec<Vec<f32>> = levelled.iter().map(|leaf| leaf.levels.clone()).collect();
let levels = if room.is_finite() {
plan_levels(&level_widths, room - fixed - units.iter().map(|unit| unit.least).sum::<f32>())
} else {
vec![0; levelled.len()]
};
let width_at = |leaf: &Reported, level: usize| leaf.levels.get(level).copied().unwrap_or_default();
let held: f32 = levelled.iter().zip(&levels).map(|(leaf, level)| width_at(*leaf, *level)).sum();
let widths = if room.is_finite() {
shrink_or_drop(&units, &whole, &first, (fixed, gap), room, order, drops)
shrink_or_drop(&units, &whole, &first, (fixed + held, gap), room, order, drops)
} else {
units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false }).collect()
};
let mut again = false;
for (leaf, cap) in leaves.iter().zip(widths) {
// A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the
// records its content's run leaves for the real run come from a sweep at the levels given.
let mut again = !levelled.is_empty();
for (leaf, cap) in continuous.iter().zip(widths) {
let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0));
layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, cap.dropped);
// Half a point: less than a pixel shows at any scale the box runs.
again |= (leaf.took - cap.width).abs() >= 0.5;
}
for (leaf, level) in levelled.iter().zip(levels) {
// The level travels as the record's height (`level_of`).
let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(*leaf, level), level as f32));
layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, false);
}
again
};
let (inner, rect, mut leaves, fixed, probe, again) = crate::contract::keeping_ids(&ctx, || {
+1 -1
View File
@@ -7,7 +7,7 @@ mod label;
mod slot;
pub use arrange::{Placed, arrange};
pub use body::{BodyLayout, RowAlign, ShrinkOrder, ShrinkUnit, shrink_widths};
pub use body::{BodyLayout, RowAlign, ShrinkOrder, ShrinkUnit, levelled_unit, plan_levels, shrink_widths};
pub use column_group::ColumnGroup;
#[doc(hidden)]
pub use column_group::ambient_width;
+4 -2
View File
@@ -237,12 +237,14 @@ impl Deref for Scoped {
/// each leaf, and each body that does not fill the row, is a unit the row narrows to fit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Shrink {
/// The first sweep of a measuring run of the row: each unit reports its widths to the row (`layout::report_shrink`).
/// The first sweep of a measuring run of the row: each unit reports its widths to the row (`layout::report_shrink`),
/// a levelled unit its width at each level (`layout::levelled_unit`).
Count(Id),
/// The sweep of a short row that asks each body unit for its least width (`layout::report_least`): it measures its
/// content unbounded along x, every leaf at its least, and leaves no record.
Least(Id),
/// Each unit shows at most the width the measuring run of the row gave it (`layout::shrink_cap`).
/// Each unit shows at most the width the measuring run of the row gave it (`layout::shrink_cap`), a levelled unit
/// at the level the row gave it.
Apply(Id),
/// A `Stack` body: each leaf shows at most the stack's room, never below its least.
Fit,
+1 -1
View File
@@ -40,7 +40,7 @@ pub use intents::settle;
pub use intents::take_submit;
pub use intents::with_window_intents;
pub(crate) use intents::{
Lent, context_part, context_request, give_back, lend, request_context, route_whole_reset, scope_escape, take_cancel, take_every_escape,
Lent, context_part, context_request, context_requests, give_back, lend, request_context, route_whole_reset, scope_escape, take_cancel, take_every_escape,
take_window_cancel,
};
pub(crate) use nodes::{redirect_node, register_expanded, register_node};
@@ -500,6 +500,11 @@ pub(crate) fn context_request(ctx: &Context, id: Id) -> Option<egui::Rect> {
current(ctx, |stage| stage.contexts.iter().find(|(owner, ..)| *owner == id).map(|(_, rect, _)| *rect))
}
/// Every context request of this pass so far, in the order they were made: the component and the rect it opens at.
pub(crate) fn context_requests(ctx: &Context) -> Vec<(Id, egui::Rect)> {
current(ctx, |stage| stage.contexts.iter().map(|(owner, rect, _)| (*owner, *rect)).collect())
}
/// The part of `id` its context request of this pass was made at, when it made one at a part.
pub(crate) fn context_part(ctx: &Context, id: Id) -> Option<PartRef> {
current(ctx, |stage| stage.contexts.iter().find(|(owner, ..)| *owner == id).and_then(|(.., part)| *part))
+8
View File
@@ -764,6 +764,14 @@ impl<T: Hash> Hash for Sub<T> {
}
}
/// A salt for an id made from `key`, a value that is only `Hash`: the ids egui makes also ask for `Debug`, which an
/// app's key type need not have. Equal keys give equal salts within a run, so the id stays the same from pass to pass.
pub fn key_salt(key: &impl Hash) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut hasher);
hasher.finish()
}
/// The runtime sub-id of `base` for `tag`: the one derivation of every id the runtime makes from a component
/// id (body, children, header, footer, layer, rows, items, popups, the gesture, `memory_at` slots, animation
/// slots, edge and transform widgets, text and access sub-nodes).
@@ -0,0 +1,65 @@
//! A row of continuous and levelled units: the continuous unit narrows first, the levelled one then steps down a level
//! at a time, and the row fits its room.
use std::cell::Cell;
use std::rc::Rc;
use craft_ui::buttons::Button;
use craft_ui::contract::{Show as _, ShowContainer as _};
use craft_ui::display::{Elide, Text};
use craft_ui::layout::levelled_unit;
use craft_ui::layout_components::Row;
use craft_ui::testing::{Fixture, is_measuring, trial};
use egui::{Id, Shape};
/// The continuous unit's text: an elided line that cuts from its end.
const LINE: &str = "Quarterly report of the northern region, second draft";
/// The levelled unit's labels, widest first.
const LEVELS: [&str; 3] = ["A wide label for the widest level", "Middle level", "S"];
/// The level the unit showed at in the real run, and the text the line showed, for a row `width` wide.
fn shown(width: f32) -> (usize, String) {
let level = Rc::new(Cell::new(usize::MAX));
let seen = level.clone();
let mut fixture = Fixture::new(move |ui| {
Row::new().fill_width().show(ui, |ui, _| {
Text::new(LINE).elide(Elide::End).show(ui);
levelled_unit(ui, Id::new("levelled"), LEVELS.len(), |ui, at| {
if !is_measuring(ui.ctx()) && !ui.is_sizing_pass() {
seen.set(at);
}
Button::new(LEVELS[at]).show(ui);
});
});
});
fixture.room(egui::vec2(width, 60.0)).settle();
let text = fixture
.frame_shapes()
.iter()
.find_map(|shape| match shape {
Shape::Text(text) if text.galley.job.text.starts_with("Quarterly") => Some(text.galley.job.text.clone()),
_ => None,
})
.unwrap_or_default();
(level.get(), text)
}
#[trial]
fn a_mixed_row_narrows_its_continuous_unit_first_then_steps_its_levelled_unit_down() {
let (wide, whole) = shown(900.0);
assert_eq!(wide, 0, "a row with room shows the levelled unit at its widest level");
assert_eq!(whole, LINE, "a row with room cuts no text");
let mut last = 0;
let mut cut_at_widest = false;
for step in 0..=42 {
let width = 900.0 - step as f32 * 20.0;
let (level, text) = shown(width);
assert!(level < LEVELS.len(), "the unit showed in the real run ({width})");
assert!(level >= last, "a narrower row never shows the levelled unit wider ({width}): {level} after {last}");
cut_at_widest |= level == 0 && text != LINE;
last = level;
}
assert!(cut_at_widest, "the continuous unit gives way before the levelled unit steps down");
assert_eq!(last, LEVELS.len() - 1, "a row with no room shows the levelled unit at its narrowest level");
}
@@ -2,5 +2,6 @@
mod elide;
mod faces;
mod levelled;
mod measure;
mod state_looks;