fu2-ribbon: app batch 2 rulings (S-L418, S-L392, S-L360, S-L361, S-L363)

Button keeps room for its widest text (room_for) and shows a rendered
picture in the leading icon's place (picture). ShownRow reports the id its
item is recorded under; the ribbon reports tab_ids from it and hosts its own
context menu (context_menu body), so RibbonOutput::menu and
RibbonMenuRequest::opener go. Stories and trials for each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Martin BallandClaude Opus 5.5 committed 2026-11-19 00:15:34 +00:00
1 parent 9c4a60014d
commit 2055375e6b
14 files changed
+467 -88

No files matched your search

+121 -24
View File
@@ -14,13 +14,16 @@ use std::sync::Arc;
use craft_behavior::{CanvasTransform, EditEvent, IconId, Metrics, Mixed, SelectionChange, Sense, keyed};
use craft_keymap::CommandRef;
use craft_ui::buttons::IconButton;
use craft_ui::contract::overlay::Anchor;
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,
Access, Bind, BodyCx, CollectionEvent, Common, Component, Container, ContainerProps, Cx, NoValue, Outcome, Props as _, Role,
Scroll, Show as _, ShowCollection as _, ShowContainer as _, Sizing, Trigger, clicked, scroll_step,
};
use craft_ui::layout_components::Row;
use craft_ui::menu::Menu;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::inspect;
use craft_ui::runtime::memory::with_session;
use craft_ui::runtime::motion::{Animate as _, spec};
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::tabs::{StripEnd, Tab, TabKind, TabRole, TabStrip, TabStripOutput};
@@ -36,15 +39,22 @@ craft_ui::words! {
struct RibbonWords {
scroll_left: "ribbon.scrollLeft" = "Scroll left";
scroll_right: "ribbon.scrollRight" = "Scroll right";
context_menu: "ribbon.contextMenu" = "Ribbon menu";
}
}
/// 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
/// with minimise and a context menu. The strip and the row show inside one inspected region
/// (`inspect::record`), whose record ([`RibbonOutput::controls`]) gives each control's rect and
/// command. On a tab change the group row slides in from the side on which the new tab lies
/// relative to the old one (mirrored in right-to-left), through one `Tween`; with reduce motion the
/// new content shows at rest.
/// command, and [`RibbonOutput::tab_ids`] says which recorded element is which tab. On a tab change
/// the group row slides in from the side on which the new tab lies relative to the old one
/// (mirrored in right-to-left), through one `Tween`; with reduce motion the new content shows at
/// rest.
///
/// A context request (a secondary click, the Menu key or Shift+F10) on a tab, a control or the row's
/// background opens the ribbon's own menu, whose rows the app's [`context_menu`](Ribbon::context_menu)
/// body shows for that request. The ribbon holds the request while the menu is open, and focus goes back
/// where it was when the menu closes by key.
#[must_use = "show the ribbon with `show`"]
#[derive(craft_ui::contract::Pattern)]
#[pattern(probe(Ribbon<'static, usize>))]
@@ -54,12 +64,22 @@ pub struct Ribbon<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> {
shown: Bind<'a, T>,
trailing: &'a [StripEnd<'a>],
minimised: Option<Bind<'a, bool>>,
/// The body of the context menu: the rows for the request that opened it.
context_menu: Option<&'a mut dyn FnMut(&mut Ui, &RibbonMenuRequest, &mut BodyCx<'_>)>,
}
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 {
Ribbon { label: label.into(), tabs, shown, trailing: &[], minimised: None }
Ribbon { label: label.into(), tabs, shown, trailing: &[], minimised: None, context_menu: None }
}
/// The rows of the ribbon's context menu. The ribbon opens its menu on a context request and runs `body` inside
/// it on every pass the menu is open, with the request that opened it: the command of the control it was on, or
/// none on a tab or the row's background. Without a body a context request opens nothing.
pub fn context_menu(mut self, body: &'a mut dyn FnMut(&mut Ui, &RibbonMenuRequest, &mut BodyCx<'_>)) -> Self {
self.context_menu = Some(body);
self
}
/// Items at the reading end of the tab strip, after the tabs.
@@ -84,8 +104,9 @@ impl<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> Ribbon<'a, T> {
/// Shows the strip and the group row of the shown tab; `body` fills the row for that tab.
///
/// 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.
/// the pass's input made (a context request, a double click) is taken 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 takes none. The context menu
/// it opened stays open on later passes until it closes.
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);
@@ -118,8 +139,9 @@ impl<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> Ribbon<'a, T> {
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;
let mut asked: Option<(RibbonMenuRequest, Asker)> = None;
let mut strip_response: Option<Response> = None;
let mut tab_ids: Vec<(T, Id)> = Vec::new();
if let Some(strip) = strip {
for event in &strip.response.events {
match event {
@@ -128,18 +150,93 @@ impl<'a, T: Clone + Eq + Hash + Send + Sync + Debug + 'static> Ribbon<'a, T> {
_ => {}
}
}
let response: &Response = &strip.response.response;
strip_rect = Some(response.rect);
// The strip shows each tab as an item recorded under the row's id; a tab in the overflow menu has no row.
tab_ids = strip.response.shown.iter().map(|row| (row.key.clone(), row.id)).collect();
picked = strip.picked;
menu = strip.menu.map(|request| RibbonMenuRequest { command: None, at: request.at, opener: response.id });
asked = strip.menu.map(|request| (RibbonMenuRequest { command: None, at: request.at }, Asker::Strip));
strip_response = Some(strip.response.response.clone());
}
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);
asked = Some((request, Asker::Row));
}
RibbonOutput { shown: chosen.or(current), picked, menu, controls, tabs: strip_rect }
if let Some(body) = self.context_menu.take() {
let openers = Openers { strip: strip_response.as_ref(), row: region.as_ref().map(|region| &region.response) };
context_menu(ui, id, asked, openers, body);
}
let tabs_rect = strip_response.as_ref().map(|response| response.rect);
RibbonOutput { shown: chosen.or(current), picked, tab_ids, controls, tabs: tabs_rect }
}
}
/// Which of the ribbon's regions asked for its context menu: the menu hangs from that region's response.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Asker {
/// The tab strip, for a tab.
Strip,
/// The group row, for a control or its background.
Row,
}
/// The responses of this pass the ribbon's context menu can hang from; `None` for a region not shown.
struct Openers<'r> {
strip: Option<&'r Response>,
row: Option<&'r Response>,
}
/// The context menu the ribbon holds open: the request that opened it and the region that asked, and the frame the
/// ribbon last showed in. It is the menu's open-popup state, kept in the ribbon's own slot.
#[derive(Clone, Default)]
struct HeldMenu {
menu: Option<(RibbonMenuRequest, Asker)>,
frame: u64,
}
/// Shows the ribbon `id`'s context menu while it is open: `asked`, this pass's request, opens it (or moves it to the
/// new request), and `body` shows its rows. The menu hangs from this pass's response of the region that asked, at the
/// request's point; the held request goes when the menu closes or that region is not shown.
fn context_menu(
ui: &mut Ui,
id: Id,
asked: Option<(RibbonMenuRequest, Asker)>,
openers: Openers<'_>,
body: &mut dyn FnMut(&mut Ui, &RibbonMenuRequest, &mut BodyCx<'_>),
) {
let slot = id.with("context_menu");
let frame = ui.ctx().cumulative_frame_nr();
let held = with_session(ui.ctx(), slot, |held: &mut HeldMenu| {
// A frame without the ribbon closed its menu with it: the request must not open the menu again when the
// ribbon shows again.
if held.frame.saturating_add(1) < frame {
held.menu = None;
}
if asked.is_some() {
held.menu = asked;
}
held.frame = frame;
held.menu.clone()
});
let Some((request, asker)) = held else { return };
let opener = match asker {
Asker::Strip => openers.strip,
Asker::Row => openers.row,
};
let mut open = opener.is_some();
if let Some(opener) = opener {
let words = Env::of(ui).words::<RibbonWords>();
let shown = Menu::new(words.context_menu.clone())
.opened_by(opener, Trigger::Manual)
.anchor(Anchor::Point(request.at))
.open(Bind::bound(&mut open))
.show(ui, |ui, cx| body(ui, &request, cx));
if shown.output.closed.is_some() {
open = false;
}
}
if !open {
with_session(ui.ctx(), slot, |held: &mut HeldMenu| held.menu = None);
}
}
@@ -221,8 +318,8 @@ fn row_request(region: &RegionOutput, recorded: Option<&inspect::Recorded>) -> O
.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 }),
Some((element, rect)) => Some(RibbonMenuRequest { command: element.command.clone(), at: rect.left_bottom() }),
None => region.own.map(|rect| RibbonMenuRequest { command: None, at: rect.left_bottom() }),
}
}
@@ -261,22 +358,22 @@ pub struct RibbonOutput<T> {
pub shown: Option<T>,
/// The tab the user picked this pass.
pub picked: Option<T>,
/// A context menu was asked for.
pub menu: Option<RibbonMenuRequest>,
/// Each tab shown this pass with the id of its element in [`controls`](RibbonOutput::controls) (a keytip's
/// place); a tab in the overflow menu has none.
pub tab_ids: Vec<(T, Id)>,
/// The inspected record of the strip and the row: each control's rect and command.
pub controls: Option<Arc<inspect::Recorded>>,
/// The tab row's rect this pass; `None` while no strip shows.
pub tabs: Option<Rect>,
}
/// A request for a context menu on a ribbon control or tab.
/// A request for the ribbon's context menu, on a control, a tab or the row's background.
#[derive(Clone, Debug)]
pub struct RibbonMenuRequest {
/// The command of the control the request is for, when it has one.
/// The command of the control the request is for, when it has one; none on a tab or the row's background.
pub command: Option<CommandRef>,
/// Where the menu opens.
pub at: Pos2,
/// 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.
+33 -3
View File
@@ -3,13 +3,14 @@
use craft_behavior::IconId;
use craft_keymap::CommandRef;
use craft_ui::buttons::{Arrangement, Button};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::contract::{Bind, BodyCx, Show as _};
use craft_ui::menu::MenuItem;
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 egui::{Event, Modifiers, PointerButton, Ui};
use super::{Ribbon, RibbonGroup, RibbonRow, RibbonTab};
use super::{Ribbon, RibbonGroup, RibbonMenuRequest, RibbonRow, RibbonTab};
/// The group titles of each tab.
const GROUPS: [[&str; 4]; 3] =
@@ -37,6 +38,15 @@ struct Setup {
end: bool,
/// The ribbon reads right to left.
rtl: bool,
/// The ribbon has a context menu.
menu: bool,
}
/// The rows of the stories' context menu: a request on a control adds it, any other customises.
fn menu_rows(ui: &mut Ui, request: &RibbonMenuRequest, _: &mut BodyCx<'_>) {
let first = if request.command.is_some() { "Add to Quick Access Toolbar" } else { "Customize Quick Access Toolbar" };
MenuItem::new(first).show(ui);
MenuItem::new("Collapse the Ribbon").show(ui);
}
/// The groups of `tab`.
@@ -59,6 +69,7 @@ fn show(ui: &mut Ui, data: &mut StoryData, setup: Setup) -> StoryOutput {
tabs.push(RibbonTab::new(3, "Picture").contextual());
}
let items = [StripEnd::command("Share", IconId::new("link").into(), CommandRef::new("ribbon.share"))];
let mut rows = menu_rows;
let mut ribbon = Ribbon::new("Ribbon", &tabs, Bind::given(*shown));
if setup.end {
ribbon = ribbon.trailing(&items);
@@ -66,6 +77,9 @@ fn show(ui: &mut Ui, data: &mut StoryData, setup: Setup) -> StoryOutput {
if setup.minimised {
ribbon = ribbon.minimised(Bind::given(true));
}
if setup.menu {
ribbon = ribbon.context_menu(&mut rows);
}
let direction = if setup.rtl { Direction::Rtl } else { Env::of(ui).direction };
let out = with_env(
ui,
@@ -137,6 +151,22 @@ fn ribbon_end_items_narrow(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { room: Some(SCROLLED_ROOM), end: true, ..Setup::default() })
}
/// A right click on the first tab, which opens the ribbon's context menu.
fn open_context_menu(fixture: &mut Fixture) {
let Some(tab) = fixture.by_label("Home") else { return };
let at = tab.rect.center();
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);
}
/// The ribbon's own context menu, open from a right click on a tab.
#[story(Ribbon<'static, usize>, covers = [Open], drive = Drive::Custom(open_context_menu), title = "Context menu")]
fn ribbon_context_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show(ui, data, Setup { menu: true, ..Setup::default() })
}
fn pick_last_tab(fixture: &mut Fixture) {
if let Some(tab) = fixture.by_label("View") {
fixture.click(&tab);
+56 -2
View File
@@ -1,15 +1,17 @@
//! Keytips: a lone Alt tap or F10 shows them, a letter a badge takes is claimed and never types, a second letter
//! narrows the badges, the badges sit on the controls of the pass's own record and stay off in a text field or under
//! a modal, badges never start one another, and a host sequence waits, ends on Escape and fires once.
//! a modal, badges never start one another, a host sequence waits, ends on Escape and fires once, and a real ribbon's
//! tab ids place the tab badges.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use craft_behavior::IconId;
use craft_host::target::Os;
use craft_i18n::Folder;
use craft_keymap::mnemonic::assign_keytips;
use craft_menu::{KeytipControl, Keytips, KeytipsOutput};
use craft_menu::{KeytipControl, Keytips, KeytipsOutput, Ribbon, RibbonGroup, RibbonTab};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, CommandSet, Overlay, Props as _, Show as _, ShowContainer as _};
use craft_ui::layout_components::{Row, Stack};
@@ -301,6 +303,58 @@ fn badges_sit_on_the_controls_of_this_passes_record_and_stay_off_in_a_text_field
assert!(rig.last().output.active, "F10 shows them again once the modal is gone");
}
/// What one pass of the ribbon rig saw: the keytips' output, the ribbon's record and its tab ids.
type RibbonPass = (KeytipsOutput, Option<Arc<Recorded>>, Vec<(usize, Id)>);
/// The tab badges of a real ribbon come from the tab ids it reports: Alt shows the Home badge on the Home tab the strip
/// shows, and its letter reports the Home badge.
#[trial]
fn the_tab_badges_sit_on_the_ribbons_tabs_by_the_ids_it_reports() {
let passes: Rc<RefCell<Vec<RibbonPass>>> = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&passes);
let mut fixture = Fixture::new(move |ui| {
let tabs = [RibbonTab::new(0_usize, "Home"), RibbonTab::new(1, "Insert")];
let ribbon = Ribbon::new("Ribbon", &tabs, Bind::given(0_usize)).show(ui, |row, _| {
row.group(RibbonGroup::new("clip", "Clipboard", IconId::new("list").into()), |ui| {
Button::command(Trial::Bold).show(ui);
});
});
let letters = [(0_usize, "Home", "H"), (1, "Insert", "N")];
let badges: Vec<(Label, &str, Id)> = letters
.iter()
.filter_map(|(key, name, badge)| ribbon.tab_ids.iter().find(|(tab, _)| tab == key).map(|(_, id)| (Label::from(*name), *badge, *id)))
.collect();
let places: Vec<Arc<Recorded>> = ribbon.controls.iter().cloned().collect();
let output = Keytips::new(true).tabs(&badges).places(&places).show(ui);
seen.borrow_mut().push((output, ribbon.controls.clone(), ribbon.tab_ids.clone()));
});
// The framework arms the menu key from a lone Alt only off macOS; the trial does not depend on its runner.
fixture.os(Os::Windows);
fixture.settle();
fixture.frame(vec![Event::ModifiersChanged(Modifiers::ALT)]);
fixture.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
fixture.settle();
let (output, recorded, tab_ids) = passes.borrow().last().cloned().unwrap_or_else(|| panic!("the rig ran a pass"));
assert!(output.active, "a lone Alt tap shows the keytips");
assert_eq!(tab_ids.iter().map(|(tab, _)| *tab).collect::<Vec<_>>(), [0, 1], "the ribbon reports both tabs it shows");
let recorded = recorded.unwrap_or_else(|| panic!("the ribbon recorded its region"));
let home_id = tab_ids[0].1;
let home = recorded
.elements
.iter()
.position(|element| element.id == home_id && element.part.is_none())
.and_then(|index| recorded.stop_rect(index))
.unwrap_or_else(|| panic!("the Home tab's id is an element of the ribbon's record"));
let badge = fixture.texts().iter().find(|text| text.text == "H").map(|text| text.rect).unwrap_or_else(|| panic!("the Home badge shows"));
assert!(sits_on(badge, home), "the Home badge {badge:?} sits on the Home tab {home:?}");
passes.borrow_mut().clear();
fixture.key(Key::H, Modifiers::NONE).settle();
let chosen: Vec<String> = passes.borrow().iter().filter_map(|(output, _, _)| output.tab.clone()).collect();
assert_eq!(chosen, ["H"], "H reports the Home badge, once");
}
#[trial]
fn assign_keytips_keeps_given_letters_and_no_badge_is_a_prefix_of_another() {
let folder = Folder::new("en");
+42 -15
View File
@@ -1,4 +1,5 @@
//! The ribbon: the fit rule, keyed group levels, a collapsed group's popover, the tab-change slide and the run model.
//! 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.
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -7,13 +8,14 @@ use std::sync::Arc;
use craft_behavior::{IconId, MotionMode};
use craft_keymap::CommandRef;
use craft_menu::{GroupLevel, GroupWidths, Ribbon, RibbonGroup, RibbonRow, RibbonTab, plan};
use craft_menu::{GroupLevel, GroupWidths, Ribbon, RibbonGroup, RibbonMenuRequest, RibbonRow, RibbonTab, plan};
use craft_ui::buttons::{Arrangement, Button, SplitButton};
use craft_ui::contract::{Bind, Entry, Props as _, Show as _};
use craft_ui::contract::{Bind, BodyCx, Entry, Props as _, Show as _};
use craft_ui::menu::MenuItem;
use craft_ui::runtime::env::{Direction, Env};
use craft_ui::runtime::inspect::{Element, Recorded};
use craft_ui::testing::{Fixture, is_measuring, last_pass_measuring_runs, trial};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2};
use egui::{Event, Id, Key, Modifiers, PointerButton, Pos2, Ui, vec2};
/// How collapsed a level is: 0 full, 1 compact, 2 collapsed.
fn rank(level: GroupLevel) -> u8 {
@@ -307,30 +309,55 @@ fn right_click(fixture: &mut Fixture, at: Pos2) {
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.
/// The row the ribbon's context menu body shows.
const MENU_ROW: &str = "Add to Quick Access Toolbar";
/// A right click on a ribbon control opens the ribbon's own menu, whose body gets the control's bound command; the
/// menu stays open on a pass with no new input, and Escape closes it with focus back on the control. A right click on
/// a tab opens it with no command.
#[trial]
fn a_right_click_on_a_control_asks_for_its_menu_with_its_command() {
fn a_right_click_on_a_control_opens_the_ribbons_menu_with_its_command() {
let menus: Rc<RefCell<Vec<Option<CommandRef>>>> = Rc::new(RefCell::new(Vec::new()));
let seen = menus.clone();
let paste_id = Rc::new(Cell::new(Id::NULL));
let (seen, at) = (menus.clone(), paste_id.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, _| {
let mut body = |ui: &mut Ui, request: &RibbonMenuRequest, _: &mut BodyCx<'_>| {
seen.borrow_mut().push(request.command.clone());
MenuItem::new(MENU_ROW).show(ui);
};
let _ = Ribbon::new("Ribbon", &tabs, Bind::given(0_usize)).context_menu(&mut body).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);
at.set(Button::new("Paste").command(CommandRef::new("edit.paste")).arrangement(Arrangement::Stacked).show(ui).response.id);
});
});
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");
// A press focuses the control, so the menu has a stop to give the focus back to.
fixture.click(&paste);
assert_eq!(fixture.focused(), Some(paste_id.get()), "the click focused 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");
assert!(fixture.by_label(MENU_ROW).is_some(), "the right click opens the ribbon's menu");
assert!(
menus.borrow().iter().all(|command| *command == Some(CommandRef::new("edit.paste"))) && !menus.borrow().is_empty(),
"the body gets the control's command: {:?}",
menus.borrow()
);
menus.borrow_mut().clear();
fixture.idle(1);
assert!(fixture.by_label(MENU_ROW).is_some(), "the menu stays open on a pass with no new input");
assert!(!menus.borrow().is_empty(), "its body runs on that pass");
fixture.key(Key::Escape, Modifiers::NONE).settle();
assert!(fixture.by_label(MENU_ROW).is_none(), "Escape closes the menu");
assert_eq!(fixture.focused(), Some(paste_id.get()), "focus is back on the control");
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");
assert!(fixture.by_label(MENU_ROW).is_some(), "a right click on a tab opens the menu");
assert!(menus.borrow().iter().all(Option::is_none) && !menus.borrow().is_empty(), "a tab's request carries no command: {:?}", menus.borrow());
}
@@ -90,6 +90,9 @@ impl<K, E> Default for ItemsOut<K, E> {
pub struct ShownRow<K> {
/// The row's key.
pub key: K,
/// The id the row's item component is recorded under: its access node and focus stop, so an app finds which
/// recorded element is which row (a keytip on a ribbon tab).
pub id: egui::Id,
/// The row's rect.
pub rect: egui::Rect,
/// The rect of each cell, by column key; empty for a collection with no columns.
@@ -101,8 +104,8 @@ pub struct ShownRow<K> {
}
impl<K> ShownRow<K> {
pub(crate) fn new(key: K, rect: egui::Rect, cells: Vec<(ColumnKey, egui::Rect)>) -> Self {
ShownRow { key, rect, cells, openers: Vec::new(), hovered: false }
pub(crate) fn new(key: K, id: egui::Id, rect: egui::Rect, cells: Vec<(ColumnKey, egui::Rect)>) -> Self {
ShownRow { key, id, rect, cells, openers: Vec::new(), hovered: false }
}
/// The row with its hover fact set.
@@ -664,7 +664,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
row = self.screen(&layout, rect, at, offset, rtl);
}
}
shown_rows.push(ShownRow::new(key.clone(), row, shown_cells.clone()).with_hover(state.hovered));
shown_rows.push(ShownRow::new(key.clone(), item_id, row, shown_cells.clone()).with_hover(state.hovered));
let Some((mut row_ui, installed)) = row_ui else {
debug_assert!(tip.is_none(), "a member of a collection's run takes no rich tooltip");
let shown = shown_rows.len() - 1;
+60 -14
View File
@@ -1,10 +1,11 @@
//! `Button`: a push button with an optional leading and trailing icon and a busy state.
//! `Button`: a push button with an optional leading icon or picture, a trailing icon and a busy state.
use super::face::{self, Arrangement, FaceLook, FaceSpec};
use crate::contract::{
Common, Component, Cx, Hover, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _,
};
use crate::display::Spinner;
use crate::display::{Picture, Spinner};
use crate::list::ThumbAspect;
use crate::primitives::{HAlign, IconSpec, PaintShape};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
@@ -21,6 +22,9 @@ use std::ops::Deref;
/// The part a loading button shows its spinner in.
const SPINNER: PartKey = PartKey::new("spinner");
/// The part a button with a picture shows it in, in the leading icon's place.
const PICTURE: PartKey = PartKey::new("picture");
/// The style of a push button.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[style(variants = [Variant::SECONDARY, Variant::PRIMARY, Variant::GHOST, Variant::DANGER, Variant::look(Emphasis::Outline, Tone::Accent)])]
@@ -124,21 +128,26 @@ impl Outcome for ButtonOutput {
}
/// A push button. A label wider than the room is cut with an ellipsis and shown whole in a tooltip. While `loading`
/// a spinner takes the place of the icon (of the label, without an icon) at the same width, the button ignores
/// activation, keeps focus and reports busy.
/// a spinner takes the place of the icon or picture (of the label, without either) at the same width, the button
/// ignores activation, keeps focus and reports busy.
#[derive(crate::contract::Component, crate::contract::Props)]
pub struct Button<'a> {
#[common]
common: Common,
/// A leading icon; it mirrors under right-to-left when it has a direction.
#[prop(into)]
icon: Option<IconSpec<'a>>,
/// A rendered picture in the leading icon's place, with the width of its box as a multiple of its height.
picture: Option<(ThumbAspect, Picture<'a>)>,
/// An icon at the reading end: the chevron of a button that opens a menu.
#[prop(into)]
trailing_icon: Option<IconSpec<'a>>,
/// Working: a spinner, no activation, AccessKit busy.
#[prop]
loading: bool,
/// Text the button keeps room for: the face is as wide as the wider of its label and this text, so a button whose
/// label changes (a zoom percent) keeps one width. The label is placed as usual.
#[prop(into)]
room_for: Option<Label>,
/// The text the face paints in place of the label, which stays the accessible name: the label with its access
/// letter marked.
#[prop(into)]
@@ -168,8 +177,10 @@ impl<'a> Button<'a> {
Button {
common: Common::new(),
icon: None,
picture: None,
trailing_icon: None,
loading: false,
room_for: None,
painted: None,
tint: None,
least_width: None,
@@ -184,13 +195,36 @@ impl<'a> Button<'a> {
<Button as Props>::command(Button::new(Label::Empty), command)
}
/// A leading icon; it mirrors under right-to-left when it has a direction. The last of `icon` and `picture`
/// called wins.
pub fn icon(mut self, icon: impl Into<IconSpec<'a>>) -> Self {
self.icon = Some(icon.into());
self.picture = None;
self
}
/// The button shows `picture` in the leading icon's place, as high as the icon and `aspect` times as wide, as its
/// own component in that box (a rendered equation, a stored image). The picture is decoration: press, focus, hit
/// area, keytip and accessible name stay the button's. The last of `icon` and `picture` called wins.
pub fn picture(mut self, aspect: ThumbAspect, picture: Picture<'a>) -> Self {
self.picture = Some((aspect, picture));
self.icon = None;
self
}
/// The face as it shows `label`: the painted text in its place when set.
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
let label = self.painted.as_ref().map_or(label, Label::as_str);
self.face_of(self.painted.as_ref().map_or(label, Label::as_str))
}
/// The face showing `label` as it is.
fn face_of<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
FaceSpec {
arrangement: self.arrangement,
label,
role: None,
lead: self.icon.as_ref(),
picture: self.picture.as_ref().map(|(aspect, _)| *aspect),
trail: self.trailing_icon.as_ref(),
loading: self.loading,
mnemonic: None,
@@ -220,22 +254,30 @@ impl Component for Button<'_> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
face::measure(cx, &self.spec(cx.resolved.label))
let shown = face::measure(cx, &self.spec(cx.resolved.label));
match &self.room_for {
Some(room) => shown.max(face::measure(cx, &self.face_of(room.as_str()))),
None => shown,
}
}
fn sense(&self) -> Sense {
if self.loading { Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS }
}
/// A loading button declares the slot of its spinner, which paints as the face of that part.
/// A loading button declares the slot of its spinner, which paints as the face of that part; any other button with
/// a picture declares the picture's box, where `paint` shows it.
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
if !self.loading {
return;
}
let (area, rtl) = (cx.content_rect, cx.flow.is_rtl());
let spinner = face::spinner_rect(cx, &self.spec(cx.resolved.label), &cx.style.face, cx.style.icon.side, area, rtl);
if let Some(rect) = spinner {
cx.part(SPINNER, rect);
if self.loading {
let spinner = face::spinner_rect(cx, &self.spec(cx.resolved.label), &cx.style.face, cx.style.icon.side, area, rtl);
if let Some(rect) = spinner {
cx.part(SPINNER, rect);
}
} else if self.picture.is_some()
&& let Some(rect) = face::lead_rect(cx, &self.spec(cx.resolved.label), &cx.style.face, cx.style.icon.side, area, rtl)
{
cx.part(PICTURE, rect);
}
}
@@ -261,6 +303,10 @@ impl Component for Button<'_> {
if cx.part_if_declared(SPINNER).is_some() {
ui.face(SPINNER, Spinner::new().size(cx.resolved.size));
}
if let (Some(part), Some((_, picture))) = (cx.part_if_declared(PICTURE), self.picture.take()) {
// The button's name names the picture: shown unlabelled, it is no access node and senses nothing.
let _ = ui.child("picture", part.rect, picture.label(Label::Empty));
}
}
fn finish(self, cx: Cx<'_, Self>) -> ButtonOutput {
+60 -22
View File
@@ -3,6 +3,7 @@
use super::GroupLevel;
use crate::contract::{Component, Cx, MeasureCx, PaintUi, Styled as _};
use crate::list::ThumbAspect;
use crate::primitives::{HAlign, IconSpec, TextLayout, TextRun};
use crate::style::{FocusLook, GlyphRole, IconLook, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens, VariantParts};
use craft_behavior::{Flow, Insets, Metrics, Proposal};
@@ -66,6 +67,9 @@ pub(crate) struct FaceSpec<'a> {
pub label: &'a str,
pub role: Option<TypeRole>,
pub lead: Option<&'a IconSpec<'a>>,
/// A picture in the leading icon's place, as high as the leading icon and this many times as wide. The face
/// reserves its box and paints nothing there: the button shows the picture in that box (`lead_rect`).
pub picture: Option<ThumbAspect>,
pub trail: Option<&'a IconSpec<'a>>,
/// A spinner takes the place of the leading icon, or of the label when there is no leading icon: the face keeps
/// the slot empty and the button shows a `Spinner` there.
@@ -85,13 +89,29 @@ impl FaceSpec<'_> {
}
}
fn icons(&self) -> usize {
usize::from(self.lead.is_some()) + usize::from(self.trail.is_some())
/// Whether the face has a leading part: an icon or a picture.
fn leads(&self) -> bool {
self.lead.is_some() || self.picture.is_some()
}
/// The width of the leading part when it is `side` high: `side` for an icon, the picture's aspect of it for a
/// picture, 0 without either.
fn lead_width(&self, side: f32) -> f32 {
match (self.picture, self.lead) {
(Some(aspect), _) => aspect.of(side),
(None, Some(_)) => side,
(None, None) => 0.0,
}
}
/// The width the leading part of `lead_side` and the trailing icon of `side` take together.
fn icons_width(&self, lead_side: f32, side: f32) -> f32 {
self.lead_width(lead_side) + if self.trail.is_some() { side } else { 0.0 }
}
/// The gaps between the parts that are shown.
fn gaps(&self) -> usize {
(self.icons() + usize::from(!self.label.is_empty())).saturating_sub(1)
(usize::from(self.leads()) + usize::from(self.trail.is_some()) + usize::from(!self.label.is_empty())).saturating_sub(1)
}
}
@@ -100,7 +120,7 @@ impl<'a> FaceSpec<'a> {
/// icon still shows and the label stays the accessible name and the tooltip. A stacked face keeps its label at
/// every level, and a face without an icon keeps it, since nothing else would show.
fn drops_label(&self, level: GroupLevel) -> bool {
self.arrangement == Arrangement::Inline && level == GroupLevel::Compact && self.lead.is_some() && !self.label.is_empty()
self.arrangement == Arrangement::Inline && level == GroupLevel::Compact && self.leads() && !self.label.is_empty()
}
/// The spec as the face shows it under `level`, with the label dropped where `drops_label` says.
@@ -161,7 +181,8 @@ struct Stack {
trail: Option<Rect>,
}
/// Lays a stacked face out in `area` from its lines' sizes: the leading icon of `lead_side` centred at the top, a gap,
/// Lays a stacked face out in `area` from its lines' sizes: the leading icon of `lead_side` (a picture that high)
/// centred at the top, a gap,
/// then each line centred under it, the trailing icon of `side` after the last line at its reading end (on a row of
/// its own when there is no line). The block is centred vertically; `size` is what `measure` reports.
fn stack(spec: &FaceSpec<'_>, sides: (f32, f32), gap: f32, lines: &[Vec2], area: Rect, rtl: bool) -> Stack {
@@ -176,13 +197,14 @@ fn stack(spec: &FaceSpec<'_>, sides: (f32, f32), gap: f32, lines: &[Vec2], area:
if lines.is_empty() && trail {
rows.push(Vec2::splat(side));
}
let icon = if spec.lead.is_some() { lead_side } else { 0.0 };
let under_icon = if spec.lead.is_some() && !rows.is_empty() { gap } else { 0.0 };
let width = rows.iter().map(|row| row.x).fold(icon, f32::max);
let icon = if spec.leads() { lead_side } else { 0.0 };
let lead_width = spec.lead_width(lead_side);
let under_icon = if spec.leads() && !rows.is_empty() { gap } else { 0.0 };
let width = rows.iter().map(|row| row.x).fold(lead_width, f32::max);
let size = Vec2::new(width, icon + under_icon + rows.iter().map(|row| row.y).sum::<f32>());
let middle = area.center().x;
let mut y = area.top() + (area.height() - size.y).max(0.0) / 2.0;
let lead = spec.lead.map(|_| Rect::from_min_size(pos2(middle - lead_side / 2.0, y), Vec2::splat(lead_side)));
let lead = spec.leads().then(|| Rect::from_min_size(pos2(middle - lead_width / 2.0, y), Vec2::new(lead_width, lead_side)));
y += icon + under_icon;
let mut placed = Stack { size, lead, lines: Vec::new(), trail: None };
for (i, row) in rows.iter().enumerate() {
@@ -337,7 +359,7 @@ pub(crate) fn measure<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>)
return stack(spec, (lead_side, side), cx.gap(), &sizes, Rect::ZERO, false).size;
}
let icon = cx.icon();
let fixed = icon * spec.icons() as f32 + cx.gap() * spec.gaps() as f32;
let fixed = spec.icons_width(icon, icon) + cx.gap() * spec.gaps() as f32;
let text = if spec.label.is_empty() {
Vec2::ZERO
} else if cx.proposal == Proposal::Min {
@@ -363,9 +385,9 @@ struct Slots {
}
/// Places the icons of `side` and a label `text_width` wide with `gap` between them, in `area` by `spec.align`: the leading
/// icon at the reading start, the trailing icon at the reading end.
/// icon (or picture) at the reading start, the trailing icon at the reading end.
fn slots(spec: &FaceSpec<'_>, side: f32, gap: f32, text_width: f32, area: Rect, rtl: bool) -> Slots {
let width = side * spec.icons() as f32 + gap * spec.gaps() as f32 + text_width;
let width = spec.icons_width(side, side) + gap * spec.gaps() as f32 + text_width;
let free = (area.width() - width).max(0.0);
let lead = match spec.align {
HAlign::Start => 0.0,
@@ -380,8 +402,8 @@ fn slots(spec: &FaceSpec<'_>, side: f32, gap: f32, text_width: f32, area: Rect,
};
let mut slots = Slots { lead: None, text: None, trail: None };
let mut gapped = false;
if spec.lead.is_some() {
slots.lead = Some(take(side));
if spec.leads() {
slots.lead = Some(take(spec.lead_width(side)));
gapped = true;
}
if !spec.label.is_empty() {
@@ -427,7 +449,7 @@ pub(crate) fn paint<C: Component>(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextL
let (text_look, icon_look) = ink;
let (text_color, icon_color, side) = (cx.resolve(&text_look.color), cx.resolve(&icon_look.color), icon_look.side);
let draw = ui.draw();
let fixed = side * spec.icons() as f32 + look.gap * spec.gaps() as f32;
let fixed = spec.icons_width(side, side) + look.gap * spec.gaps() as f32;
let run = spec.run().color(text_color);
let text = if spec.label.is_empty() { None } else { Some(draw.layout(&run, (area.width() - fixed).max(0.0))) };
let text_width = text.as_ref().map_or(0.0, |text| text.size().x);
@@ -438,7 +460,7 @@ pub(crate) fn paint<C: Component>(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextL
draw.icon(icon_at(slot, area, side), &tinted(lead, icon_color));
}
if let (Some(text), Some(slot)) = (&text, slots.text)
&& !(spec.loading && spec.lead.is_none())
&& !(spec.loading && !spec.leads())
{
draw.galley(pos2(slot.min.x, text_top(&draw, area, text)), text);
}
@@ -465,7 +487,7 @@ fn paint_stacked<C: Component>(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextLook
{
draw.icon(slot, &tinted(lead, icon_color));
}
if !(spec.loading && spec.lead.is_none()) {
if !(spec.loading && !spec.leads()) {
for (text, slot) in layouts.iter().zip(&placed.lines) {
draw.galley(slot.min, text);
}
@@ -509,13 +531,29 @@ pub(super) fn spinner_rect<C: Component>(
if spec.arrangement == Arrangement::Stacked {
let placed = stacked_in(cx, spec, look, side, area, rtl);
return match placed.lead {
Some(lead) => Some(lead),
Some(lead) => Some(Rect::from_center_size(lead.center(), Vec2::splat(lead.height()))),
None => placed.lines.first().map(|line| Rect::from_center_size(line.center(), Vec2::splat(side))),
};
}
let fixed = side * spec.icons() as f32 + look.gap * spec.gaps() as f32;
let text_width = if spec.label.is_empty() { 0.0 } else { cx.layout_at(&spec.run(), (area.width() - fixed).max(0.0)).size().x };
let slots = slots(spec, side, look.gap, text_width, area, rtl);
let slot = if spec.lead.is_some() { slots.lead } else { slots.text }?;
let slots = inline_slots(cx, spec, look, side, area, rtl);
let slot = if spec.leads() { slots.lead } else { slots.text }?;
Some(icon_at(slot, area, side))
}
/// The slots of an inline face in `area`, its label laid out in the room the icons and gaps leave.
fn inline_slots<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>, look: &FaceLook, side: f32, area: Rect, rtl: bool) -> Slots {
let fixed = spec.icons_width(side, side) + look.gap * spec.gaps() as f32;
let text_width = if spec.label.is_empty() { 0.0 } else { cx.layout_at(&spec.run(), (area.width() - fixed).max(0.0)).size().x };
slots(spec, side, look.gap, text_width, area, rtl)
}
/// The box of the face's leading part in `area`, as `paint` places it: the leading icon's square, or the picture's
/// box, as high as the leading icon and its aspect times as wide. `None` when the face has neither.
pub(super) fn lead_rect<C: Component>(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>, look: &FaceLook, side: f32, area: Rect, rtl: bool) -> Option<Rect> {
let spec = &spec.at(cx.env.get::<GroupLevel>());
if spec.arrangement == Arrangement::Stacked {
return stacked_in(cx, spec, look, side, area, rtl).lead;
}
let slot = inline_slots(cx, spec, look, side, area, rtl).lead?;
Some(Rect::from_center_size(pos2(slot.center().x, area.center().y), Vec2::new(slot.width(), side)))
}
@@ -133,6 +133,7 @@ impl<'a, T: Value + 'static> SplitButton<'a, T> {
label,
role: None,
lead: self.icon.as_ref(),
picture: None,
trail: (self.arrangement == Arrangement::Stacked).then_some(chevron),
loading: false,
mnemonic: None,
+29 -1
View File
@@ -2,13 +2,15 @@
use super::{Arrangement, Button, GroupLevel, IconButton, Link, SplitButton, SplitMenu, ToggleButton};
use crate::contract::{Bind, BodyCx, Entry, Props as _, Show as _, ShowContainer as _, Validity};
use crate::display::{Shade, Text};
use crate::display::{Picture, Shade, Text};
use crate::layout_components::{Grid, Row};
use crate::list::ThumbAspect;
use crate::menu::MenuItem;
use crate::primitives::{AppIcons, IconMark, IconSpec, register_app_icons};
use crate::runtime::commands::EditCommands;
use crate::runtime::env::{Message, with_env};
use crate::style::DataColor;
use crate::testing::pictures::sample_picture;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::{ColumnWidth, IconId, Mixed, Proposal};
use craft_theme::{ControlSize, Variant};
@@ -163,6 +165,32 @@ fn button_stacked(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown.into()
}
/// Buttons that keep room for their widest text: "1%" and "500%" with room for "500%" are equally wide, beside "1%"
/// without it.
#[story(Button<'static>, covers = [], drive = Drive::Never, title = "Room for the widest text")]
fn button_room_for(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let shown = Row::new().show(ui, |ui, _| {
for label in ["1%", "500%"] {
Button::new(label).room_for("500%").variant(Variant::GHOST).id_salt(label).show(ui);
}
Button::new("1%").variant(Variant::GHOST).id_salt("no room").show(ui);
});
shown.into()
}
/// Stacked buttons with a rendered picture in the icon's place: square and wide.
#[story(Button<'static>, covers = [], drive = Drive::Never, title = "Stacked with a picture")]
fn button_stacked_picture(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let shown = Row::new().show(ui, |ui, _| {
for (label, key, aspect, pixels) in [("Equation", 3, ThumbAspect::SQUARE, [64, 64]), ("Fraction", 5, ThumbAspect::new(2, 1), [128, 64])] {
let image = move || sample_picture(key, pixels);
let picture = Picture::new("", key, &image);
Button::new(label).picture(aspect, picture).arrangement(Arrangement::Stacked).id_salt(label).show(ui);
}
});
shown.into()
}
/// The same inline buttons at full size and inside a compact group, where they drop their labels and keep them as
/// their names and tooltips.
#[story(Button<'static>, covers = [], drive = Drive::Never, title = "Compact in a group")]
@@ -117,6 +117,7 @@ impl<'a> ToggleButton<'a> {
label: if self.icon_only { "" } else { label },
role: self.role,
lead,
picture: None,
trail: self.trailing_icon.as_ref(),
loading: false,
mnemonic: None,
@@ -189,6 +189,7 @@ impl Segment {
label: if self.icon.is_some() { "" } else { label },
role: None,
lead: self.icon.as_ref(),
picture: None,
trail: None,
loading: false,
mnemonic: None,
+2
View File
@@ -119,6 +119,7 @@ impl Component for TitleFace {
label: cx.resolved.label,
role: None,
lead: None,
picture: None,
trail: None,
loading: false,
mnemonic: None,
@@ -141,6 +142,7 @@ impl Component for TitleFace {
label: cx.resolved.label,
role: None,
lead: None,
picture: None,
trail: None,
loading: false,
mnemonic: self.mnemonic,
+55 -4
View File
@@ -1,13 +1,17 @@
//! Buttons: the stacked arrangement's height, the hover report of a click the pointer stays on, and the compact
//! group level, under which an inline button drops its label and keeps it as its name and tooltip.
//! Buttons: the stacked arrangement's height, the hover report of a click the pointer stays on, the compact
//! group level, under which an inline button drops its label and keeps it as its name and tooltip, the room a button
//! keeps for its widest text, and a picture in the leading icon's place.
use craft_behavior::IconId;
use craft_behavior::{IconId, PartKey};
use craft_theme::ControlSize;
use craft_ui::buttons::{Arrangement, Button, GroupLevel, SplitButton, SplitMenu, ToggleButton};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Show as _};
use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Role, Show as _};
use craft_ui::display::Picture;
use craft_ui::list::ThumbAspect;
use craft_ui::runtime::commands::CommandState;
use craft_ui::runtime::env::with_env;
use craft_ui::testing::pictures::sample_picture;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, trial};
use egui::{Event, Id, Pos2, Rect, Response, Ui};
@@ -265,3 +269,50 @@ fn an_inline_button_drops_its_label_under_a_compact_group_and_names_itself_by_to
assert!(passes[1] < passes[0] - 0.5, "the full-size measurement is not reused at the compact level: {passes:?}");
assert!((passes[1] - settled).abs() < 0.5, "the second pass measures as a settled compact button does: {passes:?} against {settled}");
}
#[trial]
fn a_button_with_room_for_its_widest_text_keeps_one_width_whatever_its_label() {
let widths = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&widths);
let mut fixture = Fixture::new(move |ui| {
let mut shown = Vec::new();
for label in ["1%", "500%"] {
shown.push(Button::new(label).room_for("500%").id_salt(label).show(ui).response.rect.width());
}
shown.push(Button::new("1%").id_salt("no room").show(ui).response.rect.width());
*seen.borrow_mut() = shown;
});
fixture.settle();
let widths = widths.borrow().clone();
let (least, most, alone) = (widths[0], widths[1], widths[2]);
assert!((least - most).abs() < 0.5, "1% and 500% with room for 500% are equally wide: {least} against {most}");
assert!(alone < least - 0.5, "1% without the room is narrower: {alone} against {least}");
}
#[trial]
fn a_click_on_a_buttons_picture_activates_the_button_which_stays_one_access_node() {
let at = Rc::new(Cell::new(Id::NULL));
let clicks = Rc::new(Cell::new(0));
let (seen, counted) = (Rc::clone(&at), Rc::clone(&clicks));
let mut fixture = Fixture::new(move |ui| {
let image = || sample_picture(3, [96, 48]);
let shown = Button::new("Equation")
.picture(ThumbAspect::new(2, 1), Picture::new("Rendered equation", 3, &image))
.arrangement(Arrangement::Stacked)
.show(ui);
seen.set(shown.response.id);
if shown.clicked() {
counted.set(counted.get() + 1);
}
});
fixture.settle();
let button = fixture.node_of(at.get()).expect("the button is in the access tree");
let picture = fixture.part_rect(at.get(), PartKey::new("picture")).expect("the button declares its picture's part");
assert!(button.rect.contains_rect(picture), "the picture {picture:?} lies inside the button {:?}", button.rect);
assert!(picture.width() > picture.height() + 0.5, "the picture's box is its aspect times as wide as high: {picture:?}");
fixture.click_at(picture.center());
assert!(clicks.get() > 0, "a click inside the picture activates the button");
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");
}