mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 00:34:25 +00:00
Row slots: a hosted trailing component takes the width it measures (trailing_field, optional_field drops first, trailing_space keeps an absent field's room), lead_text puts a short text in the leading slot whose double click a row reports as LeadClicked, and a trailing part's click carries its count and whether its row held the lead when the press began (RowPressed::Part)
PageList shows each row's number and reports Fit on a double click on it; its options open on the active row or on a double click. PaintList hosts the paint chip, hex and opacity fields and the binding's badge, with a solid row named by its hex. RenderQueueList's row actions are small labelled buttons and an encoding row shows its progress bar. LayersPanel::trailing adds the host's component after a row's indicators. A row's progress bar is named after the row.
This commit is contained in:
@@ -2,18 +2,22 @@
|
||||
|
||||
use craft_behavior::{Axis, EditEvent, IconId, Selection};
|
||||
use craft_behavior::{DisplayOrder, ItemSource, Mixed, SelectionChange};
|
||||
use craft_theme::Rgba;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::contract::{Bind, Outcome, Show as _, ShowCollection as _};
|
||||
use craft_ui::contract::{CollectionEvent, NoValue, Rename};
|
||||
use craft_ui::display::Badge;
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize, TrailingFace, TrailingPart};
|
||||
use craft_ui::primitives::{ContentPainterCx, IconSpec, PaintShape};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::text::{HexField, NumberField};
|
||||
use egui::{Color32, Rect, Response, Ui};
|
||||
use std::cell::RefCell;
|
||||
|
||||
use super::{Paint, PaintWords, paint_image, ramp_stops};
|
||||
use super::{Paint, PaintChip, PaintWords, paint_image, ramp_stops};
|
||||
|
||||
/// How a paint is bound (FigCraft's colour style or variable).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -241,8 +245,9 @@ const ROW_CHIP: (u16, u16) = (3, 2);
|
||||
///
|
||||
/// With [`options`](Self::options) a row also offers the binding's name with Bind and Detach ([`rows`](Self::rows)),
|
||||
/// "Select layers with this color" and Remove after the name, and Add under the rows. Each reports a
|
||||
/// [`PaintListEvent`]. The per-row chip edit, hex field and opacity field wait for a row slot that holds field
|
||||
/// controls.
|
||||
/// [`PaintListEvent`]. With `edit` a live [`PaintChip`] takes the thumbnail's place among the trailing items, and
|
||||
/// `hex` and `opacity` add a hex field and a percent field to each solid row; the binding shows as a badge by the
|
||||
/// name that drops out first in a narrow list.
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
pub struct PaintList<'a> {
|
||||
label: Label,
|
||||
@@ -275,42 +280,87 @@ impl<'a> PaintList<'a> {
|
||||
let (paints, rows, options, label) = (self.paints, self.rows, self.options, self.label.clone());
|
||||
let mut output = None;
|
||||
let mut add = false;
|
||||
let acted = RefCell::new(Vec::new());
|
||||
let shown = Stack::new().show(ui, |ui, cx| {
|
||||
let held = match selected_bind.reborrow().read(cx) {
|
||||
Some(Mixed::Same(Some(row))) if row < paints.len() => Selection::single(row),
|
||||
_ => Selection::default(),
|
||||
};
|
||||
let list = List::<usize>::new(label.clone()).selection(Bind::given(held)).can_rename(|_| true);
|
||||
let first_solid = paints.iter().find_map(|(_, paint)| if let Paint::Solid(color) = paint { Some(*color) } else { None });
|
||||
let fallback = self.fallback.or(first_solid).unwrap_or(Self::DEFAULT_SOLID);
|
||||
let acted = &acted;
|
||||
output = Some(list.show_items(ui, &Paints(paints), &mut |row, _| {
|
||||
let (name, paint) = &paints[*row];
|
||||
let mut item =
|
||||
ListRow::new(name.clone()).thumb_aspect(ThumbSize::Small, ThumbAspect::new(ROW_CHIP.0, ROW_CHIP.1), move |painter, rect| {
|
||||
let row = *row;
|
||||
let (name, paint) = &paints[row];
|
||||
let solid = match paint {
|
||||
Paint::Solid(color) => Some(*color),
|
||||
_ => None,
|
||||
};
|
||||
let mut item = ListRow::new(name.clone());
|
||||
if let Some(color) = solid {
|
||||
item = item.accessible_name(format!("{name}, {}", color.to_rgba().to_hex()));
|
||||
}
|
||||
if !options.edit {
|
||||
item = item.thumb_aspect(ThumbSize::Small, ThumbAspect::new(ROW_CHIP.0, ROW_CHIP.1), move |painter, rect| {
|
||||
paint_thumb(painter, rect, paint);
|
||||
});
|
||||
if let Some(link) = rows.get(*row).and_then(|data| data.link.as_ref()) {
|
||||
item = item.trailing(link.name.clone());
|
||||
}
|
||||
// The first item added is the outermost: Remove closes the row, the binding's badge sits by the name.
|
||||
if options.remove {
|
||||
let label = Label::from(words.remove.fill(&[("name", name.as_str())]));
|
||||
item = item.trailing_part(REMOVE, TrailingFace::Icon(IconSpec::svg(IconId::new("minus"))), label);
|
||||
}
|
||||
if options.select_users {
|
||||
let label = Label::from(words.select_users.fill(&[("name", name.as_str())]));
|
||||
item = item.trailing_part(SELECT_USERS, TrailingFace::Icon(IconSpec::svg(IconId::new("layers"))), label);
|
||||
}
|
||||
let link = rows.get(row).and_then(|data| data.link.as_ref());
|
||||
if options.bind {
|
||||
let (name, icon) = match rows.get(*row).and_then(|data| data.link.as_ref()) {
|
||||
let (label, icon) = match link {
|
||||
Some(PaintLink { kind: PaintLinkKind::Style, .. }) => (words.detach_style.clone(), "unlink"),
|
||||
Some(PaintLink { kind: PaintLinkKind::Variable, .. }) => (words.detach_variable.clone(), "unlink"),
|
||||
None => (words.styles.clone(), "palette"),
|
||||
};
|
||||
item = item.trailing_part(BIND, TrailingFace::Icon(IconSpec::svg(IconId::new(icon))), name);
|
||||
item = item.trailing_part(BIND, TrailingFace::Icon(IconSpec::svg(IconId::new(icon))), label);
|
||||
}
|
||||
if options.select_users {
|
||||
item = item.trailing_part(
|
||||
SELECT_USERS,
|
||||
TrailingFace::Icon(IconSpec::svg(IconId::new("layers"))),
|
||||
Label::from(words.select_users.fill(&[("name", name.as_str())])),
|
||||
);
|
||||
// A row without a solid colour keeps the fields' room empty, so the buttons after them line up.
|
||||
if options.opacity {
|
||||
let percent = solid.map_or(100.0, |color| f64::from(color.a) * 100.0);
|
||||
let field = NumberField::new(words.opacity.clone(), Bind::given(Some(percent))).range(0.0..=100.0).unit("%");
|
||||
item = match solid {
|
||||
Some(_) => item.trailing_field(field, move |shown| {
|
||||
for event in shown.edit.events.iter() {
|
||||
let event = event.clone().map(|percent| (percent.unwrap_or(100.0) / 100.0) as f32);
|
||||
acted.borrow_mut().push(PaintListEvent::Opacity { row, event });
|
||||
}
|
||||
}),
|
||||
None => item.trailing_space(field),
|
||||
};
|
||||
}
|
||||
if options.remove {
|
||||
item = item.trailing_part(
|
||||
REMOVE,
|
||||
TrailingFace::Icon(IconSpec::svg(IconId::new("minus"))),
|
||||
Label::from(words.remove.fill(&[("name", name.as_str())])),
|
||||
);
|
||||
if options.hex {
|
||||
// The field shows no alpha digits: a typed colour keeps the row's alpha.
|
||||
let opaque = solid.map_or(Rgba::rgb(0, 0, 0), |color| Srgba { a: 1.0, ..color }.to_rgba());
|
||||
let field = HexField::hex(words.hex.clone(), Bind::given(opaque));
|
||||
item = match solid {
|
||||
Some(color) => item.trailing_field(field, move |shown| {
|
||||
if let Some(typed) = shown.events.landed() {
|
||||
acted.borrow_mut().push(PaintListEvent::Hex { row, color: Srgba { a: color.a, ..Srgba::from(*typed) } });
|
||||
}
|
||||
}),
|
||||
None => item.trailing_space(field),
|
||||
};
|
||||
}
|
||||
if options.edit {
|
||||
let chip = PaintChip::new(words.edit.clone(), Bind::given(paint.clone()), solid.unwrap_or(fallback));
|
||||
item = item.trailing_field(chip, move |shown| {
|
||||
for event in shown.edit.events.iter() {
|
||||
acted.borrow_mut().push(PaintListEvent::Edit { row, event: event.clone() });
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(link) = link {
|
||||
item = item.optional_field(Badge::new(link.name.clone()), |_| {});
|
||||
}
|
||||
item
|
||||
}));
|
||||
@@ -321,7 +371,7 @@ impl<'a> PaintList<'a> {
|
||||
// A parent's measuring run reuses what it measured and does not run the body.
|
||||
let Some(list) = output else { return PaintListOutput { response: shown.output, selected: None, events: Vec::new() } };
|
||||
let mut selected = None;
|
||||
let mut events = Vec::new();
|
||||
let mut events = acted.into_inner();
|
||||
for event in list.events {
|
||||
match event {
|
||||
CollectionEvent::Selection(SelectionChange::Set(keys)) => selected = keys.last().copied().or(selected),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The screen tests of craft-color, folded into the lib's test target.
|
||||
|
||||
mod color_parts;
|
||||
mod paint_list;
|
||||
mod panels;
|
||||
mod picker;
|
||||
mod sampling;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//! `PaintList` rows with their fields: a typed hex keeps the paint's alpha.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_color::ui::{Paint, PaintList, PaintListEvent, PaintListOptions};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, vec2};
|
||||
|
||||
/// A hex typed into a translucent row's field reports the typed colour with the row's alpha.
|
||||
#[trial]
|
||||
fn a_typed_hex_keeps_the_rows_alpha() {
|
||||
let seen = Rc::new(RefCell::new(Vec::new()));
|
||||
let held = seen.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let paints = [(String::from("Shadow"), Paint::Solid(Srgba::new(0.2, 0.4, 0.6, 0.5))), (String::from("Sunrise"), Paint::None)];
|
||||
let out = PaintList::new("Paints", &paints, Bind::given(None)).options(PaintListOptions::default().hex(true)).show(ui);
|
||||
held.borrow_mut().extend(out.events);
|
||||
});
|
||||
fixture.room(vec2(400.0, 200.0));
|
||||
fixture.settle();
|
||||
let field = fixture.by_label("Color").expect("the solid row has a hex field");
|
||||
fixture.click(&field);
|
||||
fixture.key(Key::A, Modifiers::COMMAND);
|
||||
fixture.type_text("ff0000");
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
let hex = seen.borrow().iter().find_map(|event| match event {
|
||||
PaintListEvent::Hex { row: 0, color } => Some(*color),
|
||||
_ => None,
|
||||
});
|
||||
let hex = hex.unwrap_or_else(|| panic!("the field reports the typed colour: {:?}", seen.borrow()));
|
||||
assert!(hex.r > 0.99 && hex.g < 0.01 && hex.b < 0.01, "the typed colour: {hex:?}");
|
||||
assert!((hex.a - 0.5).abs() < 0.01, "the row's alpha is kept: {hex:?}");
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
//! What the panel's parts share in one pass: the tree, the settings, the thumbnails and the words.
|
||||
|
||||
use craft_ui::list::ListWords;
|
||||
use craft_ui::contract::Show;
|
||||
use craft_ui::list::{ListRow, ListWords};
|
||||
use craft_ui::primitives::textures::{ThumbSource, Thumbnails};
|
||||
use egui::Id;
|
||||
|
||||
use super::LayersPanelWords;
|
||||
use crate::ui::options::LayersOptions;
|
||||
use crate::ui::thumbs::LayerThumb;
|
||||
use crate::ui::tree::{LayerSelection, LayerTree};
|
||||
use crate::ui::tree::{LayerInfo, LayerSelection, LayerTree};
|
||||
use std::cell::RefCell;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
/// The thumbnail cache and the app's source of the rows' pictures.
|
||||
pub(super) struct ThumbHost<'a, Id: Clone + Eq + std::hash::Hash + Send + Sync + 'static> {
|
||||
@@ -23,6 +26,26 @@ impl<Id: Clone + Eq + std::hash::Hash + Send + Sync + 'static> Clone for ThumbHo
|
||||
|
||||
impl<Id: Clone + Eq + std::hash::Hash + Send + Sync + 'static> Copy for ThumbHost<'_, Id> {}
|
||||
|
||||
/// The host's component at each layer row's trailing end (`LayersPanel::trailing`), with its output handed back.
|
||||
pub(super) trait TrailingCell<Id> {
|
||||
/// Adds the cell of the layer `id` to its row.
|
||||
fn add<'r>(&'r self, row: ListRow<'r>, id: &Id, info: &LayerInfo) -> ListRow<'r>;
|
||||
}
|
||||
|
||||
/// A [`TrailingCell`] of the host's `build` and `output`.
|
||||
pub(super) struct HostCell<C, B, O> {
|
||||
pub(super) build: B,
|
||||
pub(super) output: RefCell<O>,
|
||||
pub(super) component: PhantomData<fn() -> C>,
|
||||
}
|
||||
|
||||
impl<Id: Clone + 'static, C: Show, B: Fn(&Id, &LayerInfo) -> C, O: FnMut(&Id, C::Output)> TrailingCell<Id> for HostCell<C, B, O> {
|
||||
fn add<'r>(&'r self, row: ListRow<'r>, id: &Id, info: &LayerInfo) -> ListRow<'r> {
|
||||
let layer = id.clone();
|
||||
row.trailing_field((self.build)(id, info), move |shown| (self.output.borrow_mut())(&layer, shown))
|
||||
}
|
||||
}
|
||||
|
||||
/// The pass's shared state, lent to the row mapping, the drag rules, the footer and the menus.
|
||||
pub(super) struct PanelContext<'a, T: LayerTree> {
|
||||
/// The rows' list, which drags name.
|
||||
@@ -36,4 +59,6 @@ pub(super) struct PanelContext<'a, T: LayerTree> {
|
||||
pub(super) lock_column: bool,
|
||||
/// The app's key that flips the selected layers' eyes.
|
||||
pub(super) visibility_key: Option<craft_keymap::Chord>,
|
||||
/// The host's component at each layer row's trailing end.
|
||||
pub(super) trailing: Option<&'a (dyn TrailingCell<T::Id> + 'a)>,
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ pub use menu::{LayersMenuAction, LayersPanelCommands, LayersPanelKeys, panel_row
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, CommandSet as _, Commands as _, NoValue, Outcome, Show, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::ListWords;
|
||||
use craft_ui::primitives::textures::{ThumbSource, Thumbnails};
|
||||
@@ -31,15 +31,16 @@ use craft_ui::runtime::memory::Remember as _;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use body::{LayerRows, ToggleSweeps, reveal_plan, show_body, start_rename};
|
||||
use context::{PanelContext, ThumbHost};
|
||||
use context::{HostCell, PanelContext, ThumbHost, TrailingCell};
|
||||
use footer::show_footer;
|
||||
use menu::{OpenMenu, RowMenu, show_row_menus};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use super::filter::{LayerFilter, LayerFilterBar};
|
||||
use super::options::LayersSettings;
|
||||
use super::rows::BlendRows;
|
||||
use super::thumbs::LayerThumb;
|
||||
use super::tree::{LayerRowKey, LayerTree};
|
||||
use super::tree::{LayerInfo, LayerRowKey, LayerTree};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the Layers panel's rows, footer and menus. Patterns with `{row}`, `{layer}` and
|
||||
@@ -160,6 +161,7 @@ pub struct LayersPanel<'a, T: LayerTree> {
|
||||
blend_rows: bool,
|
||||
filter_bar: bool,
|
||||
row_menu: Option<Box<RowMenu<'a, T::Id>>>,
|
||||
trailing: Option<Box<dyn TrailingCell<T::Id> + 'a>>,
|
||||
reveal: Option<T::Id>,
|
||||
rename: Option<T::Id>,
|
||||
}
|
||||
@@ -199,6 +201,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
blend_rows: true,
|
||||
filter_bar: true,
|
||||
row_menu: None,
|
||||
trailing: None,
|
||||
reveal: None,
|
||||
rename: None,
|
||||
}
|
||||
@@ -260,6 +263,14 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The host's component at each layer row's trailing end, after the indicators and never dropped for the name
|
||||
/// (Illustrator's target circle, a selection square): `build` makes the layer's component and `output` gets what
|
||||
/// it reports, with the layer, in the pass it is shown.
|
||||
pub fn trailing<C: Show + 'a>(mut self, build: impl Fn(&T::Id, &LayerInfo) -> C + 'a, output: impl FnMut(&T::Id, C::Output) + 'a) -> Self {
|
||||
self.trailing = Some(Box::new(HostCell { build, output: RefCell::new(output), component: PhantomData }));
|
||||
self
|
||||
}
|
||||
|
||||
/// Reveals `layer` this pass: its closed ancestors open ([`LayersEvent::Open`]) and its row
|
||||
/// scrolls into view when hidden. The active layer is revealed by itself when it changes.
|
||||
pub fn reveal(mut self, layer: T::Id) -> Self {
|
||||
@@ -277,8 +288,20 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
/// Draws the panel over the available rect: the filter bar and [`BlendRows`] in the header, the
|
||||
/// rows, the footer. Events are reported in that order.
|
||||
pub fn show(self, ui: &mut Ui) -> LayersOutput<T::Id> {
|
||||
let LayersPanel { tree, settings, thumbnails, mut filter, lock_column, visibility_key, blend_rows, filter_bar, row_menu, reveal, rename } =
|
||||
self;
|
||||
let LayersPanel {
|
||||
tree,
|
||||
settings,
|
||||
thumbnails,
|
||||
mut filter,
|
||||
lock_column,
|
||||
visibility_key,
|
||||
blend_rows,
|
||||
filter_bar,
|
||||
row_menu,
|
||||
trailing,
|
||||
reveal,
|
||||
rename,
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<LayersPanelWords>();
|
||||
let list_words = env.words::<ListWords>();
|
||||
@@ -295,6 +318,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> {
|
||||
list_words: &list_words,
|
||||
lock_column,
|
||||
visibility_key,
|
||||
trailing: trailing.as_deref(),
|
||||
};
|
||||
let events = RefCell::new(Vec::new());
|
||||
let current = RefCell::new(LayerFilter::default());
|
||||
|
||||
@@ -235,6 +235,9 @@ fn layer_row<'r, T: LayerTree>(cx: &'r PanelContext<'r, T>, id: &T::Id) -> ListR
|
||||
if let Some(warning) = info.warning.clone() {
|
||||
row = row.trailing_icon(IconSpec::svg(IconId::new("warning")), warning);
|
||||
}
|
||||
if let Some(cell) = cx.trailing {
|
||||
row = cell.add(row, id, &info);
|
||||
}
|
||||
row.description(row_description(words, &info, active.then_some(cx.selection.target)))
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,10 @@ use egui::Ui;
|
||||
use super::{LayersOutput, LayersPanel};
|
||||
use crate::ui::filter::{FilterBy, LayerFilter};
|
||||
use crate::ui::mock::FakeLayers;
|
||||
use crate::ui::tree::{LayerPart, LayerSelection};
|
||||
use crate::ui::tree::{LayerInfo, LayerPart, LayerSelection};
|
||||
use craft_behavior::IconId;
|
||||
use craft_ui::display::Icon;
|
||||
use craft_ui::primitives::IconSpec;
|
||||
|
||||
/// The sample tree with the masked layer active and its mask targeted.
|
||||
fn selected() -> FakeLayers {
|
||||
@@ -51,6 +54,15 @@ fn layers_panel_filtered(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
/// Illustrator's target circle after each row's indicators: filled while the layer is shown.
|
||||
#[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)]
|
||||
fn layers_panel_target_cell(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = selected();
|
||||
let target = |_: &u32, info: &LayerInfo| Icon::new(IconSpec::svg(IconId::new(if info.visible { "target" } else { "circle" })));
|
||||
let shown = LayersPanel::new(&tree).trailing(target, |_, _| {}).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
#[story(LayersPanel<'static, FakeLayers>, covers = [], drive = Drive::Never)]
|
||||
fn layers_panel_extra_columns(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let tree = selected();
|
||||
|
||||
@@ -101,6 +101,8 @@ pub enum PageListEvent {
|
||||
Go(usize),
|
||||
/// Enter on the lead row, or a double-click on a row.
|
||||
Activate(usize),
|
||||
/// A double-click on a row's number: fit that page or artboard in the window.
|
||||
Fit(usize),
|
||||
/// A name typed in place (F2, a double-click on the name, the context menu's Rename): trimmed, never empty.
|
||||
/// With several rows picked the app gives the name to all of them numbered in list order as `{text}-1`,
|
||||
/// `{text}-2` (VectorCraft `artboards.rs:243`).
|
||||
@@ -131,7 +133,8 @@ pub enum PageListEvent {
|
||||
/// Delete (the button, the Delete key, or rows dropped on it): the picked rows that aren't locked, or the
|
||||
/// dropped rows.
|
||||
Delete(Vec<usize>),
|
||||
/// The options icon of a row.
|
||||
/// The options icon of the active row, or a double-click on another row's (a single click on it makes the row
|
||||
/// active, as a click on the row does).
|
||||
Options(usize),
|
||||
/// The app's menu is asked for.
|
||||
ContextMenu(ContextMenuRequest<usize>),
|
||||
@@ -181,8 +184,9 @@ fn toggle_column(edit: &EditEvent<ToggleEdit<usize>>) -> Option<&ColumnKey> {
|
||||
|
||||
/// The list, built per pass.
|
||||
///
|
||||
/// - Rows are `ListRow`s: the name, an eye and a lock toggle column (sweepable), the options icon as a trailing
|
||||
/// part. The active row is the list's current item and its lead.
|
||||
/// - Rows are `ListRow`s: the number, the name, an eye and a lock toggle column (sweepable), the options icon as a
|
||||
/// trailing part. The active row is the list's current item and its lead. A double click on the number fits the
|
||||
/// row (`Fit`).
|
||||
/// - Pointer, keys, rename and drag are the table's: click activates and picks; Shift-click extends,
|
||||
/// Cmd/Ctrl-click toggles; one Tab stop, up and down move the active row, F2 renames, Enter activates, Delete and
|
||||
/// Backspace delete, Cmd/Ctrl+] and [ move the picked rows, the Menu key and Shift+F10 open the menu.
|
||||
@@ -229,6 +233,8 @@ impl<'a> PageList<'a> {
|
||||
let events = RefCell::new(Vec::new());
|
||||
let list_id: RefCell<Option<Id>> = RefCell::new(None);
|
||||
let order: Vec<usize> = (0..rows.len()).collect();
|
||||
let number = |row: usize| env.format().integer(row as u64 + 1);
|
||||
let widest = number(rows.len().saturating_sub(1));
|
||||
let source = keyed(&order, |&row| row)
|
||||
.with_text(|&row| Cow::Owned(rows[row].name.clone()))
|
||||
.with_toggled(|&row, column| (*column == VISIBLE && !rows[row].hidden) || (*column == LOCKED && rows[row].locked));
|
||||
@@ -276,6 +282,7 @@ impl<'a> PageList<'a> {
|
||||
let options = IconSpec::svg(IconId::new("settings"));
|
||||
ListRow::new(rows[row].name.clone())
|
||||
.cells(icx.cells())
|
||||
.lead_text(number(row), widest.clone())
|
||||
.toggle(ToggleCell::eye(VISIBLE, !rows[row].hidden).name(words.visibility.clone()))
|
||||
.toggle(ToggleCell::lock(LOCKED, rows[row].locked).name(words.locking.clone()))
|
||||
.trailing_part(OPTIONS, TrailingFace::Icon(options), words.options.clone())
|
||||
@@ -312,7 +319,14 @@ impl<'a> PageList<'a> {
|
||||
events.push(PageListEvent::Delete(rows));
|
||||
}
|
||||
}
|
||||
CollectionEvent::Item(row, RowEvent::Trailing { part, .. }) if part == OPTIONS => events.push(PageListEvent::Options(row)),
|
||||
// The press moved the lead, which reported Go: a click opens the options when the row was
|
||||
// already active, or as the second click of a double click.
|
||||
CollectionEvent::Item(row, RowEvent::Trailing { part, clicks, was_lead, .. })
|
||||
if part == OPTIONS && (was_lead || clicks >= 2) =>
|
||||
{
|
||||
events.push(PageListEvent::Options(row));
|
||||
}
|
||||
CollectionEvent::Item(row, RowEvent::LeadClicked { clicks: 2.., .. }) => events.push(PageListEvent::Fit(row)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,25 +7,19 @@ use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_behavior::{DisplayOrder, EditEvent, IconId, ItemSource, Selection, SelectionChange};
|
||||
use craft_theme::Variant;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Selection, SelectionChange};
|
||||
use craft_theme::{ControlSize, Variant};
|
||||
use craft_ui::buttons::{Button, ButtonOutput};
|
||||
use craft_ui::contract::{
|
||||
Bind, BodyCx, CollectionEvent, Held, NoValue, Outcome, Pattern, Props, ReorderMove, ReorderRule, SelectMode, Show as _, ShowCollection as _,
|
||||
ShowContainer as _, clicked,
|
||||
};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::list::{List, ListRow, RowEvent, TrailingFace, TrailingPart};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::list::{List, ListRow};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Response, Ui};
|
||||
|
||||
/// The pressable part that cancels or retries an item.
|
||||
const ACTION: TrailingPart = TrailingPart::new(0);
|
||||
/// The pressable part that removes an item.
|
||||
const REMOVE: TrailingPart = TrailingPart::new(1);
|
||||
|
||||
craft_ui::words! {
|
||||
/// The queue's words, English by default (FilmCraft's).
|
||||
#[non_exhaustive]
|
||||
@@ -191,9 +185,10 @@ pub fn format_eta(env: &Env, time: Duration) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The row of `item`: "source \u{2192} file", the preset and status as its detail, the time left of an encoding
|
||||
/// item, and the row's action buttons.
|
||||
fn queue_row(env: &Env, words: &RenderQueueWords, item: &RenderQueueItem) -> ListRow<'static> {
|
||||
/// The row of `item`: "source \u{2192} file", the preset and status as its detail, an encoding item's progress bar
|
||||
/// under it with its time left at the end, and the row's buttons: Cancel or Retry, then Remove (disabled while
|
||||
/// encoding), whose clicks go to `events`.
|
||||
fn queue_row<'r>(env: &Env, words: &RenderQueueWords, item: &RenderQueueItem, events: &'r RefCell<Vec<RenderQueueEvent>>) -> ListRow<'r> {
|
||||
let format = env.format();
|
||||
let status = match &item.status {
|
||||
RenderStatus::Ready => words.ready.as_str().to_owned(),
|
||||
@@ -205,19 +200,29 @@ fn queue_row(env: &Env, words: &RenderQueueWords, item: &RenderQueueItem) -> Lis
|
||||
RenderStatus::Failed(error) => words.failed.fill(&[("e", error)]),
|
||||
RenderStatus::Cancelled => words.cancelled.as_str().to_owned(),
|
||||
};
|
||||
let mut row = ListRow::new(format!("{} \u{2192} {}", item.source, item.file)).detail(format!("{} \u{b7} {status}", item.preset));
|
||||
if let RenderStatus::Encoding { remaining: Some(time), .. } = item.status {
|
||||
row = row.optional(words.time_left.fill(&[("time", &format_eta(env, time))]));
|
||||
}
|
||||
if !item.status.is_encoding() {
|
||||
row = row.trailing_part(REMOVE, TrailingFace::Icon(IconSpec::svg(IconId::new("trash"))), words.remove.clone());
|
||||
}
|
||||
match item.status {
|
||||
RenderStatus::Ready | RenderStatus::Encoding { .. } => {
|
||||
row.trailing_part(ACTION, TrailingFace::Icon(IconSpec::svg(IconId::new("close"))), words.cancel.clone())
|
||||
let id = item.id;
|
||||
let button = |text: &Label| Button::new(text.clone()).size(ControlSize::Sm);
|
||||
let on_click = move |event: RenderQueueEvent| {
|
||||
move |shown: ButtonOutput| {
|
||||
if clicked(&shown) {
|
||||
events.borrow_mut().push(event);
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut row = ListRow::new(format!("{} \u{2192} {}", item.source, item.file))
|
||||
.detail(format!("{} \u{b7} {status}", item.preset))
|
||||
.trailing_field(button(&words.remove).enabled(!item.status.is_encoding()), on_click(RenderQueueEvent::Remove(id)));
|
||||
row = match item.status {
|
||||
RenderStatus::Ready | RenderStatus::Encoding { .. } => row.trailing_field(button(&words.cancel), on_click(RenderQueueEvent::Cancel(id))),
|
||||
_ => row.trailing_field(button(&words.retry), on_click(RenderQueueEvent::Retry(id))),
|
||||
};
|
||||
if let RenderStatus::Encoding { progress, remaining } = item.status {
|
||||
row = row.progress(progress);
|
||||
if let Some(time) = remaining {
|
||||
row = row.optional(words.time_left.fill(&[("time", &format_eta(env, time))]));
|
||||
}
|
||||
_ => row.trailing_part(ACTION, TrailingFace::Icon(IconSpec::svg(IconId::new("refresh"))), words.retry.clone()),
|
||||
}
|
||||
row
|
||||
}
|
||||
|
||||
/// FilmCraft's export queue (Premiere's queue in Export mode): a `List` of the items, each row "source \u{2192}
|
||||
@@ -269,7 +274,7 @@ impl<'a> RenderQueueList<'a> {
|
||||
.selection(Bind::bound(&mut selected))
|
||||
.show_items(ui, &source, &mut |key, _| {
|
||||
let item = items.iter().find(|item| item.id == *key).expect("the list asks for its own keys");
|
||||
queue_row(&env, &words, item)
|
||||
queue_row(&env, &words, item, &events)
|
||||
});
|
||||
let mut out_events = events.borrow_mut();
|
||||
for event in out.events {
|
||||
@@ -280,15 +285,6 @@ impl<'a> RenderQueueList<'a> {
|
||||
let removable = |key: &RenderItemId| items.iter().any(|item| item.id == *key && !item.status.is_encoding());
|
||||
out_events.extend(keys.into_iter().filter(removable).map(RenderQueueEvent::Remove));
|
||||
}
|
||||
CollectionEvent::Item(key, RowEvent::Trailing { part, .. }) => {
|
||||
let item = items.iter().find(|item| item.id == key);
|
||||
match (part, item.map(|item| &item.status)) {
|
||||
(REMOVE, _) => out_events.push(RenderQueueEvent::Remove(key)),
|
||||
(ACTION, Some(RenderStatus::Ready | RenderStatus::Encoding { .. })) => out_events.push(RenderQueueEvent::Cancel(key)),
|
||||
(ACTION, Some(_)) => out_events.push(RenderQueueEvent::Retry(key)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -544,7 +544,7 @@ impl CollectionProps {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the collection holds a primary press on a row, within slop.
|
||||
/// Where the collection holds a primary press on a row, within slop, or the press a part of the row holds.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RowPressed {
|
||||
@@ -552,6 +552,12 @@ pub enum RowPressed {
|
||||
Row,
|
||||
/// On the cell of this toggle column, which the press flips.
|
||||
Cell(ColumnKey),
|
||||
/// On a part of the item that took the press itself (a row's trailing button).
|
||||
#[non_exhaustive]
|
||||
Part {
|
||||
/// The row held the lead when the press began: a press on a part moves the lead to its row.
|
||||
was_lead: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// What an item reads of its place in the collection; the item step joins it to the item's flags at step 12.
|
||||
|
||||
@@ -167,6 +167,8 @@ pub(super) struct Drags<K> {
|
||||
pub(super) marquee: Option<MarqueeDrag<K>>,
|
||||
/// A plain press on the only selected item of a `slow_click_rename` collection, waiting to become a rename.
|
||||
pub(super) slow: Option<SlowClick<K>>,
|
||||
/// The row a press an item part won landed on, and whether the row held the lead when the press began.
|
||||
pub(super) part_press: Option<(K, bool)>,
|
||||
}
|
||||
|
||||
/// A press that opens a rename when it ends as a click on the item's label and no second press follows within the
|
||||
@@ -195,6 +197,7 @@ impl<K> Default for Drags<K> {
|
||||
command: None,
|
||||
marquee: None,
|
||||
slow: None,
|
||||
part_press: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,11 +156,27 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
&& let Some(at) = layout.hit(local(start.origin), offset).filter(|&at| self.source.enabled(at) && layout.shown(at))
|
||||
&& (target.owner != cx.core.id || target.part.is_some_and(|part| part.key == SECTION))
|
||||
{
|
||||
let key = self.source.key(at);
|
||||
self.drags.part_press = Some((key.clone(), self.lead.key.as_ref() == Some(&key)));
|
||||
self.move_lead(at, LeadSource::Pointer);
|
||||
if props.focus_on_press && !target.sense.intersects(Sense::TAKE_FOCUS | Sense::KEEP_FOCUS) {
|
||||
focus::request_now(&ctx, focus::FocusTarget::Id(cx.core.id));
|
||||
}
|
||||
}
|
||||
// While a part of an item holds the press, and in the pass it ends, the row reads it with whether it held the lead
|
||||
// when the press began.
|
||||
match outcome.phase {
|
||||
Some(PressPhase::Down { .. } | PressPhase::Held { .. } | PressPhase::Release { .. })
|
||||
if outcome.target.is_some_and(|target| target.part.is_some()) =>
|
||||
{
|
||||
if let Some((key, was_lead)) = self.drags.part_press.clone()
|
||||
&& let Some(at) = self.index_of(&key)
|
||||
{
|
||||
self.pressed = Some((at, RowPressed::Part { was_lead }));
|
||||
}
|
||||
}
|
||||
_ => self.drags.part_press = None,
|
||||
}
|
||||
// A click on a row's thumbnail is also a click on the row: the item reports the thumbnail's click and an unmodified click picks
|
||||
// in the same pass.
|
||||
if let (Some(PressPhase::Release { click: true, start, .. }), Some(target)) = (outcome.phase, outcome.target)
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) use thumb::RowThumb;
|
||||
pub(super) use thumb::Thumb;
|
||||
use thumb::ThumbPayload;
|
||||
pub use thumb::{ThumbAspect, ThumbPaint, ThumbSize, ThumbTarget};
|
||||
use trailing::HostedShow;
|
||||
use trailing::{Hosted, Hosting};
|
||||
pub(super) use trailing::{Trailing, TrailingItem};
|
||||
pub use trailing::{TrailingFace, TrailingPart};
|
||||
|
||||
@@ -199,6 +199,8 @@ pub struct ListRow<'a> {
|
||||
pub(super) lead_paint: Option<LeadPaintFn<'a>>,
|
||||
pub(super) thumb: ThumbSize,
|
||||
pub(super) thumb_aspect: ThumbAspect,
|
||||
/// The leading text and the widest text its slot is sized for (`lead_text`).
|
||||
pub(super) lead_text: Option<(Label, Label)>,
|
||||
pub(super) first: Option<ThumbPaint<'a>>,
|
||||
pub(super) extras: Vec<Thumb<'a>>,
|
||||
/// The thumbnail the row's editing is aimed at: framed with corner brackets whether or not the row is selected.
|
||||
@@ -270,6 +272,7 @@ impl<'a> ListRow<'a> {
|
||||
thumb: ThumbSize::None,
|
||||
thumb_aspect: ThumbAspect::SQUARE,
|
||||
first: None,
|
||||
lead_text: None,
|
||||
extras: Vec::new(),
|
||||
target: None,
|
||||
trailing: Vec::new(),
|
||||
@@ -460,14 +463,42 @@ impl<'a> ListRow<'a> {
|
||||
self.trailing_part_revealed(TrailingPart::MENU, TrailingFace::Icon(IconSpec::svg(craft_behavior::IconId::new("more"))), Label::Empty)
|
||||
}
|
||||
|
||||
/// A component at the trailing end, in the width of a short field, that always shows: a field that edits a
|
||||
/// value of the row. The row shows `field` in its slot and hands its output to `output` in the pass it is shown. The
|
||||
/// field's stop joins the row's roving group like the row's focusable parts (Forward from the row enters it, Tab leaves the collection); it takes the keys it
|
||||
/// declares.
|
||||
/// A component at the trailing end, as wide as it measures, that always shows: a field that edits a value of the
|
||||
/// row, or a button. The row shows `field` in its slot and hands its output to `output` in the pass it is shown.
|
||||
/// The field's stop joins the row's roving group like the row's focusable parts (Forward from the row enters it,
|
||||
/// Tab leaves the collection); it takes the keys it declares.
|
||||
#[must_use]
|
||||
pub fn trailing_field<C: Show + 'a>(mut self, field: C, output: impl FnOnce(C::Output) + 'a) -> Self {
|
||||
let show: HostedShow<'a> = Box::new(move |ui, at, rect| output(ui.child(("field", at), rect, field)));
|
||||
self.trailing.push(Trailing { item: TrailingItem::Hosted(Some(show)), optional: false });
|
||||
pub fn trailing_field<C: Show + 'a>(self, field: C, output: impl FnOnce(C::Output) + 'a) -> Self {
|
||||
self.hosted(Hosting { component: field, output, shown: true }, false)
|
||||
}
|
||||
|
||||
/// A component at the trailing end as [`trailing_field`](Self::trailing_field) adds one, that drops out when the
|
||||
/// label would get narrower than its least width with it (a binding's badge).
|
||||
#[must_use]
|
||||
pub fn optional_field<C: Show + 'a>(self, field: C, output: impl FnOnce(C::Output) + 'a) -> Self {
|
||||
self.hosted(Hosting { component: field, output, shown: true }, true)
|
||||
}
|
||||
|
||||
/// Empty room at the trailing end, as wide as `component` measures: a row that lacks a field the other rows have
|
||||
/// keeps the items after it in line with theirs. Nothing is shown.
|
||||
#[must_use]
|
||||
pub fn trailing_space<C: Show + 'a>(self, component: C) -> Self {
|
||||
self.hosted(Hosting { component, output: |_| {}, shown: false }, false)
|
||||
}
|
||||
|
||||
fn hosted(mut self, hosting: impl trailing::HostedItem + 'a, optional: bool) -> Self {
|
||||
let item = Hosted { item: Some(Box::new(hosting)), size: None };
|
||||
self.trailing.push(Trailing { item: TrailingItem::Hosted(item), optional });
|
||||
self
|
||||
}
|
||||
|
||||
/// A short text in the leading slot (a page number), in the detail's role and ink, at the slot's end so the labels
|
||||
/// after it line up: the slot is as wide as `widest` measures. It takes the icon's place; thumbnails replace it.
|
||||
/// A click on it picks the row as a click on the row does and reports [`RowEvent::LeadClicked`]; a double click
|
||||
/// there does not activate the row.
|
||||
#[must_use]
|
||||
pub fn lead_text(mut self, text: impl Into<Label>, widest: impl Into<Label>) -> Self {
|
||||
self.lead_text = Some((text.into(), widest.into()));
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,19 @@ pub enum RowEvent {
|
||||
part: TrailingPart,
|
||||
/// The modifiers held at the click; none for a key activation.
|
||||
mods: Mods,
|
||||
/// The press count of the click, as [`ThumbClicked`](Self::ThumbClicked) counts it.
|
||||
clicks: u32,
|
||||
/// The row held the collection's lead when the press began (a press on a part moves the lead to its row);
|
||||
/// true for a key activation.
|
||||
was_lead: bool,
|
||||
},
|
||||
/// A click landed on the leading text ([`ListRow::lead_text`]); an unmodified click also picked the row.
|
||||
#[non_exhaustive]
|
||||
LeadClicked {
|
||||
/// The modifiers held at the click.
|
||||
mods: Mods,
|
||||
/// The press count of the click, as [`ThumbClicked`](Self::ThumbClicked) counts it.
|
||||
clicks: u32,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -33,9 +33,10 @@ impl ListRow<'_> {
|
||||
icon.color.get_or_insert(cx.resolve(&cx.style.trailing_icon.color));
|
||||
ui.draw().icon(shape, &icon);
|
||||
}
|
||||
TrailingItem::Hosted(show) => {
|
||||
if let Some(show) = show.take() {
|
||||
show(ui, at, Rect::from_center_size(slot.center(), Vec2::new(slot.width(), cx.style.sizes.row)));
|
||||
TrailingItem::Hosted(hosted) => {
|
||||
if let Some(item) = hosted.item.take() {
|
||||
let height = hosted.size.map_or(cx.style.sizes.row, |size| size.ideal.y.min(cx.style.sizes.row));
|
||||
item.show(ui, at, Rect::from_center_size(slot.center(), Vec2::new(slot.width(), height)));
|
||||
}
|
||||
}
|
||||
TrailingItem::Part { part, face, enabled, revealed, .. } => {
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::contract::{ColumnAlign, PartsCx, WordSetCx as _};
|
||||
use crate::list::toggle::ToggleState;
|
||||
use crate::list::words::ListWords;
|
||||
use crate::primitives::{HAlign, TextRun, Wrap};
|
||||
use crate::runtime::env::EnvView;
|
||||
use crate::runtime::env::{EnvView, Label};
|
||||
use crate::style::{StyleCx, TextLook};
|
||||
use craft_behavior::{ColumnKey, Flow};
|
||||
use craft_theme::TypeRole;
|
||||
@@ -26,8 +26,6 @@ pub(super) struct Sizes {
|
||||
pad: f32,
|
||||
pub(super) gap: f32,
|
||||
trailing_pad: f32,
|
||||
/// The width of a hosted field.
|
||||
field: f32,
|
||||
pub(super) min_label: f32,
|
||||
thumbs: [f32; 3],
|
||||
thumb_pad: f32,
|
||||
@@ -54,7 +52,6 @@ impl Sizes {
|
||||
pad: control.pad_x,
|
||||
gap: control.gap,
|
||||
trailing_pad: tokens.space.pad.regular,
|
||||
field: tokens.size.length.short,
|
||||
min_label: MIN_LABEL_HEIGHTS * control.height,
|
||||
thumbs: [thumbs.sm, thumbs.md, thumbs.lg],
|
||||
thumb_pad: tokens.space.gap.stack,
|
||||
@@ -103,6 +100,27 @@ impl ListRow<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A trailing item's width where the row has room, the least it narrows to, and whether it drops out for room.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ItemWidth {
|
||||
pub(super) width: f32,
|
||||
pub(super) least: f32,
|
||||
pub(super) optional: bool,
|
||||
}
|
||||
|
||||
/// The measured widths a row is placed by.
|
||||
pub(super) struct Widths {
|
||||
/// The trailing items' widths.
|
||||
pub(super) items: Vec<ItemWidth>,
|
||||
/// The leading text's slot.
|
||||
pub(super) lead: Option<f32>,
|
||||
}
|
||||
|
||||
/// The run of a leading text, without its colour.
|
||||
pub(super) fn lead_run(text: &Label) -> TextRun<'_> {
|
||||
TextRun::new(text.as_str()).role(TypeRole::Caption)
|
||||
}
|
||||
|
||||
/// The cells of a row that lead and trail its label band.
|
||||
struct Bands {
|
||||
lead: f32,
|
||||
@@ -128,7 +146,10 @@ pub(super) struct Placed {
|
||||
pub(super) extras: Vec<(Rect, Option<Rect>)>,
|
||||
pub(super) label: Rect,
|
||||
pub(super) items: Vec<Option<Rect>>,
|
||||
/// The row's least width: the label at its least, the required items at theirs.
|
||||
pub(super) min_width: f32,
|
||||
/// The row's least width with the required items at their widths where the row has room.
|
||||
pub(super) ideal_width: f32,
|
||||
}
|
||||
|
||||
impl ListRow<'_> {
|
||||
@@ -142,14 +163,16 @@ impl ListRow<'_> {
|
||||
self.first.is_some() && sizes.side(self.thumb) > 0.0
|
||||
}
|
||||
|
||||
/// The width of the leading part: every thumbnail and what is between them, or the icon; `None` for a row with
|
||||
/// neither.
|
||||
fn leading(&self, sizes: &Sizes) -> Option<f32> {
|
||||
/// The width of the leading part: every thumbnail and what is between them, the leading text's slot, or the icon;
|
||||
/// `None` for a row with none of them.
|
||||
fn leading(&self, sizes: &Sizes, widths: &Widths) -> Option<f32> {
|
||||
let side = sizes.side(self.thumb);
|
||||
if self.shows_thumbs(sizes) {
|
||||
let first = self.thumb_aspect.of(side);
|
||||
let between = |extra: &Thumb<'_>| if extra.link.is_some() { sizes.icon } else { sizes.gap };
|
||||
Some(first + self.extras.iter().map(|extra| first + between(extra)).sum::<f32>())
|
||||
} else if let Some(lead) = widths.lead {
|
||||
Some(lead)
|
||||
} else {
|
||||
(self.icon.is_some() || self.lead_paint.is_some()).then_some(sizes.icon)
|
||||
}
|
||||
@@ -218,14 +241,28 @@ impl ListRow<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The widths of the trailing items: as `text_width` measures a text, the icon side for the others.
|
||||
pub(super) fn item_widths(&self, sizes: &Sizes, text_width: &dyn Fn(&TextRun<'_>) -> f32) -> Vec<(f32, bool)> {
|
||||
/// The widths of the trailing items and the leading text's slot: as `text_width` measures a text, the icon side for
|
||||
/// icons and parts, and a hosted component's measured width.
|
||||
pub(super) fn widths(&self, sizes: &Sizes, text_width: &dyn Fn(&TextRun<'_>) -> f32) -> Widths {
|
||||
let width = |item: &TrailingItem| match item {
|
||||
TrailingItem::Text { text, .. } => text_width(&trailing_run(text)),
|
||||
TrailingItem::Icon { .. } | TrailingItem::Part { .. } => sizes.icon,
|
||||
TrailingItem::Hosted(_) => sizes.field,
|
||||
TrailingItem::Hosted(hosted) => hosted.size.map_or(0.0, |size| size.ideal.x),
|
||||
};
|
||||
self.trailing.iter().map(|trailing| (width(&trailing.item), trailing.optional)).collect()
|
||||
let least = |item: &TrailingItem, width: f32| match item {
|
||||
TrailingItem::Hosted(hosted) => hosted.size.map_or(width, |size| size.least.min(width)),
|
||||
_ => width,
|
||||
};
|
||||
let items = self
|
||||
.trailing
|
||||
.iter()
|
||||
.map(|trailing| {
|
||||
let width = width(&trailing.item);
|
||||
ItemWidth { width, least: least(&trailing.item, width), optional: trailing.optional }
|
||||
})
|
||||
.collect();
|
||||
let lead = self.lead_text.as_ref().map(|(_, widest)| text_width(&lead_run(widest)));
|
||||
Widths { items, lead }
|
||||
}
|
||||
|
||||
/// The indent a row asks for before it gives way to the label's least width.
|
||||
@@ -289,22 +326,23 @@ impl ListRow<'_> {
|
||||
if self.muted.contains(column) { &style.cell_muted } else { &style.cell }
|
||||
}
|
||||
|
||||
pub(super) fn place(&self, sizes: &Sizes, items: &[(f32, bool)], rect: Rect, rtl: bool) -> Placed {
|
||||
pub(super) fn place(&self, sizes: &Sizes, widths: &Widths, rect: Rect, rtl: bool) -> Placed {
|
||||
if !self.space_above {
|
||||
return self.place_in(&self.cells, sizes, items, rect, rtl);
|
||||
return self.place_in(&self.cells, sizes, widths, rect, rtl);
|
||||
}
|
||||
let below = |rect: Rect| Rect::from_min_max(Pos2::new(rect.left(), (rect.top() + sizes.gap_row).min(rect.bottom())), rect.max);
|
||||
let cells: Vec<_> = self.cells.iter().map(|(column, rect)| (column.clone(), below(*rect))).collect();
|
||||
self.place_in(&cells, sizes, items, below(rect), rtl)
|
||||
self.place_in(&cells, sizes, widths, below(rect), rtl)
|
||||
}
|
||||
|
||||
pub(super) fn place_in(&self, cells_of: &[(ColumnKey, Rect)], sizes: &Sizes, items: &[(f32, bool)], rect: Rect, rtl: bool) -> Placed {
|
||||
pub(super) fn place_in(&self, cells_of: &[(ColumnKey, Rect)], sizes: &Sizes, widths: &Widths, rect: Rect, rtl: bool) -> Placed {
|
||||
let items = &widths.items;
|
||||
let Bands { lead, trail, toggles: cells, texts } = self.bands(cells_of, rect, rtl);
|
||||
let flow = Flow::new(rect, rtl);
|
||||
let band_width = (rect.width() - lead - trail).max(0.0);
|
||||
let band = flow.span(lead, band_width);
|
||||
let inner = Flow::new(band, rtl);
|
||||
let leading = self.leading(sizes);
|
||||
let leading = self.leading(sizes, widths);
|
||||
let leading_width = leading.map_or(0.0, |side| side + sizes.gap);
|
||||
let disclosure = if self.group.is_some() { sizes.icon } else { 0.0 };
|
||||
let marker = if self.clipped { sizes.icon } else { 0.0 };
|
||||
@@ -313,15 +351,21 @@ impl ListRow<'_> {
|
||||
let base = sizes.pad;
|
||||
let indent_full = self.indent_full(sizes);
|
||||
let end = band_width - sizes.trailing_pad;
|
||||
let required: f32 = items.iter().filter(|(_, optional)| !optional).map(|(width, _)| width + sizes.gap).sum();
|
||||
let required: f32 = items.iter().filter(|item| !item.optional).map(|item| item.width + sizes.gap).sum();
|
||||
let mut used = required;
|
||||
let mut kept: Vec<bool> = items.iter().map(|(_, optional)| !optional).collect();
|
||||
for (at, (width, optional)) in items.iter().enumerate() {
|
||||
if *optional && end - (used + width + sizes.gap) - (base + indent_full + column + leading_width) >= sizes.min_label {
|
||||
let mut kept: Vec<bool> = items.iter().map(|item| !item.optional).collect();
|
||||
for (at, item) in items.iter().enumerate() {
|
||||
if item.optional && end - (used + item.width + sizes.gap) - (base + indent_full + column + leading_width) >= sizes.min_label {
|
||||
kept[at] = true;
|
||||
used += width + sizes.gap;
|
||||
used += item.width + sizes.gap;
|
||||
}
|
||||
}
|
||||
// A row that lacks room for the label's least width narrows its hosted fields toward their least widths, each
|
||||
// by the same share of what it can give.
|
||||
let lack = (base + indent_full + column + leading_width + sizes.min_label - (end - used)).max(0.0);
|
||||
let give: f32 = items.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(item, _)| item.width - item.least).sum();
|
||||
let share = if give > 0.0 { (lack / give).min(1.0) } else { 0.0 };
|
||||
used -= give * share;
|
||||
let label_end = end - used;
|
||||
let overflow = (base + column + leading_width + sizes.min_label - label_end).max(0.0);
|
||||
let label_end = label_end + overflow;
|
||||
@@ -330,11 +374,12 @@ impl ListRow<'_> {
|
||||
let items = items
|
||||
.iter()
|
||||
.zip(&kept)
|
||||
.map(|((width, _), kept)| {
|
||||
.map(|(item, kept)| {
|
||||
kept.then(|| {
|
||||
let width = item.width - (item.width - item.least) * share;
|
||||
let start = end - from_end - width + overflow;
|
||||
from_end += width + sizes.gap;
|
||||
inner.span(start, *width)
|
||||
inner.span(start, width)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -365,7 +410,9 @@ impl ListRow<'_> {
|
||||
let toggles = cells.iter().map(|(at, cell, _)| (*at, *cell)).collect();
|
||||
let texts = texts.iter().map(|(at, position, cell, _)| (*at, *position, *cell)).collect();
|
||||
let dividers = cells.iter().filter(|(_, _, leading)| *leading).map(|(_, cell, _)| if rtl { cell.left() } else { cell.right() }).collect();
|
||||
let min_width = lead + trail + base + column + leading_width + sizes.min_label + required + sizes.trailing_pad;
|
||||
let least: f32 = widths.items.iter().filter(|item| !item.optional).map(|item| item.least + sizes.gap).sum();
|
||||
let min_width = lead + trail + base + column + leading_width + sizes.min_label + least + sizes.trailing_pad;
|
||||
let ideal_width = min_width - least + required;
|
||||
Placed {
|
||||
toggles,
|
||||
texts,
|
||||
@@ -379,6 +426,7 @@ impl ListRow<'_> {
|
||||
label: inner.span(label_start, (label_end - label_start).max(0.0)),
|
||||
items,
|
||||
min_width,
|
||||
ideal_width,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -398,7 +446,6 @@ pub fn placement_under_fixed_sizes(row: &ListRow<'_>, width: f32, rtl: bool) ->
|
||||
pad: 6.0,
|
||||
gap: 4.0,
|
||||
trailing_pad: 8.0,
|
||||
field: 64.0,
|
||||
min_label: 60.0,
|
||||
thumbs: [24.0, 32.0, 48.0],
|
||||
thumb_pad: 4.0,
|
||||
@@ -410,8 +457,8 @@ pub fn placement_under_fixed_sizes(row: &ListRow<'_>, width: f32, rtl: bool) ->
|
||||
cell_inset: 6.0,
|
||||
cell_pad: 4.0,
|
||||
};
|
||||
let items = row.item_widths(&sizes, &|run| FIXED_ADVANCE * run.full_text().chars().count() as f32);
|
||||
let placed = row.place(&sizes, &items, Rect::from_min_size(Pos2::ZERO, Vec2::new(width, sizes.row)), rtl);
|
||||
let widths = row.widths(&sizes, &|run| FIXED_ADVANCE * run.full_text().chars().count() as f32);
|
||||
let placed = row.place(&sizes, &widths, Rect::from_min_size(Pos2::ZERO, Vec2::new(width, sizes.row)), rtl);
|
||||
RowPlacement { label: placed.label, items: placed.items, disclosure: placed.disclosure, min_label: sizes.min_label }
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::ListRowStyleKey;
|
||||
use super::output::{RowEvent, RowOutput};
|
||||
use super::paint::draw_clip_arrow;
|
||||
use super::placement::Sizes;
|
||||
use super::placement::{Sizes, lead_run};
|
||||
use super::style::{FillKey, ListRowStyle, RowForm, fill_of, row_ink_of, selected_outline};
|
||||
use super::thumb::{RowThumb, target_at};
|
||||
use super::trailing::{TrailingFace, TrailingItem, TrailingPart};
|
||||
@@ -39,6 +39,7 @@ pub(super) const TRAILING: PartKey = PartKey::new("trailing");
|
||||
const TRAILING_ICON: PartKey = PartKey::new("trailing-icon");
|
||||
const TRAILING_TEXT: PartKey = PartKey::new("trailing-text");
|
||||
pub(super) const THUMB: PartKey = PartKey::new("thumb");
|
||||
const LEAD: PartKey = PartKey::new("lead");
|
||||
|
||||
/// The name a pattern with `{row}` gives for the row labelled `row`.
|
||||
pub(super) fn named(pattern: &Label, row: &str) -> String {
|
||||
@@ -121,7 +122,8 @@ impl Component for ListRow<'_> {
|
||||
let room = cx.room.unwrap_or(0.0);
|
||||
let columns = self.toggles.iter().map(|toggle| &toggle.column).chain(self.texts.iter().map(|text| &text.column));
|
||||
let toggles: f32 = columns.filter_map(|key| self.cells.iter().find(|(column, _)| column == key)).map(|(_, cell)| cell.width()).sum();
|
||||
let widths = self.item_widths(sizes, &|run| cx.layout_at(run, f32::INFINITY).size().x);
|
||||
self.measure_hosted(cx);
|
||||
let widths = self.widths(sizes, &|run| cx.layout_at(run, f32::INFINITY).size().x);
|
||||
let probe = self.place_in(&[], sizes, &widths, Rect::from_min_size(Pos2::ZERO, Vec2::new(room, height)), rtl);
|
||||
let probe_min = probe.min_width + toggles;
|
||||
let band = cx.room.map_or(f32::INFINITY, |_| (probe.label.width() - toggles).max(0.0));
|
||||
@@ -151,7 +153,7 @@ impl Component for ListRow<'_> {
|
||||
Some(detail) => label.max(cx.layout(&TextRun::new(detail.as_str()).role(cx.style.detail.role)).size().x),
|
||||
None => label,
|
||||
};
|
||||
Vec2::new(probe_min - sizes.min_label + label.max(sizes.min_label) + self.indent_full(sizes), height)
|
||||
Vec2::new(probe.ideal_width + toggles - sizes.min_label + label.max(sizes.min_label) + self.indent_full(sizes), height)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
@@ -164,7 +166,8 @@ impl Component for ListRow<'_> {
|
||||
return;
|
||||
}
|
||||
self.adopt_toggle_columns(&cx.env, cx.resolved.id);
|
||||
let widths = self.item_widths(&cx.style.sizes, &|run| cx.layout_at(run, f32::INFINITY).size().x);
|
||||
self.measure_hosted(cx);
|
||||
let widths = self.widths(&cx.style.sizes, &|run| cx.layout_at(run, f32::INFINITY).size().x);
|
||||
let placed = self.place(&cx.style.sizes, &widths, rect, cx.flow.is_rtl());
|
||||
for (at, cell) in &placed.toggles {
|
||||
let toggle = &self.toggles[*at];
|
||||
@@ -264,6 +267,10 @@ impl Component for ListRow<'_> {
|
||||
if self.drags.iter().any(|(held, _)| *held == target_at(at)) { Sense::CLICK | Sense::DRAG } else { Sense::CLICK } | Sense::PICKS_ITEM;
|
||||
cx.part(THUMB.at(at as u64), thumb).sense(sense).pointer_only("A thumbnail is a pointer target; the keys act on the row");
|
||||
}
|
||||
if let (Some(slot), Some(_)) = (placed.icon, &self.lead_text) {
|
||||
let rect = Rect::from_x_y_ranges(slot.x_range(), rect.y_range());
|
||||
cx.part(LEAD, rect).sense(Sense::CLICK | Sense::PICKS_ITEM).pointer_only("The leading text is a pointer target; the keys act on the row");
|
||||
}
|
||||
}
|
||||
|
||||
fn flags(&self) -> Flags {
|
||||
@@ -298,13 +305,16 @@ impl Component for ListRow<'_> {
|
||||
crate::runtime::drag::start(&cx.ctx, cx.id, payload.clone(), None, preview);
|
||||
self.event = Some(RowEvent::ThumbDrag(target));
|
||||
} else if let Some(source) = cx.part_activated(THUMB.at(at as u64)) {
|
||||
let clicks = match (source, phase) {
|
||||
(FireSource::Pointer, PressPhase::Release { start, click: true, .. }) => start.clicks,
|
||||
_ => 1,
|
||||
};
|
||||
let clicks = part_clicks(source, phase);
|
||||
self.event = Some(RowEvent::ThumbClicked { target, mods: part_mods(cx, THUMB.at(at as u64), source), clicks });
|
||||
}
|
||||
}
|
||||
if self.lead_text.is_some()
|
||||
&& let Some(source) = cx.part_activated(LEAD)
|
||||
{
|
||||
self.event =
|
||||
Some(RowEvent::LeadClicked { mods: part_mods(cx, LEAD.into(), source), clicks: part_clicks(source, cx.part(LEAD).press.phase) });
|
||||
}
|
||||
for trailing in &self.trailing {
|
||||
let TrailingItem::Part { part, .. } = &trailing.item else { continue };
|
||||
let key = TRAILING.at(u64::from(part.0));
|
||||
@@ -312,7 +322,13 @@ impl Component for ListRow<'_> {
|
||||
if *part == TrailingPart::MENU {
|
||||
self.menu = Some(cx.part(key).rect.left_bottom());
|
||||
} else {
|
||||
self.event = Some(RowEvent::Trailing { part: *part, mods: part_mods(cx, key, source) });
|
||||
let clicks = part_clicks(source, cx.part(key).press.phase);
|
||||
let was_lead = match (source, &self.pressed) {
|
||||
(FireSource::Pointer, Some(RowPressed::Part { was_lead, .. })) => *was_lead,
|
||||
(FireSource::Pointer, _) => false,
|
||||
_ => true,
|
||||
};
|
||||
self.event = Some(RowEvent::Trailing { part: *part, mods: part_mods(cx, key, source), clicks, was_lead });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -357,6 +373,9 @@ impl Component for ListRow<'_> {
|
||||
} else if self.option {
|
||||
access.role(Role::LIST_BOX_OPTION);
|
||||
}
|
||||
if self.progress.is_some() {
|
||||
access.node(PROGRESS, Role::PROGRESS_INDICATOR).name = Name::Text(label.to_owned());
|
||||
}
|
||||
if let Some(open) = self.group {
|
||||
access.expanded(open);
|
||||
let pattern = if open { &words.collapse } else { &words.expand };
|
||||
@@ -420,7 +439,7 @@ impl Component for ListRow<'_> {
|
||||
let sizes = &style.sizes;
|
||||
let rtl = cx.env.direction().is_rtl();
|
||||
let rect = cx.rect;
|
||||
let widths = self.item_widths(sizes, &|run| ui.draw().layout(run, f32::INFINITY).size().x);
|
||||
let widths = self.widths(sizes, &|run| ui.draw().layout(run, f32::INFINITY).size().x);
|
||||
let placed = self.place(sizes, &widths, rect, rtl);
|
||||
self.label_rect = placed.label;
|
||||
{
|
||||
@@ -434,10 +453,16 @@ impl Component for ListRow<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let lead_painted = self.lead_paint.is_some();
|
||||
let lead_painted = self.lead_paint.is_some() || self.lead_text.is_some();
|
||||
self.paint_toggles(ui, cx, &placed);
|
||||
let ink = cx.resolve(&style.text.color);
|
||||
if let (Some(slot), Some(paint)) = (placed.icon, self.lead_paint.take()) {
|
||||
if let (Some(slot), Some((text, _))) = (placed.icon, &self.lead_text) {
|
||||
let draw = ui.draw();
|
||||
let run = lead_run(text).color(cx.resolve(&style.detail.color));
|
||||
let shown = draw.layout(&run, slot.width());
|
||||
let x = if rtl { slot.left() } else { slot.right() - shown.size().x };
|
||||
draw.galley(Pos2::new(x, slot.center().y - shown.size().y / 2.0), &shown);
|
||||
} else if let (Some(slot), Some(paint)) = (placed.icon, self.lead_paint.take()) {
|
||||
let _ = ui.child("lead", Rect::from_x_y_ranges(slot.x_range(), rect.y_range()), RowThumb::new(paint));
|
||||
}
|
||||
if let Some(open) = self.group
|
||||
@@ -475,6 +500,14 @@ impl Component for ListRow<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The press count of an activation: the click's count for a pointer click, 1 for a key or AccessKit activation.
|
||||
fn part_clicks(source: FireSource, phase: PressPhase) -> u32 {
|
||||
match (source, phase) {
|
||||
(FireSource::Pointer, PressPhase::Release { start, click: true, .. }) => start.clicks,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The modifiers of an activation of `part`: those held at a click, none for a key or AccessKit activation.
|
||||
fn part_mods(cx: &Cx<'_, ListRow<'_>>, part: PartRef, source: FireSource) -> Mods {
|
||||
match source {
|
||||
@@ -484,6 +517,18 @@ fn part_mods(cx: &Cx<'_, ListRow<'_>>, part: PartRef, source: FireSource) -> Mod
|
||||
}
|
||||
|
||||
impl ListRow<'_> {
|
||||
/// Measures each hosted trailing component not yet measured in this pass, for its slot.
|
||||
fn measure_hosted(&mut self, cx: &MeasureCx<'_, Self>) {
|
||||
for (at, trailing) in self.trailing.iter_mut().enumerate() {
|
||||
if let TrailingItem::Hosted(hosted) = &mut trailing.item
|
||||
&& hosted.size.is_none()
|
||||
&& let Some(item) = hosted.item.as_mut()
|
||||
{
|
||||
hosted.size = Some(item.measure(cx, at));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the trailing part `part`: the one given, or "More ({row})" for the row's menu button.
|
||||
fn part_name(&self, part: TrailingPart, name: &Label, words: &ListWords, row: &str) -> Label {
|
||||
if part == TrailingPart::MENU { Label::from(named(&words.more, row)) } else { name.clone() }
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! A row's trailing items: texts, pressable parts and hosted components.
|
||||
|
||||
use crate::contract::PaintUi;
|
||||
use super::ListRow;
|
||||
use crate::contract::{MeasureCx, PaintUi, Show};
|
||||
use crate::primitives::{IconSpec, Span, TextRun};
|
||||
use crate::runtime::env::Label;
|
||||
use craft_behavior::Proposal;
|
||||
use craft_theme::TypeRole;
|
||||
use egui::Rect;
|
||||
use egui::{Rect, Vec2};
|
||||
|
||||
/// The key of a pressable trailing item, chosen by the caller: a row's parts are told apart by it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -42,8 +44,49 @@ impl TrailingFace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a hosted component at the rect the row gives it; the index is the item's place among the trailing items.
|
||||
pub(super) type HostedShow<'a> = Box<dyn FnOnce(&mut PaintUi<'_>, usize, Rect) + 'a>;
|
||||
/// A component a row hosts at its trailing end, erased: measured for its slot, then shown once.
|
||||
pub(in crate::list) trait HostedItem {
|
||||
/// The component's size at its ideal and the least width it narrows to, as `PaintUi::child` will show it under the
|
||||
/// key of trailing item `at`.
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, ListRow<'_>>, at: usize) -> HostedSize;
|
||||
|
||||
/// Shows the component at `rect` and hands its output on.
|
||||
fn show(self: Box<Self>, ui: &mut PaintUi<'_>, at: usize, rect: Rect);
|
||||
}
|
||||
|
||||
/// A hosted component and what takes its output; `shown` false keeps its slot empty.
|
||||
pub(super) struct Hosting<C, F> {
|
||||
pub component: C,
|
||||
pub output: F,
|
||||
pub shown: bool,
|
||||
}
|
||||
|
||||
impl<C: Show, F: FnOnce(C::Output)> HostedItem for Hosting<C, F> {
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, ListRow<'_>>, at: usize) -> HostedSize {
|
||||
let ideal = cx.child(("field", at), &mut self.component, Proposal::Ideal);
|
||||
let least = cx.child(("field", at), &mut self.component, Proposal::Min).x;
|
||||
HostedSize { ideal, least }
|
||||
}
|
||||
|
||||
fn show(self: Box<Self>, ui: &mut PaintUi<'_>, at: usize, rect: Rect) {
|
||||
if self.shown {
|
||||
(self.output)(ui.child(("field", at), rect, self.component));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hosted component's size where the row has room, and the least width it narrows to where it has not.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::list) struct HostedSize {
|
||||
pub ideal: Vec2,
|
||||
pub least: f32,
|
||||
}
|
||||
|
||||
/// A hosted item: the component until it is shown, and its size once measured in this pass.
|
||||
pub(in crate::list) struct Hosted<'a> {
|
||||
pub item: Option<Box<dyn HostedItem + 'a>>,
|
||||
pub size: Option<HostedSize>,
|
||||
}
|
||||
|
||||
/// What a trailing item is.
|
||||
pub(in crate::list) enum TrailingItem<'a> {
|
||||
@@ -54,11 +97,12 @@ pub(in crate::list) enum TrailingItem<'a> {
|
||||
/// A pressable face of the row's icon size; a `revealed` one shows only on a hovered or selected row, while it has
|
||||
/// focus or while the menu it opens is open.
|
||||
Part { part: TrailingPart, face: TrailingFace, name: Label, enabled: bool, revealed: bool },
|
||||
/// A component of its own, shown in a short field's width; its stop joins the row's group and it takes its own keys.
|
||||
Hosted(Option<HostedShow<'a>>),
|
||||
/// A component of its own, in a slot as wide as it measures; its stop joins the row's group and it takes its own
|
||||
/// keys.
|
||||
Hosted(Hosted<'a>),
|
||||
}
|
||||
|
||||
/// A trailing item and whether it drops out for room; only a text can be optional.
|
||||
/// A trailing item and whether it drops out for room.
|
||||
pub(in crate::list) struct Trailing<'a> {
|
||||
pub item: TrailingItem<'a>,
|
||||
pub optional: bool,
|
||||
|
||||
@@ -155,3 +155,84 @@ fn a_click_on_the_selected_event_deselects_it() {
|
||||
"selected, then deselected: {changes:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A list of the three rows built by `row`, in `room`, and what it reported.
|
||||
fn rows_rig(room: Vec2, row: fn(usize) -> ListRow<'static>) -> (Fixture, Rc<RefCell<Vec<CollectionEvent<usize, RowEvent>>>>) {
|
||||
let seen = Rc::new(RefCell::new(Vec::new()));
|
||||
let held = seen.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let keys = [0_usize, 1, 2];
|
||||
let source = keyed(&keys, |key: &usize| *key).with_text(|key| std::borrow::Cow::Borrowed(NAMES[*key]));
|
||||
let out = List::new("Artboards").show_items(ui, &source, &mut |key, _| row(*key));
|
||||
held.borrow_mut().extend(out.events);
|
||||
});
|
||||
fixture.room(room);
|
||||
fixture.settle();
|
||||
(fixture, seen)
|
||||
}
|
||||
|
||||
/// A hosted component's slot is as wide as it measures; in a narrow list an optional one drops out, and a field
|
||||
/// narrows toward its least width so the row stays inside the list.
|
||||
#[trial]
|
||||
fn hosted_items_take_their_own_width_and_an_optional_one_drops_first() {
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::display::Badge;
|
||||
let row = |key: usize| {
|
||||
ListRow::new(NAMES[key])
|
||||
.trailing_field(Button::new("Apply to every page"), |_| {})
|
||||
.trailing_field(Button::new("OK"), |_| {})
|
||||
.trailing_field(craft_ui::text::HexField::hex("Color", craft_ui::contract::Bind::given(craft_theme::Rgba::rgb(0, 0, 0))), |_| {})
|
||||
.optional_field(Badge::new("Primary"), |_| {})
|
||||
};
|
||||
let (fixture, _) = rows_rig(Vec2::new(800.0, 200.0), row);
|
||||
let short = fixture.by_label("OK").expect("the short button shows");
|
||||
let long = fixture.by_label("Apply to every page").expect("the long button shows");
|
||||
assert!(long.rect.width() > short.rect.width(), "the long label's button is wider: {:?} {:?}", long.rect, short.rect);
|
||||
assert!(!long.rect.intersects(short.rect), "the slots do not overlap");
|
||||
assert!(fixture.by_label("Primary").is_some(), "the optional badge shows in a wide list");
|
||||
let wide_field = fixture.by_label("Color").expect("the field shows").rect;
|
||||
let (narrow, _) = rows_rig(Vec2::new(360.0, 200.0), row);
|
||||
assert!(narrow.by_label("Primary").is_none(), "the optional badge drops out in a narrow list");
|
||||
assert!(narrow.by_label("OK").is_some(), "the required button stays");
|
||||
let (field, row_rect) = (narrow.by_label("Color").expect("the field stays").rect, narrow.by_label(NAMES[0]).expect("the row shows").rect);
|
||||
assert!(field.width() < wide_field.width(), "the field narrows: {field:?} from {wide_field:?}");
|
||||
assert!(field.right() <= row_rect.right() + 0.5, "the row's items stay inside it: {field:?} in {row_rect:?}");
|
||||
}
|
||||
|
||||
/// A double click on a row's leading text reports it with its count and does not activate the row; a click on a
|
||||
/// trailing part reports whether its row held the lead when the press began.
|
||||
#[trial]
|
||||
fn the_leading_text_takes_its_double_click_and_a_part_click_tells_whether_its_row_was_the_lead() {
|
||||
use craft_ui::list::{TrailingFace, TrailingPart};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
const NUMBERS: [&str; 3] = ["Options 1", "Options 2", "Options 3"];
|
||||
let row = |key: usize| {
|
||||
ListRow::new(NAMES[key]).lead_text((key + 1).to_string(), "000000").trailing_part(
|
||||
TrailingPart::new(0),
|
||||
TrailingFace::Icon(IconSpec::svg(craft_behavior::IconId::new("settings"))),
|
||||
NUMBERS[key],
|
||||
)
|
||||
};
|
||||
let (mut fixture, seen) = rows_rig(Vec2::new(320.0, 200.0), row);
|
||||
let first = fixture.by_label(NAMES[0]).expect("the row has a node").rect;
|
||||
let number = egui::Pos2::new(first.left() + 20.0, first.center().y);
|
||||
fixture.click_at(number).click_at(number).settle();
|
||||
{
|
||||
let seen = seen.borrow();
|
||||
assert!(seen.iter().any(|event| matches!(event, CollectionEvent::Item(0, RowEvent::LeadClicked { clicks: 2, .. }))), "{seen:?}");
|
||||
assert!(!seen.iter().any(|event| matches!(event, CollectionEvent::Activate(_))), "no activation: {seen:?}");
|
||||
}
|
||||
let was_lead = |seen: &Rc<RefCell<Vec<CollectionEvent<usize, RowEvent>>>>| {
|
||||
seen.borrow().iter().rev().find_map(|event| match event {
|
||||
CollectionEvent::Item(2, RowEvent::Trailing { was_lead, .. }) => Some(*was_lead),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
fixture.advance(1.0).idle(1);
|
||||
let options = fixture.by_label(NUMBERS[2]).expect("the part has a node").center();
|
||||
fixture.click_at(options).settle();
|
||||
assert_eq!(was_lead(&seen), Some(false), "the first click lands on a row that was not the lead");
|
||||
fixture.advance(1.0).idle(1);
|
||||
fixture.click_at(options).settle();
|
||||
assert_eq!(was_lead(&seen), Some(true), "the press moved the lead there, so the next click finds it the lead");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user