mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 04:27:49 +00:00
Framework batch 4 c: port follow-ups (see runs/fwb4-c.md)
This commit is contained in:
@@ -99,7 +99,8 @@ pub trait ItemLayout {
|
||||
|
||||
/// Whether the items are as wide as they measure themselves. A layout that asks for widths places the items
|
||||
/// from their measured ideal and minimum widths (`set_width`), so every item must be built and measured: its
|
||||
/// `visible` lists all items, and the collection does not virtualise it.
|
||||
/// `visible` lists all items, and the collection does not virtualise it. Its items sit side by side, so where the
|
||||
/// collection's width comes from its rows (a room that does not bound it) it is their ideal widths' sum.
|
||||
fn auto_widths(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ fn model() -> MenuBar {
|
||||
vec![
|
||||
item("file.new", "New").into(),
|
||||
Node::submenu("Open Recent", vec![item("file.recent.a", "notes.txt").into()]),
|
||||
Node::submenu("Export", vec![item("file.export.pdf", "PDF").into()]).enabled(false),
|
||||
Node::Separator,
|
||||
item("file.revert", "Revert").enabled(false).into(),
|
||||
],
|
||||
|
||||
@@ -129,8 +129,8 @@ impl<'a> Rows<'a> {
|
||||
Node::Separator => {
|
||||
Divider::horizontal().show(ui);
|
||||
}
|
||||
Node::Submenu { children, .. } => {
|
||||
if is_dead(children) {
|
||||
Node::Submenu { children, enabled, .. } => {
|
||||
if !enabled || is_dead(children) {
|
||||
MenuItem::submenu(label).enabled(false).show(ui);
|
||||
} else {
|
||||
Menu::submenu_row(ui, label, |ui, _| self.show(ui, children));
|
||||
@@ -212,7 +212,7 @@ fn checked(ui: &Ui, command: &CommandRef) -> Option<bool> {
|
||||
fn is_dead(nodes: &[Node]) -> bool {
|
||||
!nodes.iter().any(|node| match node {
|
||||
Node::Item(item) => item.enabled,
|
||||
Node::Submenu { children, .. } => !is_dead(children),
|
||||
Node::Submenu { children, enabled, .. } => *enabled && !is_dead(children),
|
||||
Node::Separator | Node::Standard { .. } => false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -347,7 +347,9 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option
|
||||
it.label = options.text("Preferences…");
|
||||
Node::Item(it)
|
||||
}
|
||||
Node::Submenu { children, role, platforms, .. } => Node::Submenu { label: options.text("Preferences"), children, role, platforms },
|
||||
Node::Submenu { children, role, platforms, enabled, .. } => {
|
||||
Node::Submenu { label: options.text("Preferences"), children, role, platforms, enabled }
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
ensure_menu(&mut bar, MenuRole::Edit, "Edit", options).children.extend([Node::Separator, s]);
|
||||
@@ -373,9 +375,13 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar {
|
||||
let shown = nodes.iter().filter_map(|n| match n {
|
||||
Node::Item(it) if !it.platforms.contains(on) => None,
|
||||
Node::Submenu { platforms, .. } if !platforms.contains(on) => None,
|
||||
Node::Submenu { label, children, role, platforms } => {
|
||||
Some(Node::Submenu { label: label.clone(), children: keep(children, on, appkit), role: *role, platforms: *platforms })
|
||||
}
|
||||
Node::Submenu { label, children, role, platforms, enabled } => Some(Node::Submenu {
|
||||
label: label.clone(),
|
||||
children: keep(children, on, appkit),
|
||||
role: *role,
|
||||
platforms: *platforms,
|
||||
enabled: *enabled,
|
||||
}),
|
||||
Node::Standard { .. } if !appkit => None,
|
||||
other => Some(other.clone()),
|
||||
});
|
||||
@@ -441,11 +447,11 @@ fn settings_node(node: Node, comma_taken: Option<CommandRef>, options: &LayoutOp
|
||||
give(&mut it);
|
||||
Node::Item(it)
|
||||
}
|
||||
Node::Submenu { mut children, role, platforms, .. } => {
|
||||
Node::Submenu { mut children, role, platforms, enabled, .. } => {
|
||||
if let Some(Node::Item(first)) = children.iter_mut().find(|n| matches!(n, Node::Item(i) if i.enabled)) {
|
||||
give(first);
|
||||
}
|
||||
Node::Submenu { label: options.text("Settings"), children, role, platforms }
|
||||
Node::Submenu { label: options.text("Settings"), children, role, platforms, enabled }
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
@@ -461,12 +467,12 @@ fn appearance_node(bar: &mut MenuBar, options: &LayoutOptions) -> Vec<Node> {
|
||||
items.push(it);
|
||||
}
|
||||
match submenu {
|
||||
Some(Node::Submenu { mut children, role, platforms, .. }) => {
|
||||
Some(Node::Submenu { mut children, role, platforms, enabled, .. }) => {
|
||||
if !items.is_empty() {
|
||||
children.push(Node::Separator);
|
||||
children.extend(items);
|
||||
}
|
||||
vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms }]
|
||||
vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms, enabled }]
|
||||
}
|
||||
_ => items,
|
||||
}
|
||||
|
||||
@@ -173,7 +173,11 @@ fn lower_nodes(nodes: &[Node], targets: &mut HashMap<String, Target>) -> Vec<nat
|
||||
.iter()
|
||||
.map(|n| match n {
|
||||
Node::Separator => native::Node::Separator,
|
||||
Node::Submenu { label, children, .. } => native::Node::Submenu { label: label.clone(), children: lower_nodes(children, targets) },
|
||||
// A native submenu is disabled while it has no children: a disabled one goes over empty.
|
||||
Node::Submenu { label, children, enabled, .. } => native::Node::Submenu {
|
||||
label: label.clone(),
|
||||
children: if *enabled { lower_nodes(children, targets) } else { Vec::new() },
|
||||
},
|
||||
Node::Standard { kind, label } => native::Node::Platform {
|
||||
kind: match kind {
|
||||
Standard::Services => native::Platform::Services,
|
||||
|
||||
@@ -150,6 +150,9 @@ pub enum Node {
|
||||
role: Option<ItemRole>,
|
||||
/// The platforms it is shown on.
|
||||
platforms: Platforms,
|
||||
/// Whether it can be opened. A disabled submenu shows its row greyed and never opens
|
||||
/// (Open Recent with nothing to list); one whose rows are all disabled is greyed too.
|
||||
enabled: bool,
|
||||
},
|
||||
/// An item AppKit provides and runs itself (Services, Zoom, …), with the label to show.
|
||||
#[non_exhaustive]
|
||||
@@ -432,9 +435,20 @@ impl Node {
|
||||
Node::Standard { kind, label: label.into() }
|
||||
}
|
||||
|
||||
/// A submenu shown on every platform.
|
||||
/// An enabled submenu shown on every platform.
|
||||
pub fn submenu(label: impl Into<String>, children: Vec<Node>) -> Node {
|
||||
Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL }
|
||||
Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL, enabled: true }
|
||||
}
|
||||
|
||||
/// Set whether an item can be chosen or a submenu opened:
|
||||
/// `Node::submenu("Open Recent", rows).enabled(!recent.is_empty())`.
|
||||
pub fn enabled(mut self, on: bool) -> Node {
|
||||
match &mut self {
|
||||
Node::Item(it) => it.enabled = on,
|
||||
Node::Submenu { enabled, .. } => *enabled = on,
|
||||
Node::Separator | Node::Standard { .. } => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`.
|
||||
@@ -702,12 +716,12 @@ pub fn tidy(nodes: Vec<Node>) -> Vec<Node> {
|
||||
let mut out: Vec<Node> = Vec::with_capacity(nodes.len());
|
||||
for n in nodes {
|
||||
let n = match n {
|
||||
Node::Submenu { label, children, role, platforms } => {
|
||||
Node::Submenu { label, children, role, platforms, enabled } => {
|
||||
let children = tidy(children);
|
||||
if children.is_empty() {
|
||||
continue;
|
||||
}
|
||||
Node::Submenu { label, children, role, platforms }
|
||||
Node::Submenu { label, children, role, platforms, enabled }
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
@@ -764,8 +778,10 @@ fn hash_nodes(nodes: &[Node], h: &mut DefaultHasher) {
|
||||
it.alternate.as_ref().map(|a| (a.command.key(), a.mods)).hash(h);
|
||||
}
|
||||
Node::Separator => '-'.hash(h),
|
||||
Node::Submenu { label, children, role, .. } => {
|
||||
('[', label, role).hash(h);
|
||||
// A native submenu is enabled only through its children (see `mac::lower_nodes`), so its
|
||||
// enabled state is structure.
|
||||
Node::Submenu { label, children, role, enabled, .. } => {
|
||||
('[', label, role, enabled).hash(h);
|
||||
hash_nodes(children, h);
|
||||
']'.hash(h);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! The in-window bar's own rules over the model.
|
||||
|
||||
use craft_menu::{Item, Menu, MenuBar, MenuBarUi, Node};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
|
||||
/// A submenu the app disables stays greyed and never opens, though its rows could be chosen
|
||||
/// (Open Recent with a placeholder row while the app keeps no recent files).
|
||||
#[trial]
|
||||
fn a_disabled_submenu_is_greyed_and_does_not_open() {
|
||||
let bar = MenuBar::new(vec![Menu::new(
|
||||
"File",
|
||||
vec![
|
||||
Node::submenu("Open Recent", vec![Item::new("file.recent.a", "notes.txt").into()]).enabled(false),
|
||||
Node::submenu("Export", vec![Item::new("file.export.pdf", "PDF").into()]),
|
||||
],
|
||||
)]);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
MenuBarUi::new(&bar).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let Some(file) = fixture.by_label("File") else { panic!("the bar shows File") };
|
||||
fixture.click(&file).settle();
|
||||
let Some(recent) = fixture.by_label("Open Recent") else { panic!("File shows Open Recent") };
|
||||
let Some(export) = fixture.by_label("Export") else { panic!("File shows Export") };
|
||||
assert!(fixture.tree().is_disabled_key(recent.node), "the disabled submenu is greyed");
|
||||
assert!(!fixture.tree().is_disabled_key(export.node), "its enabled sibling is not");
|
||||
fixture.click(&recent).settle();
|
||||
assert!(fixture.by_label("notes.txt").is_none(), "a click does not open it");
|
||||
fixture.click(&export).settle();
|
||||
assert!(fixture.by_label("PDF").is_some(), "the enabled one opens");
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The integration binary of craft-menu: every test is a registered trial.
|
||||
|
||||
mod bar;
|
||||
mod layout;
|
||||
mod mnemonic;
|
||||
mod native;
|
||||
|
||||
@@ -225,6 +225,18 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
|
||||
};
|
||||
let previous = self.layout.take().or_else(|| self.previous.take()).map(|held| Arc::try_unwrap(held).unwrap_or_else(|held| (*held).clone()));
|
||||
let mut layout = comp.item_layout_from(previous, &*self.source, width, item, scx);
|
||||
// An auto-width layout sets its items side by side: where its width comes from its rows, it takes their run at
|
||||
// their ideal widths, not the widest one (a tab strip in a bar's unbounded row).
|
||||
let run = (layout.auto_widths() && (asked.is_some() || !bounded) && !self.source.is_empty())
|
||||
.then(|| self.run_in(ui, id, room).min(room.x))
|
||||
.filter(|run| *run > width);
|
||||
let (width, asked) = match run {
|
||||
Some(run) => {
|
||||
layout = comp.item_layout_from(Some(layout), &*self.source, run, item, scx);
|
||||
(run, asked.map(|asked| asked.max(run)))
|
||||
}
|
||||
None => (width, asked),
|
||||
};
|
||||
if self.header.has_columns() {
|
||||
layout.set_columns(&self.header.columns(width));
|
||||
}
|
||||
|
||||
@@ -43,10 +43,10 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
|
||||
rows.max(comp.ideal_width(item, scx)).min(room.x)
|
||||
}
|
||||
|
||||
/// The largest ideal size of the rows in this pass, and the widest cell each column's items reported: each row is
|
||||
/// built as `content` builds it, with its column cells at the widths the header resolves with no room to share (a
|
||||
/// fixed or toggle column at its own width), and measured without allocating.
|
||||
fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) {
|
||||
/// The largest ideal size of the rows in this pass, the sum of their ideal widths, and the widest cell each column's
|
||||
/// items reported: each row is built as `content` builds it, with its column cells at the widths the header
|
||||
/// resolves with no room to share (a fixed or toggle column at its own width), and measured without allocating.
|
||||
fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::contract::steps::measuring(&ctx, || self.largest_row_in(comp, ui, id))
|
||||
}
|
||||
@@ -96,8 +96,9 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
|
||||
if inputs.is_some() {
|
||||
layout_memory::begin_measure(&ctx, key);
|
||||
}
|
||||
let (largest, cells) = self.largest_row(comp, ui, id);
|
||||
let (largest, run, cells) = self.largest_row(comp, ui, id);
|
||||
layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(room, largest));
|
||||
layout_memory::emit_record(&ctx, run_id(id), layout_memory::Measured::new(room, Vec2::new(run, 0.0)));
|
||||
let env = Env::of(ui);
|
||||
let content: Vec<(usize, craft_behavior::ColumnKey)> = self.header.content_columns().map(|(at, key)| (at, key.clone())).collect();
|
||||
for (at, column) in content {
|
||||
@@ -126,13 +127,23 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
|
||||
})
|
||||
}
|
||||
|
||||
fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) {
|
||||
/// The length of the rows side by side at their ideal widths, as the last measure of the largest row in the room
|
||||
/// `room` found them (`largest_in`); 0 before one.
|
||||
pub(super) fn run_in(&self, ui: &Ui, id: Id, room: Vec2) -> f32 {
|
||||
let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ui.ctx()));
|
||||
layout_memory::measured(ui.ctx(), run_id(id))
|
||||
.filter(|found| layout_memory::Measured::serves(room.x, found.room.x, false, found.took.x, tolerance))
|
||||
.map_or(0.0, |found| found.took.x)
|
||||
}
|
||||
|
||||
fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let env = Env::of(ui);
|
||||
let mut memory = MemoryStage::open_peek(&ctx, id);
|
||||
let cells: Vec<(craft_behavior::ColumnKey, Rect)> =
|
||||
self.header.columns(0.0).into_iter().map(|(key, width)| (key, Rect::from_min_size(Pos2::ZERO, Vec2::new(width, 0.0)))).collect();
|
||||
let mut largest = Vec2::ZERO;
|
||||
let mut run = 0.0;
|
||||
let mut widest: Vec<(craft_behavior::ColumnKey, f32)> = Vec::new();
|
||||
for at in 0..self.source.len() {
|
||||
if self.source.section_stop(at) {
|
||||
@@ -141,6 +152,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
|
||||
let row = RowMeasure { at, rect: Rect::ZERO, cells: cells.clone(), proposal: Proposal::Ideal };
|
||||
let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row);
|
||||
largest = largest.max(size);
|
||||
run += size.x;
|
||||
for (column, width) in cells {
|
||||
match widest.iter_mut().find(|(held, _)| *held == column) {
|
||||
Some((_, held)) => *held = held.max(width),
|
||||
@@ -148,7 +160,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
|
||||
}
|
||||
}
|
||||
}
|
||||
(largest, widest)
|
||||
(largest, run, widest)
|
||||
}
|
||||
|
||||
/// Builds the item of `row.at` as the collection `id` builds it, with the default row state, under `installed`
|
||||
@@ -217,6 +229,11 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the measure of the largest row of the collection `id` records the length of its rows side by side.
|
||||
fn run_id(id: Id) -> Id {
|
||||
sub(id, "run")
|
||||
}
|
||||
|
||||
/// A row to build and measure (`measure_row`): its position, rect and column cells, and the proposal it is measured at.
|
||||
pub(super) struct RowMeasure {
|
||||
pub(super) at: usize,
|
||||
|
||||
@@ -10,14 +10,15 @@ use crate::buttons::IconButton;
|
||||
use crate::contract::{
|
||||
Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, FooterRegion, HeaderEdge, HeaderParts,
|
||||
HeaderRegion, ListDrag, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role,
|
||||
ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _,
|
||||
Show as _, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _,
|
||||
};
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow};
|
||||
use crate::runtime::commands::{self, CommandSet as _, CommandState, Commands as _};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::runtime::focus::{self, FocusTarget};
|
||||
use crate::sections::FooterBar;
|
||||
use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind};
|
||||
use crate::style::{ComponentStyle, Corners, StyleCx, SurfaceKind, TypeRole};
|
||||
use crate::tabs::{Tab, TabKind, TabStrip, TornOff};
|
||||
use craft_behavior::{DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed};
|
||||
use craft_theme::{ControlSize, Tokens};
|
||||
@@ -465,7 +466,7 @@ impl<P: Clone + Hash + Send + Sync + 'static> Container for DockGroup<'_, P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's items and the tab strip, on one line.
|
||||
/// The host's items and the tab strip, on one line, a tab with its panel's count; then the shown panel's caption.
|
||||
fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
|
||||
for (command, state) in self.command_states.drain(..) {
|
||||
cx.publish(command, state);
|
||||
@@ -515,7 +516,10 @@ impl<P: Clone + Hash + Send + Sync + 'static> Container for DockGroup<'_, P> {
|
||||
// The panel's toggle command marks its tab as it marks the panel's rail button, with the hint to say why.
|
||||
let resolved = panel.and_then(|panel| panel.command.clone()).map(|command| commands::resolve(&ctx, command));
|
||||
let marked = resolved.as_ref().is_some_and(|resolved| IconButton::shows_marker(resolved));
|
||||
let tab = Tab::new(title).closable(panel.is_some_and(closes)).marked(marked);
|
||||
let mut tab = Tab::new(title).closable(panel.is_some_and(closes)).marked(marked);
|
||||
if let Some(count) = panel.and_then(|panel| panel.count) {
|
||||
tab = tab.detail(env.format().integer(u64::try_from(count).unwrap_or(u64::MAX)));
|
||||
}
|
||||
match resolved.and_then(|resolved| resolved.hint).filter(|_| marked) {
|
||||
Some(hint) => tab.tooltip(hint),
|
||||
None => tab,
|
||||
@@ -550,6 +554,9 @@ impl<P: Clone + Hash + Send + Sync + 'static> Container for DockGroup<'_, P> {
|
||||
reported.item = shown.inner.flatten().or(reported.item);
|
||||
}
|
||||
});
|
||||
if let Some(caption) = panels.iter().find(|panel| panel.key == active).and_then(|panel| panel.caption.clone()) {
|
||||
Text::new(caption).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
self.extra = extra;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,12 +113,30 @@ pub struct PanelTitle {
|
||||
pub closable: bool,
|
||||
/// The panel's toggle command: the tab resolves it for its marker and its hint.
|
||||
pub command: Option<CommandRef>,
|
||||
/// The number the tab shows after the title ([`PanelSpec::count`]).
|
||||
pub count: Option<usize>,
|
||||
/// The line under the header row while the panel is shown ([`PanelSpec::caption`]).
|
||||
pub caption: Option<Label>,
|
||||
}
|
||||
|
||||
impl PanelTitle {
|
||||
/// A panel `key` titled `title`, not closable from its tab.
|
||||
pub fn new(key: PanelKey, title: impl Into<Label>) -> Self {
|
||||
PanelTitle { key, title: title.into(), closable: false, command: None }
|
||||
PanelTitle { key, title: title.into(), closable: false, command: None, count: None, caption: None }
|
||||
}
|
||||
|
||||
/// The number the tab shows after the title.
|
||||
#[must_use]
|
||||
pub fn count(mut self, count: Option<usize>) -> Self {
|
||||
self.count = count;
|
||||
self
|
||||
}
|
||||
|
||||
/// The line under the header row while the panel is shown.
|
||||
#[must_use]
|
||||
pub fn caption(mut self, caption: Option<Label>) -> Self {
|
||||
self.caption = caption;
|
||||
self
|
||||
}
|
||||
|
||||
/// The panel's toggle command.
|
||||
|
||||
@@ -137,6 +137,11 @@ pub struct PanelSpec {
|
||||
/// The panel has a footer pinned under its body, which `DockPanels::footer` fills: it stays in view while the
|
||||
/// body scrolls.
|
||||
pub footer: bool,
|
||||
/// A number after the panel's name on its tab, in faint type and in its accessible name ("Comments, 3"): what
|
||||
/// the panel lists.
|
||||
pub count: Option<usize>,
|
||||
/// A line of small faint text under the header row while the panel is the one its group shows ("2 replies").
|
||||
pub caption: Option<Label>,
|
||||
}
|
||||
|
||||
impl PanelSpec {
|
||||
@@ -154,9 +159,25 @@ impl PanelSpec {
|
||||
grid: None,
|
||||
command: None,
|
||||
footer: false,
|
||||
count: None,
|
||||
caption: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `n` after the panel's name on its tab.
|
||||
#[must_use]
|
||||
pub fn count(mut self, n: usize) -> Self {
|
||||
self.count = Some(n);
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows `text` under the header row while the panel is shown.
|
||||
#[must_use]
|
||||
pub fn caption(mut self, text: impl Into<Label>) -> Self {
|
||||
self.caption = Some(text.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// The panel has a footer pinned under its body, which `DockPanels::footer` fills.
|
||||
#[must_use]
|
||||
pub fn footer(mut self) -> Self {
|
||||
|
||||
@@ -108,6 +108,13 @@ fn a_group_with_a_footer(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
.into()
|
||||
}
|
||||
|
||||
/// A group whose shown panel counts what it lists after its name and says more in a caption under the header.
|
||||
#[story(DockGroup<'static, usize>, covers = [Default])]
|
||||
fn a_panel_with_a_count_and_a_caption(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let panels = vec![title_of(LAYERS).count(Some(3)).caption(Some("2 hidden".into())), title_of(CHANNELS).count(Some(4))];
|
||||
DockGroup::new(LAYERS, &panels, panels[0].key).show(ui, |_, _| ()).output.into()
|
||||
}
|
||||
|
||||
/// A click on the panel menu button opens the group's panel menu.
|
||||
fn open_panel_menu(fixture: &mut Fixture) {
|
||||
if let Some(button) = fixture.root_id().and_then(|id| fixture.part(id, MENU)) {
|
||||
|
||||
@@ -33,3 +33,34 @@ fn a_minimized_group_runs_no_body() {
|
||||
assert!(runs > 0 && found, "an expanded group shows its body: {runs} runs, node {found}");
|
||||
assert_eq!(body(true), (0, false), "a minimized group runs no body and leaves no node");
|
||||
}
|
||||
|
||||
// A panel's count follows its name on its tab and in the tab's name; the shown panel's caption sits in the header
|
||||
// under the tabs and above the body, and goes when another panel of the group is shown.
|
||||
#[trial]
|
||||
fn the_shown_panels_caption_sits_under_the_tabs_and_its_count_names_its_tab() {
|
||||
let shown = Rc::new(Cell::new(0usize));
|
||||
let picked = Rc::clone(&shown);
|
||||
let panels = vec![
|
||||
PanelTitle::new(PanelKey::new(1), "Comments").count(Some(3)).caption(Some("2 replies".into())),
|
||||
PanelTitle::new(PanelKey::new(2), "Pages").count(Some(9)),
|
||||
];
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let group = DockGroup::new(1usize, &panels, panels[picked.get()].key);
|
||||
let out = group.show_at(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(300.0, 240.0)), |ui, _| {
|
||||
Button::new("Body button").show(ui);
|
||||
});
|
||||
if let Some(key) = out.output.picked {
|
||||
picked.set(panels.iter().position(|panel| panel.key == key).unwrap_or(0));
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
let Some(tab) = fixture.by_label("Comments, 3") else { panic!("the tab is named with its count") };
|
||||
let Some(caption) = fixture.by_label("2 replies") else { panic!("the shown panel's caption shows") };
|
||||
let Some(body) = fixture.by_label("Body button") else { panic!("the body shows") };
|
||||
assert!(caption.rect.top() >= tab.rect.bottom() - 0.5, "the caption {:?} is under the tab {:?}", caption.rect, tab.rect);
|
||||
assert!(body.rect.top() >= caption.rect.bottom() - 0.5, "the body {:?} is under the caption {:?}", body.rect, caption.rect);
|
||||
let Some(pages) = fixture.by_label("Pages, 9") else { panic!("the other tab is named with its count") };
|
||||
fixture.click(&pages).settle();
|
||||
assert_eq!(shown.get(), 1, "the click shows Pages");
|
||||
assert!(fixture.by_label("2 replies").is_none(), "Comments' caption goes with it");
|
||||
}
|
||||
|
||||
@@ -836,7 +836,11 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
.iter()
|
||||
.map(|panel| {
|
||||
let spec = scene.spec(panel);
|
||||
PanelTitle::new(PanelKey::of(panel), spec.label).closable(scene.permissions(panel).closable).command(spec.command)
|
||||
PanelTitle::new(PanelKey::of(panel), spec.label)
|
||||
.closable(scene.permissions(panel).closable)
|
||||
.command(spec.command)
|
||||
.count(spec.count)
|
||||
.caption(spec.caption)
|
||||
})
|
||||
.collect();
|
||||
let shown = &members[active];
|
||||
|
||||
@@ -245,7 +245,8 @@ impl Outcome for StartOutput {
|
||||
/// Enter opens a file; arrows move; the context menu (secondary click, the menu key or Shift+F10) and the
|
||||
/// [`StartRecentCommands`] remove it from the list, clear the list or show it in its folder. A file's
|
||||
/// [`note`](RecentFile::note) shows in place of its age.
|
||||
/// - **Pinned folders.** Each folder is a heading row. A listed folder holds its files, the first
|
||||
/// - **Pinned folders.** Each folder is a heading row, with a disclosure when the app lists it (still listing, empty
|
||||
/// or unavailable too). A listed folder holds its files, the first
|
||||
/// [`PINNED_FILES_SHOWN`] until the app expands it, then a More row; the heading's trailing note says when the app is
|
||||
/// still listing, cannot list, found no files or kept only the newest. The app owns fold and expansion: the
|
||||
/// disclosure and Left/Right report [`StartAction::FoldPinned`], the More row [`StartAction::ExpandPinned`], and the
|
||||
@@ -813,7 +814,7 @@ fn folder_note(words: &ShellWords, folder: &PinnedFolder) -> Option<Label> {
|
||||
}
|
||||
|
||||
/// The source of the pinned folders' list: each folder's heading, then the files it shows and its More row when it
|
||||
/// holds more than [`PINNED_FILES_SHOWN`]. A heading is a tree group when the folder has listed files.
|
||||
/// holds more than [`PINNED_FILES_SHOWN`]. A heading is a tree group when the app lists the folder.
|
||||
struct PinnedRows<'f> {
|
||||
rows: Vec<(PinnedKey, PinnedRow<'f>)>,
|
||||
}
|
||||
@@ -860,8 +861,9 @@ impl DisplayOrder<PinnedKey> for PinnedRows<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every folder the app lists folds, one with no files to show too, so each heading has its disclosure.
|
||||
fn has_children(&self, at: usize) -> bool {
|
||||
matches!(self.rows[at].1, PinnedRow::Folder(folder) if !listed_files(folder).is_empty())
|
||||
matches!(self.rows[at].1, PinnedRow::Folder(folder) if folder.listing.is_some())
|
||||
}
|
||||
|
||||
fn open(&self, at: usize) -> bool {
|
||||
@@ -887,13 +889,11 @@ fn pinned_row<'r>(words: &ShellWords, row: PinnedRow<'_>) -> ListRow<'r> {
|
||||
.detail(folder.path.display().to_string())
|
||||
.icon(IconSpec::svg(IconId::new("folder")))
|
||||
.depth(0);
|
||||
if !listed_files(folder).is_empty() {
|
||||
heading = heading.group(!folder.folded);
|
||||
}
|
||||
// A folder the app does not list keeps the plain row; its menu and Delete still unpin it.
|
||||
if folder.listing.is_none() {
|
||||
return heading;
|
||||
}
|
||||
heading = heading.group(!folder.folded);
|
||||
if let Some(note) = folder_note(words, folder) {
|
||||
heading = heading.trailing(note);
|
||||
}
|
||||
|
||||
@@ -111,6 +111,71 @@ fn the_recent_menu_offers_show_in_folder_where_the_platform_can_reveal() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A start screen of `files` in `view`, in a room wide enough for the rail; every action goes to the log.
|
||||
fn recent_screen(files: Vec<RecentFile>, view: RecentView) -> (Fixture, Log) {
|
||||
let log: Log = Rc::default();
|
||||
let seen = Rc::clone(&log);
|
||||
let (mut view, mut sort) = (view, RecentSort::Opened);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &files).show(ui);
|
||||
seen.borrow_mut().extend(out.actions);
|
||||
});
|
||||
fixture.room(egui::Vec2::new(1100.0, 900.0)).settle();
|
||||
log.borrow_mut().clear();
|
||||
(fixture, log)
|
||||
}
|
||||
|
||||
/// A card's remove action and a list row's revealed remove button ask to remove that file alone, and the recent menu's
|
||||
/// Clear asks to clear the list.
|
||||
#[trial]
|
||||
fn a_recent_file_is_removed_from_its_card_or_row_and_the_menu_clears_them_all() {
|
||||
let files = || vec![RecentFile::new("/tmp/work/Poster.psd", "Poster.psd"), RecentFile::new("/tmp/work/Flyer.psd", "Flyer.psd")];
|
||||
let flyer = PathBuf::from("/tmp/work/Flyer.psd");
|
||||
|
||||
let (mut grid, log) = recent_screen(files(), RecentView::Grid);
|
||||
let card = target(&grid, "Flyer.psd");
|
||||
grid.frame(vec![moved(card.center())]).idle(2);
|
||||
let remove = target(&grid, "Remove from Recent");
|
||||
grid.click(&remove).idle(2);
|
||||
assert_eq!(*log.borrow(), vec![StartAction::RemoveRecent(flyer.clone())], "the hovered card's action removes its file alone");
|
||||
|
||||
let (mut list, log) = recent_screen(files(), RecentView::List);
|
||||
// A row is named by its name and its folder.
|
||||
let row = target(&list, "Flyer.psd, /tmp/work");
|
||||
list.frame(vec![moved(row.center())]).idle(2);
|
||||
let remove = target(&list, "Remove Flyer.psd from Recent");
|
||||
list.click(&remove).idle(2);
|
||||
assert_eq!(*log.borrow(), vec![StartAction::RemoveRecent(flyer)], "the row's remove button removes its file alone");
|
||||
|
||||
log.borrow_mut().clear();
|
||||
let at = target(&list, "Poster.psd, /tmp/work").center();
|
||||
list.frame(vec![moved(at)]);
|
||||
list.frame(vec![secondary(at, true)]);
|
||||
list.frame(vec![secondary(at, false)]);
|
||||
list.idle(3);
|
||||
let clear = target(&list, "Clear Recent Files");
|
||||
list.click(&clear).idle(2);
|
||||
assert_eq!(*log.borrow(), vec![StartAction::ClearRecent], "the menu's Clear asks to clear the list");
|
||||
}
|
||||
|
||||
/// In the list, a long name and a long folder path are cut short and end before the row's trailing detail, which shows
|
||||
/// whole.
|
||||
#[trial]
|
||||
fn a_long_recent_name_and_folder_are_cut_before_the_detail() {
|
||||
let name = format!("{}.pdf", "Quarterly report final version ".repeat(10));
|
||||
let folder = format!("/{}", "A folder with a long name".repeat(8));
|
||||
let file = RecentFile::new(format!("{folder}/{name}"), name.clone()).note("7 pages");
|
||||
let (fixture, _) = recent_screen(vec![file], RecentView::List);
|
||||
let texts = fixture.texts();
|
||||
let Some(detail) = texts.iter().find(|text| text.text == "7 pages") else { panic!("the row shows its detail") };
|
||||
assert!(!detail.elided, "the detail shows whole");
|
||||
for whole in [&name, &folder] {
|
||||
let Some(text) = texts.iter().find(|text| text.text == *whole) else { panic!("the row shows {whole:?}") };
|
||||
assert!(text.elided, "{whole:?} is cut short");
|
||||
assert!(text.rect.right() <= detail.rect.left(), "{whole:?} ends before the detail: {:?}, {:?}", text.rect, detail.rect);
|
||||
}
|
||||
}
|
||||
|
||||
/// The template's detail line; a tile with a detail is named "name, detail".
|
||||
const TEMPLATE_DETAIL: &str = "210 × 297 mm";
|
||||
|
||||
@@ -228,6 +293,7 @@ fn a_listed_pinned_folder_folds_shows_more_and_opens_its_files() {
|
||||
PinnedFolder::new(&work, "Work").listing(FolderListing::Listed { files, total: count }),
|
||||
PinnedFolder::new("/tmp/Inbox", "Inbox").listing(FolderListing::Pending),
|
||||
PinnedFolder::new("/mnt/Gone", "Gone").listing(FolderListing::Unavailable),
|
||||
PinnedFolder::new("/tmp/Empty", "Empty").listing(FolderListing::Listed { files: Vec::new(), total: 0 }),
|
||||
];
|
||||
let (mut fixture, log, pins, notes) = pinned_screen(folders);
|
||||
|
||||
@@ -273,4 +339,11 @@ fn a_listed_pinned_folder_folds_shows_more_and_opens_its_files() {
|
||||
assert!((0..count).all(|n| fixture.by_label(&file_name(n)).is_none()), "a folded folder shows no file row");
|
||||
assert!(fixture.by_label("Show less").is_none(), "a folded folder shows no More row");
|
||||
assert!(fixture.by_label(&heading_name).is_some(), "a folded folder keeps its heading");
|
||||
|
||||
// Every folder the app lists folds, one with no files too.
|
||||
let empty = target(&fixture, "Empty, /tmp/Empty");
|
||||
fixture.click(&empty).idle(2);
|
||||
log.borrow_mut().clear();
|
||||
fixture.key(Key::ArrowLeft, Modifiers::NONE).idle(2);
|
||||
assert_eq!(*log.borrow(), vec![StartAction::FoldPinned(PathBuf::from("/tmp/Empty"))], "an empty folder's disclosure folds it");
|
||||
}
|
||||
|
||||
@@ -476,8 +476,8 @@ impl<'a> Tile<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A hover action: an `IconButton::command` face shown while the pointer is over the tile or it has visible focus,
|
||||
/// where `action_place` puts it, and reached by the keys as a part of the tile; repeatable. Its activation is
|
||||
/// A hover action: an `IconButton::command` face shown while the pointer is over the tile, it has visible focus or
|
||||
/// it is selected, where `action_place` puts it, and reached by the keys as a part of the tile; repeatable. Its activation is
|
||||
/// [`TilePartEvent::Action`] with its index; `command` gives its label, tooltip and enabled state, and the tile
|
||||
/// does not fire it.
|
||||
#[must_use]
|
||||
@@ -860,7 +860,7 @@ impl Component for Tile<'_> {
|
||||
for (at, (mark, rect)) in self.marks.iter().zip(&placed.marks).enumerate() {
|
||||
let _ = cx.part(MARK.at(at as u64), *rect).tooltip(mark.tip.clone());
|
||||
}
|
||||
if !placed.actions.is_empty() && (cx.hovered() || cx.focus_visible()) {
|
||||
if !placed.actions.is_empty() && (cx.hovered() || cx.focus_visible() || cx.resolved.selected == Some(true)) {
|
||||
for (at, rect) in placed.actions.iter().enumerate() {
|
||||
cx.part(ACTION.at(at as u64), *rect).sense(Sense::CLICK | Sense::FOCUS).focusable();
|
||||
}
|
||||
|
||||
@@ -348,3 +348,41 @@ fn a_labelled_check_box_in_a_row_in_a_bar_lays_out_under_rtl() {
|
||||
}
|
||||
assert!(label.max.x <= alpha.min.x + SLACK, "the check box {label:?} follows Alpha {alpha:?} from the right");
|
||||
}
|
||||
|
||||
/// A text tab strip in a tool bar's row, as a window's mode strip: the row gives it unbounded room, so it measures
|
||||
/// the natural length of its tabs and every tab shows, none in the overflow menu, and the strip ends before the
|
||||
/// bar's trailing group.
|
||||
#[trial]
|
||||
fn a_tab_strip_in_a_bar_row_takes_its_tabs_natural_length() {
|
||||
use craft_behavior::keyed;
|
||||
use craft_ui::contract::ShowCollection as _;
|
||||
use craft_ui::tabs::{Tab, TabKind, TabStrip};
|
||||
const MODES: [&str; 4] = ["All tools", "Edit", "Convert", "E-Sign"];
|
||||
let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING)));
|
||||
let out = Rc::clone(&seen);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let mut trailing = Rect::NOTHING;
|
||||
let mut strip = Rect::NOTHING;
|
||||
Bar::new("Modes", BarKind::Tool)
|
||||
.trailing(|ui, _| {
|
||||
trailing = IconButton::new(IconId::new("printer")).label("Print").show(ui).rect;
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
let keys = [0_usize, 1, 2, 3];
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let tabs = TabStrip::new("Modes").kind(TabKind::Text).natural_height(true).shown(1);
|
||||
strip = tabs.show_items(ui, &source, &mut |key, _| Tab::new(MODES[*key])).response.response.rect;
|
||||
});
|
||||
out.set((strip, trailing));
|
||||
});
|
||||
});
|
||||
fixture.room(Vec2::new(1274.0, 200.0)).settle();
|
||||
let (strip, trailing) = seen.get();
|
||||
let shown: Vec<Rect> = MODES.iter().filter_map(|title| fixture.by_label(title)).map(|tab| tab.rect).collect();
|
||||
let dump = format!("strip {strip:?}, trailing {trailing:?}, tabs {shown:?}");
|
||||
assert_eq!(shown.len(), MODES.len(), "every tab shows: {dump}");
|
||||
let length: f32 = shown.iter().map(Rect::width).sum();
|
||||
assert!(strip.width() >= length - SLACK, "the strip is as long as its tabs: {dump}");
|
||||
assert!(strip.max.x <= trailing.min.x + SLACK, "and ends before the trailing group: {dump}");
|
||||
}
|
||||
|
||||
@@ -62,24 +62,27 @@ fn the_badge_bar_leaves_out_what_does_not_fit_and_never_overlaps() {
|
||||
}
|
||||
|
||||
/// A named hover action carries its tile in its accessible name, so the shown actions of different tiles are told
|
||||
/// apart; the actions of a tile that does not show them stay out of the tree.
|
||||
/// apart; a selected tile shows its actions without the pointer, and the actions of a tile that does not show them
|
||||
/// stay out of the tree.
|
||||
#[trial]
|
||||
fn a_named_action_is_exposed_by_its_own_name_while_its_tile_shows_it() {
|
||||
use craft_behavior::IconId;
|
||||
use craft_ui::contract::Props as _;
|
||||
use craft_ui::runtime::commands::CommandRef;
|
||||
use craft_ui::testing::Fixture;
|
||||
use craft_ui::testing::pointer::moved;
|
||||
const NAMES: [&str; 2] = ["Rotate page 1 clockwise", "Rotate page 2 clockwise"];
|
||||
const PAGES: [&str; 2] = ["Page 1", "Page 2"];
|
||||
const NAMES: [&str; 3] = ["Rotate page 1 clockwise", "Rotate page 2 clockwise", "Rotate page 3 clockwise"];
|
||||
const PAGES: [&str; 3] = ["Page 1", "Page 2", "Page 3"];
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (page, name) in PAGES.iter().zip(NAMES) {
|
||||
Tile::new(*page).action_named(IconId::new("rotate_cw"), CommandRef::new("page.rotate"), name).show(ui);
|
||||
for (at, (page, name)) in PAGES.iter().zip(NAMES).enumerate() {
|
||||
Tile::new(*page).action_named(IconId::new("rotate_cw"), CommandRef::new("page.rotate"), name).selected(at == 2).show(ui);
|
||||
}
|
||||
});
|
||||
});
|
||||
fixture.room(vec2(400.0, 300.0)).settle();
|
||||
assert!(NAMES.iter().all(|name| fixture.by_label(name).is_none()), "no tile is hovered, so no action shows");
|
||||
fixture.room(vec2(600.0, 300.0)).settle();
|
||||
assert!(NAMES[..2].iter().all(|name| fixture.by_label(name).is_none()), "no tile is hovered, so no action shows");
|
||||
assert!(fixture.by_label(NAMES[2]).is_some(), "the selected tile shows its action unhovered");
|
||||
let over = fixture.by_label(PAGES[1]).expect("the second tile").rect.center();
|
||||
fixture.frame(vec![moved(over)]).settle();
|
||||
assert!(fixture.by_label(NAMES[1]).is_some(), "the hovered tile's action is named for its tile");
|
||||
|
||||
Reference in New Issue
Block a user