Files
craft-libs/crates/ui-widgets/tests/it/bars/bar.rs
T
aiongg e7b6352729 framework-01-w8: net change of 10 commits
- framework-01-w8: written by an agent
- framework-01-w8: finished by an agent
- framework-01-w8: fade takes env (framework-01-w5's signature)
- framework-01-w8: review fixes (review-1)
- framework-01-w8: review fixes (review-1, files the rulings name)
- framework-01-w8: a content column adds no Ui of its own, so its children keep their ids when its width becomes bounded or unbounded (fw01 round 2)
- framework-01-w8: the keyframe lane story fills the width its time axis is fitted to (fw01 round 2)
- framework-01-w8: a body's reveal is queued as a jump for the next pass's step 4, like the scroll bar's moves (fw01 round 2)
- framework-01-w8: the filling-bar trial pages the narrow bar and reads only what its view shows (fw01 round 2)
- framework-01-w8: a body group names its container; a text part's keys read the selection it holds for its edit menu (top run round)
2026-11-15 04:46:05 +00:00

351 lines
18 KiB
Rust

//! `Bar`: a body too wide for the bar shrinks its members before it scrolls, a captioned field among them too; a
//! bar gives way from its end, a status bar's trailing group keeps its width, and a row of labelled controls in it
//! lays out under right-to-left.
use craft_behavior::CanvasView;
use craft_behavior::IconId;
use craft_behavior::kurbo::{Point, Size};
use craft_theme::variant::Tone;
use craft_ui::bars::{Bar, BarKind, BreadcrumbBar, StatusItem, StatusMessage, StatusProgress, StatusReadout, StatusValues, path_crumbs};
use craft_ui::buttons::{Button, IconButton, Link};
use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::display::Text;
use craft_ui::form::Field;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::pickers::Select;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::layout::Block;
use craft_ui::testing::{Fixture, shrink_least_runs, trial};
use craft_ui::text::TextField;
use egui::{Rect, Vec2};
use std::cell::Cell;
use std::rc::Rc;
const SLACK: f32 = 0.5;
/// The rects of a select and of the last of `buttons` buttons after it, in an options bar `width` wide.
fn bar(width: f32, buttons: usize) -> (Rect, Rect) {
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let entries = [Entry::new(0u8, "Current and Below, No Adjustments"), Entry::new(1, "All Layers")];
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
let select = Select::new("Sample", Bind::given(1u8), &entries).sizing(Sizing::Content).show(ui).response.rect;
let mut last = Rect::NOTHING;
for at in 0..buttons {
last = Button::new(format!("Button {at}")).show(ui).rect;
}
out.set((select, last));
});
});
fixture.room(Vec2::new(width, 80.0)).settle();
seen.get()
}
#[trial]
fn a_bar_too_narrow_for_its_members_elides_a_select_before_it_scrolls() {
let (wide, _) = bar(900.0, 1);
let (select, button) = bar(200.0, 1);
assert!(select.width() < wide.width() - SLACK, "the select kept its width {} in a narrow bar", select.width());
assert!(button.max.x <= 200.0 + SLACK, "the last member ends at {} past the bar's end", button.max.x);
// Buttons do not shrink: when even the select's least leaves no room for them, the select keeps its width (at most
// the bar's room) and the rest scrolls.
let (crowded, button) = bar(200.0, 6);
assert!(button.max.x > 200.0, "six buttons fit a 200-point bar: {button:?}");
assert!(crowded.width() > select.width() + SLACK, "the select narrowed to {} in a bar that scrolls anyway", crowded.width());
}
/// What a captioned select in an options bar `width` wide shows, with `buttons` buttons after it.
struct Captioned {
select: Rect,
caption: Rect,
last: Rect,
/// Whether a row asked its body units for their least widths.
probed: bool,
}
fn captioned(width: f32, buttons: usize) -> Captioned {
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let entries = [Entry::new(0u8, "Current and Below, No Adjustments"), Entry::new(1, "All Layers")];
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
let select = Field::new("Sample").show(ui, |ui, _| Select::new("Sample", Bind::given(0u8), &entries).show(ui).response.rect);
let mut last = Rect::NOTHING;
for at in 0..buttons {
last = Button::new(format!("Button {at}")).show(ui).rect;
}
out.set((select.inner.unwrap_or(Rect::NOTHING), last));
});
});
fixture.room(Vec2::new(width, 80.0)).settle();
let (select, last) = seen.get();
let caption = fixture.texts().iter().find(|text| text.text == "Sample").map_or(Rect::NOTHING, |text| text.rect);
Captioned { select, caption, last, probed: !shrink_least_runs(fixture.ctx()).is_empty() }
}
#[trial]
fn a_captioned_select_in_a_narrow_bar_narrows_with_its_caption_beside_it_before_the_bar_scrolls() {
let wide = captioned(900.0, 1);
assert!(!wide.probed, "a bar its members fit asked a body for its least width");
let narrow = captioned(260.0, 1);
assert!(narrow.select.width() < wide.select.width() - SLACK, "the select kept its width {} in a narrow bar", narrow.select.width());
assert!(narrow.last.max.x <= 260.0 + SLACK, "the last member ends at {} past the bar's end", narrow.last.max.x);
assert!(
narrow.caption.max.x <= narrow.select.min.x + SLACK && narrow.caption.center().y > narrow.select.min.y,
"the caption {:?} is not beside the select {:?}",
narrow.caption,
narrow.select
);
// Once the field is at its least, the rest scrolls.
let crowded = captioned(260.0, 6);
assert!(crowded.last.max.x > 260.0, "six buttons fit a 260-point bar: {:?}", crowded.last);
}
/// The rects of an up button, a path, a search field and a count, in that order, in a tool bar `width` wide.
fn header(width: f32) -> Vec<Rect> {
let seen = Rc::new(std::cell::RefCell::new(Vec::new()));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let crumbs = path_crumbs("Project");
let mut search = String::new();
Bar::new("Header", BarKind::Tool).show(ui, |ui, _| {
let up = IconButton::new(IconId::new("chevron_up")).label("Up").show(ui).rect;
let path = BreadcrumbBar::new("Path", &crumbs).show(ui).response.rect;
let field = TextField::search("Search", Bind::bound(&mut search)).show(ui).response.rect;
let count = Text::new("1 of 9 items selected").show(ui).rect;
*out.borrow_mut() = vec![up, path, field, count];
});
});
fixture.room(Vec2::new(width, 80.0)).settle();
seen.borrow().clone()
}
#[trial]
fn the_members_of_a_tool_bar_never_overlap_as_it_narrows() {
for width in [900.0, 342.0, 260.0] {
let rects = header(width);
for pair in rects.windows(2) {
assert!(pair[0].max.x <= pair[1].min.x + SLACK, "at {width} points {:?} runs into {:?}", pair[0], pair[1]);
}
}
}
/// What a select in an options bar `width` wide shows, with three buttons after it: its rect and whether its text
/// was elided.
fn select_in(width: f32) -> (Rect, bool) {
let seen = Rc::new(Cell::new(Rect::NOTHING));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let entries = [Entry::new(0u8, "Point Sample"), Entry::new(1, "5 by 5 Average")];
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
out.set(Select::new("Sample Size", Bind::given(0u8), &entries).sizing(Sizing::Content).show(ui).response.rect);
for at in 0..3 {
Button::new(format!("Button {at}")).show(ui);
}
});
});
fixture.room(Vec2::new(width, 80.0)).settle();
let elided = fixture.texts().iter().any(|text| text.text == "Point Sample" && text.elided);
(seen.get(), elided)
}
#[trial]
fn a_select_in_a_short_bar_narrows_past_a_fields_own_least_and_elides() {
let (wide, _) = select_in(900.0);
// The widths at which the buttons after it, at their least, leave the select less than a field's own least.
let narrowed = (200..=400).step_by(10).map(|width| select_in(width as f32)).find(|(rect, _)| rect.width() < 96.0);
let Some((narrow, elided)) = narrowed else { panic!("the select stayed at least 96 wide at every width") };
assert!(narrow.width() < wide.width() - SLACK && elided, "the select {narrow:?} did not elide its pick");
}
/// What a status bar shows: the message's rect (none when it shows nothing), the readout before it, and the trailing
/// group's progress and render-path link.
struct Status {
message: Option<Rect>,
readout: Rect,
progress: Rect,
link: Rect,
}
impl Default for Status {
fn default() -> Self {
Status { message: None, readout: Rect::NOTHING, progress: Rect::NOTHING, link: Rect::NOTHING }
}
}
fn status_fixture(message: &'static str, seen: Rc<Cell<Status>>) -> Fixture {
Fixture::new(move |ui| {
let (mut progress, mut link) = (Rect::NOTHING, Rect::NOTHING);
let shown = Bar::new("Status", BarKind::Status)
.trailing(|ui, _| {
let output = StatusProgress::new("Blur", Some(0.45)).cancel("Cancel").show(ui);
progress = output.response.rect;
link = Link::new("CPU Rendering").tone(Tone::Warn).show(ui).rect;
})
.show(ui, |ui, _| {
let readout = Text::new("1200 px x 800 px (72 ppi)").show(ui).rect;
(readout, StatusMessage::new(message).tone(Tone::Bad).show(ui).map(|shown| shown.rect))
});
if let Some((readout, message)) = shown.inner {
seen.set(Status { message, readout, progress, link });
}
})
}
fn status(width: f32, message: &'static str) -> Status {
let seen = Rc::new(Cell::new(Status::default()));
status_fixture(message, Rc::clone(&seen)).room(Vec2::new(width, 80.0)).settle();
seen.take()
}
#[trial]
fn a_narrow_status_bar_cuts_its_message_and_keeps_its_trailing_group_whole() {
const LONG: &str = "Exported 14 layers to the folder Documents/Exports/2026";
let wide = status(1200.0, LONG);
let narrow = status(520.0, LONG);
let (wide_message, narrow_message) = (wide.message.expect("a message shows"), narrow.message.expect("a cut message shows"));
assert!(narrow_message.width() < wide_message.width() - SLACK, "the message kept its width {} in a narrow bar", narrow_message.width());
assert!(narrow_message.max.x <= narrow.progress.min.x + SLACK, "the message runs under the trailing group: {narrow_message:?}");
assert!((narrow.progress.width() - wide.progress.width()).abs() < SLACK, "the progress narrowed with the bar");
assert!((narrow.link.width() - wide.link.width()).abs() < SLACK, "the render-path label narrowed with the bar");
assert!(narrow.link.max.x <= 520.0 + SLACK, "the trailing group ends past the bar at {}", narrow.link.max.x);
let empty = status(1200.0, "");
assert!(empty.message.is_none(), "an empty message shows");
assert!((empty.readout.width() - wide.readout.width()).abs() < SLACK, "an empty message changed the members before it");
}
/// What a tool bar of two search fields and a button shows: the bar's rect and the parts of the fields and the button its view
/// shows.
#[derive(Clone, Copy)]
struct Filling {
bar: Rect,
fields: [Rect; 2],
button: Rect,
}
/// A content-sized column `room` wide holding a block `column` wide and a tool bar of two search fields sized
/// `fields` and a button, after `pages` pages of the bar toward its end.
fn filling_bar(room: f32, column: f32, fields: Sizing, pages: usize) -> Filling {
let empty = Filling { bar: Rect::NOTHING, fields: [Rect::NOTHING; 2], button: Rect::NOTHING };
let seen = Rc::new(Cell::new(empty));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let (mut name, mut kind) = (String::new(), String::new());
Stack::new().show(ui, |ui, _| {
Block::new(Vec2::new(column, 20.0)).show(ui);
let mut shown = empty;
let bar = Bar::new("Filters", BarKind::Tool).show(ui, |ui, _| {
shown.fields[0] = TextField::search("Name", Bind::bound(&mut name)).sizing(fields).show(ui).response.rect;
shown.fields[1] = TextField::search("Kind", Bind::bound(&mut kind)).sizing(fields).show(ui).response.rect;
shown.button = Button::new("Apply").show(ui).rect;
});
shown.bar = bar.output.response.rect;
out.set(shown);
});
});
fixture.room(Vec2::new(room, 200.0)).settle();
for _ in 0..pages {
let target = fixture.by_label("Filters").expect("the bar is in the tree");
fixture.access(AccessActionKind::ScrollRight, &target).settle();
}
seen.get()
}
#[trial]
fn filling_bar_members_keep_their_natural_width_and_the_bar_scrolls() {
// A bar's row scrolls along x, so a content-sized field there measures at its natural width.
let natural = filling_bar(1400.0, 1000.0, Sizing::Content, 0).fields;
let held = filling_bar(1400.0, 1000.0, Sizing::FillWidth, 0);
let dump = format!("bar {:?}, fields {:?}, button {:?}", held.bar, held.fields, held.button);
assert!(held.bar.width() >= 1000.0 - SLACK, "the bar is held across its column: {dump}");
assert!(held.fields[0].width() > natural[0].width() + SLACK, "the fields fill the bar held at the column's width: {dump}");
let (lead, trail) = (held.fields[0].min.x - held.bar.min.x, held.bar.max.x - held.button.max.x);
assert!((lead - trail).abs() < 1.0, "the button reaches the bar's end, as the first field its start: {dump}");
// Narrowed, the members keep their widths and the bar scrolls. A member's shown rect is the part the bar's view
// shows, so the bar is paged toward its end: on some page each field shows at least its natural width and the
// button shows whole, and on no page do two members overlap.
let button = held.button.width();
let (mut widest, mut button_whole) = ([0.0_f32; 2], Vec::new());
for pages in 0..=12 {
let page = filling_bar(200.0, 100.0, Sizing::FillWidth, pages);
let dump = format!("page {pages}: bar {:?}, fields {:?}, button {:?}", page.bar, page.fields, page.button);
let shown: Vec<Rect> = page.fields.iter().chain([&page.button]).copied().filter(|rect| rect.is_positive()).collect();
for (at, first) in shown.iter().enumerate() {
for second in &shown[at + 1..] {
assert!(first.intersect(*second).width() <= SLACK, "two members overlap: {dump}");
}
}
for (widest, field) in widest.iter_mut().zip(page.fields) {
if field.is_positive() {
*widest = widest.max(field.width());
}
}
button_whole.push(page.button.is_positive() && (page.button.width() - button).abs() < SLACK);
}
for (widest, natural) in widest.iter().zip(natural) {
assert!(*widest >= natural.width() - SLACK, "a field never showed its natural width {}: at most {widest}", natural.width());
}
assert!(!button_whole[0], "the members fit the narrow bar unscrolled");
assert!(button_whole.contains(&true), "the bar does not scroll to show its last member whole: {button_whole:?}");
}
/// The texts a status bar `width` wide paints, each with whether it was cut: the readout of the document sizes, a long
/// message and the render-path link in its trailing group.
fn readout_texts(width: f32) -> Vec<(String, bool)> {
let mut fixture = Fixture::new(|ui| {
let mut values = StatusValues::default();
values.document_sizes = Some((26_100_000, 31_400_000));
let canvas = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::Pos2::new(800.0, 600.0));
let view = CanvasView::new(canvas, Point::new(1000.0, 750.0), 0.6667);
Bar::new("Status", BarKind::Status)
.trailing(|ui, _| {
Link::new("CPU Rendering").tone(Tone::Warn).show(ui);
})
.show(ui, |ui, _| {
StatusReadout::new(Bind::given(view), Size::new(2000.0, 1500.0), StatusItem::DocumentSizes, &values).show(ui);
StatusMessage::new("Exported 14 layers to the folder Documents/Exports/2026").show(ui);
});
});
fixture.room(Vec2::new(width, 80.0)).settle();
fixture.texts().iter().map(|text| (text.text.clone(), text.elided)).collect()
}
#[trial]
fn a_narrow_bar_gives_way_from_its_end_so_the_message_elides_before_the_readout() {
let cut = |texts: &[(String, bool)], start: &str| texts.iter().find(|(text, _)| text.starts_with(start)).expect(start).1;
let wide = readout_texts(1200.0);
assert!(!cut(&wide, "Doc") && !cut(&wide, "Exported"), "a wide bar cuts nothing");
let narrow = readout_texts(480.0);
assert!(cut(&narrow, "Exported"), "the message kept its whole text in a 480-point bar");
assert!(!cut(&narrow, "Doc"), "the readout's text was cut while the message after it could still give way");
}
/// A Row in a Bar under right-to-left measures in a room unbounded at its start edge, the left one: a labelled check
/// box there lays out with finite rects inside the bar, after the button before it in reading order. Guards against a
/// label row built from the room's start and width, which was NaN there.
#[trial]
fn a_labelled_check_box_in_a_row_in_a_bar_lays_out_under_rtl() {
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let mut alpha = Rect::NOTHING;
let bar = Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
alpha = Button::new("Alpha").show(ui).rect;
Checkbox::new(Bind::given(true)).label("Delete Cropped Pixels").show(ui);
});
});
out.set((bar.output.response.rect, alpha));
});
fixture.direction(craft_i18n::Direction::Rtl).room(Vec2::new(400.0, 80.0)).settle();
let (bar, alpha) = seen.get();
let label = fixture.texts().iter().find(|text| text.text == "Delete Cropped Pixels").map(|text| text.rect).expect("the label is painted");
let control = fixture.by_label("Delete Cropped Pixels").expect("the check box is in the tree").rect;
for rect in [label, control] {
assert!(rect.is_finite() && bar.contains_rect(rect), "{rect:?} lies outside the bar {bar:?}");
}
assert!(label.max.x <= alpha.min.x + SLACK, "the check box {label:?} follows Alpha {alpha:?} from the right");
}