dialogs-w8: net change of 4 commits

- dialogs-w8: written from its sheet
- dialogs-w8: repair 1
- dialogs-w8: review fixes (review-1)
- dialogs-w8: review fixes (review-1b)
This commit is contained in:
Martin Ball
2026-11-18 18:18:25 +00:00
parent 5fd18885f9
commit 7a9799d655
13 changed files with 387 additions and 46 deletions
@@ -111,9 +111,9 @@ pub struct ColumnRemove {
impl ColumnSpec {
/// The column gets a remove control named `name` at its header's end, disabled unless `enabled`.
#[must_use]
pub fn removable(self, name: impl Into<Label>, enabled: bool) -> Self {
let _ = (name.into(), enabled);
todo!("dg.F22")
pub fn removable(mut self, name: impl Into<Label>, enabled: bool) -> Self {
self.remove = Some(ColumnRemove { name: name.into(), enabled });
self
}
/// A content column with a header and a width; the other settings off.
+148 -20
View File
@@ -11,7 +11,8 @@ use crate::contract::{
Collection, Common, Component, Cx, DragPreview, DropMark, DropTarget, Focus as _, MeasureCx, PaintUi, PartsCx, Pointer as _, Props as _, Role,
Show as _, WordSetCx as _,
};
use crate::primitives::{DataWidth, PaintShape};
use crate::primitives::{DataMode, DataWidth, PaintShape};
use crate::runtime::access::{Name, SubDecl, SubNode, report_sub};
use crate::primitives::{IconSpec, TextRun};
use crate::runtime::access::items::{HeaderCell, report_header};
use crate::runtime::commands::{self, CommandRef, CommandSet, CommandState};
@@ -34,6 +35,8 @@ const HEADER: PartKey = PartKey::new("header");
const GRIP: PartKey = PartKey::new("header_grip");
/// The empty header after the last column: a secondary click on it asks for the header menu.
const ROOM: PartKey = PartKey::new("header_room");
/// A column's remove control at the end of its header cell.
const REMOVE: PartKey = PartKey::new("header_remove");
/// The narrowest a resized column gets, in control heights.
const MIN_COLUMN: f32 = 2.0;
@@ -139,6 +142,8 @@ struct Cell {
spec: usize,
rect: Rect,
hash: u64,
/// The remove control's rect inside the cell, for a column with one.
remove: Option<Rect>,
}
#[derive(Default)]
@@ -149,6 +154,9 @@ pub(super) struct Header {
/// The collection binds its column layout (`column_layout`): the binding holds the arrangement, not the memory.
bound: bool,
specs: Vec<ColumnSpec>,
/// The columns whose header cell the collection hosts a component in (`Collection::hosts_header`): they paint no
/// label and are no sort target.
hosted: Vec<ColumnKey>,
/// The widest cell of each `Content` column among all rows, or its header label when wider, from the items'
/// measure of this pass (`content_id`); zero for the other columns and while unknown.
content: Vec<f32>,
@@ -185,7 +193,8 @@ fn hash_of(key: &ColumnKey) -> u64 {
impl Header {
/// Step 4: the columns in their display order and the header's session memory. A `bound` layout (the
/// collection's `column_layout`) is the arrangement; the session memory keeps the menu and the resizes.
pub(super) fn read(&mut self, stage: &mut MemoryStage, id: Id, props: &CollectionProps, bound: Option<ColumnLayout>) {
pub(super) fn read(&mut self, stage: &mut MemoryStage, id: Id, props: &CollectionProps, bound: Option<ColumnLayout>, hosted: Vec<ColumnKey>) {
self.hosted = hosted;
self.memory = stage.session::<HeaderMemory>(sub(id, "columns")).clone();
self.bound = bound.is_some();
if let Some(layout) = bound {
@@ -396,14 +405,18 @@ impl Header {
let (rect, rest) = flow.take_start(width);
flow = rest;
let hash = hash_of(&spec.key);
let mut sense = Sense::CLICK | Sense::FOCUS;
let hosted = self.hosted.contains(&spec.key);
let mut sense = Sense::CLICK;
if !hosted {
sense |= Sense::FOCUS;
}
if spec.movable {
sense |= Sense::DRAG;
}
pcx.part(HEADER.at(hash), shown(rect))
.sense(sense)
.focusable()
.priority(HitPriority::new(HitLevel::Body, 0))
// A hosted cell's stop is the hosted component's own, which joins this group where it is shown.
let part = pcx.part(HEADER.at(hash), shown(rect)).sense(sense);
let part = if hosted { part } else { part.focusable() };
part.priority(HitPriority::new(HitLevel::Body, 0))
.state_layer()
.tooltip(spec.tip.clone().unwrap_or_else(|| help.clone()));
if spec.resizable {
@@ -418,7 +431,24 @@ impl Header {
.cursor(CursorIcon::ResizeHorizontal)
.pointer_only("Resize Column… resizes from the keyboard");
}
self.cells.push(Cell { spec: at, rect, hash });
let remove = spec.remove.as_ref().map(|remove| {
let side = self.height.min(rect.width());
let end = if rtl { rect.min.x + grip } else { rect.max.x - grip };
let place = if rtl {
Rect::from_min_max(Pos2::new(end, rect.min.y), Pos2::new(end + side, rect.max.y))
} else {
Rect::from_min_max(Pos2::new(end - side, rect.min.y), Pos2::new(end, rect.max.y))
};
pcx.part(REMOVE.at(hash), shown(place))
.sense(Sense::CLICK | Sense::FOCUS)
.focusable()
.inactive(!remove.enabled)
.priority(HitPriority::new(HitLevel::Body, 2))
.state_layer()
.tooltip(remove.name.clone());
place
});
self.cells.push(Cell { spec: at, rect, hash, remove });
}
let room = shown(flow.rect());
self.room = (room.width() > 0.0).then_some(room);
@@ -498,10 +528,16 @@ impl Header {
pub(super) fn apply_fit(&mut self, ui: &Ui, env: &crate::runtime::env::EnvView<'_>, widest: f32) {
let Some((key, shown)) = self.fit.take() else { return };
let Some(at) = self.specs.iter().position(|spec| spec.key == key) else { return };
let label = self.label_width(ui, env, at);
let label = self.label_width(ui, env, at) + self.remove_side(at);
self.resize(&key, widest.max(label), shown);
}
/// The width the remove control of the column at `at` takes from its cell: the header's height, or nothing for a
/// column without one.
fn remove_side(&self, at: usize) -> f32 {
if self.specs[at].remove.is_some() { self.height } else { 0.0 }
}
/// Moves `key` to display position `to`: the session order changes and the move is reported.
fn move_to(&mut self, key: &ColumnKey, to: usize) {
let mut order: Vec<ColumnKey> = self.specs.iter().map(|spec| spec.key.clone()).collect();
@@ -549,17 +585,26 @@ impl Header {
let active =
cx.active_part().filter(|part| part.key == HEADER).and_then(|part| self.cells.iter().position(|cell| Some(cell.hash) == part.index));
let keyed = active.is_some() && (cx.core.intents.take(Intent::Activate) || cx.activation().is_some_and(|activation| activation.by_key));
let remove_at = cx.active_part().filter(|part| part.key == REMOVE).and_then(|part| part.index);
let keyed_remove = remove_at.is_some() && (cx.core.intents.take(Intent::Activate) || cx.activation().is_some_and(|activation| activation.by_key));
for at in 0..self.cells.len() {
let (rect, hash, spec) = (self.cells[at].rect, self.cells[at].hash, self.cells[at].spec);
let (key, sortable, movable, resizable) = {
let spec = &self.specs[spec];
(spec.key.clone(), spec.sortable, spec.movable, spec.resizable)
(spec.key.clone(), spec.sortable && !self.hosted.contains(&spec.key), spec.movable, spec.resizable)
};
let phase = cx.part(HEADER.at(hash)).press.phase;
let primary = phase.start().is_some_and(|start| start.button == PointerButton::Primary);
if sortable && ((phase.is_click() && primary) || (keyed && active == Some(at))) {
self.sort(&key);
}
if self.specs[spec].remove.as_ref().is_some_and(|remove| remove.enabled) {
let phase = cx.part(REMOVE.at(hash)).press.phase;
let pressed = phase.start().is_some_and(|start| start.button == PointerButton::Primary);
if (phase.is_click() && pressed) || (keyed_remove && remove_at == Some(hash)) {
self.events.push(ColumnEvent::Removed { key: key.clone() });
}
}
if cx.part(HEADER.at(hash)).hovered && crate::runtime::pointer::frame(&ctx).release == Some(PointerButton::Secondary) {
self.ask_menu(&ctx, Some(key.clone()), ctx.pointer_latest_pos().unwrap_or(rect.left_bottom()));
}
@@ -613,7 +658,7 @@ impl Header {
self.column_drop(cx, id, rtl);
self.keyboard_resize(cx);
self.commands(cx, id, active, rtl);
active.is_some() || self.memory.resizing.is_some()
active.is_some() || remove_at.is_some() || self.memory.resizing.is_some()
}
/// Asks for the header menu at `at`, for `column` or for the empty header.
@@ -749,22 +794,48 @@ impl Header {
}
/// Step 14, I0: the header labels, with the sort mark on the sorted column.
pub(super) fn paint<C: Collection>(&self, ui: &mut Ui, cx: &Cx<'_, C>, env: &Env, id: Id, rtl: bool) {
///
/// A hosted column's cell shows the collection's component (`Collection::header_cell`) in the part of the cell the
/// remove control leaves, in the header's roving group. The cell's label component shows it from its own paint,
/// where the `PaintUi` the hosting needs exists.
pub(super) fn paint<C: Collection>(&self, ui: &mut Ui, cx: &Cx<'_, C>, comp: &mut C, env: &Env, id: Id, rtl: bool) {
let ctx = ui.ctx().clone();
let group = crate::contract::steps::parts_group(&ctx, id);
for cell in &self.cells {
let spec = &self.specs[cell.spec];
let hosted = self.hosted.contains(&spec.key);
let text = cx.core.env.resolve(&spec.header).as_str().to_owned();
let sort = self.sort_of(&spec.key);
let builder = UiBuilder::new().max_rect(cell.rect).layout(child::column_layout(rtl)).scope_id(sub(id, ("header_cell", cell.hash)));
let mut cell_ui = alloc::child(ui, builder);
cell_ui.set_clip_rect(self.view.map_or(cell.rect, |view| cell.rect.intersect(view)).intersect(ui.clip_rect()));
let installed = Env::install_for(&cell_ui, env.derive_local(|scoped| scoped.arena = None));
let installed = Env::install_for(
&cell_ui,
env.derive_local(|scoped| {
scoped.arena = None;
if hosted {
scoped.row = Some(group);
}
}),
);
let edge = spec
.resizable
.then(|| HeaderEdge { state: cx.core.part_state(GRIP.at(cell.hash)), keyed: self.memory.resizing.as_ref() == Some(&spec.key) });
let mut label = HeaderText::new(Label::from(text), self.inset, sort).id(sub(id, ("header_text", cell.hash)));
label.edge = edge;
label.align = spec.align;
label.remove = cell.remove.zip(spec.remove.as_ref()).map(|(rect, remove)| RemoveMark { rect, enabled: remove.enabled });
if hosted && let Some(declared) = comp.items().columns.iter().position(|held| held.key == spec.key) {
let body = match cell.remove {
Some(remove) if rtl => Rect::from_min_max(Pos2::new(remove.max.x, cell.rect.min.y), cell.rect.max),
Some(remove) => Rect::from_min_max(cell.rect.min, Pos2::new(remove.min.x, cell.rect.max.y)),
None => cell.rect,
};
let column = spec.key.clone();
let comp = &mut *comp;
let field: HeaderField<'_> = Box::new(move |ui: &mut PaintUi<'_>| comp.header_cell(ui, &column, ("header", declared), body));
label.field = Some(field);
}
label.show_at(&mut cell_ui, cell.rect);
Env::restore(&ctx, installed);
}
@@ -783,12 +854,36 @@ impl Header {
part: HEADER.at(cell.hash),
name,
rect: cell.rect,
clickable: self.specs[cell.spec].sortable,
clickable: self.specs[cell.spec].sortable && !self.hosted.contains(&self.specs[cell.spec].key),
active: focused == Some(at),
sort: self.sort_of(&self.specs[cell.spec].key),
})
.collect();
report_header(ctx, id, cx.core.resolved.enabled, &cells);
for cell in &self.cells {
let (Some(rect), Some(remove)) = (cell.remove, &self.specs[cell.spec].remove) else { continue };
let name = cx.core.env.resolve(&remove.name).as_str().to_owned();
let enabled = cx.core.resolved.enabled && remove.enabled;
let part = REMOVE.at(cell.hash);
let mut node = SubNode::new(part, Role::BUTTON);
node.name = Name::Text(name.clone());
report_sub(
ctx,
&SubDecl {
owner: id,
component: "Collection",
node: &node,
rect,
enabled,
focusable: enabled,
clickable: enabled,
active: cx.active_part() == Some(part),
face: None,
label: &name,
parent: id,
},
);
}
}
/// The display position of the header part that holds focus.
@@ -848,10 +943,20 @@ struct HeaderEdge {
keyed: bool,
}
/// A column's remove control as the header cell paints it.
#[derive(Clone, Copy)]
struct RemoveMark {
rect: Rect,
enabled: bool,
}
/// A component the collection hosts in a header cell, shown from the label's paint.
type HeaderField<'a> = Box<dyn FnOnce(&mut PaintUi<'_>) + 'a>;
/// A header cell's label.
#[derive(crate::contract::Component)]
#[component(sample = HeaderText::sample)]
struct HeaderText {
struct HeaderText<'a> {
#[common]
common: Common,
inset: f32,
@@ -864,15 +969,21 @@ struct HeaderText {
node: bool,
/// The column's alignment: an end-aligned column's label and sort mark end at the cell's end, over its cells.
align: ColumnAlign,
/// The collection's own component for the cell: the cell shows it in place of a label and a sort mark.
field: Option<HeaderField<'a>>,
/// The column's remove control.
remove: Option<RemoveMark>,
}
impl HeaderText {
impl HeaderText<'static> {
fn sample() -> Self {
HeaderText { node: true, ..HeaderText::new(Label::from("Name"), 0.0, Some(false)) }
}
}
impl HeaderText<'_> {
fn new(text: Label, inset: f32, sort: Option<bool>) -> Self {
HeaderText { common: Common::new(), inset, sort, edge: None, node: false, align: ColumnAlign::Start }.label(text)
HeaderText { common: Common::new(), inset, sort, edge: None, node: false, align: ColumnAlign::Start, field: None, remove: None }.label(text)
}
/// The label on one line, cut with an ellipsis when its column is narrower than the text.
@@ -880,6 +991,14 @@ impl HeaderText {
TextRun::new(text).role(HEADER_ROLE).elide()
}
/// The remove control's mark, dimmed while the control is disabled.
fn paint_remove(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(mark) = self.remove else { return };
let draw = ui.draw();
let draw = if mark.enabled { draw } else { draw.data(DataMode::Inactive) };
draw.icon(Rect::from_center_size(mark.rect.center(), Vec2::splat(cx.style.mark)), &IconSpec::svg(IconId::new("close")));
}
/// The line of the column's end edge, inside the cell `rect`: the grip's line under the pointer and while dragged,
/// the focus line while the keyboard resizes the column.
fn paint_edge(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, rtl: bool) {
@@ -897,7 +1016,7 @@ impl HeaderText {
}
}
impl Component for HeaderText {
impl Component for HeaderText<'_> {
const ROLE: Role = Role::LABEL;
const ALT_ROLES: &'static [Role] = &[Role::None];
const PARTS: bool = false;
@@ -935,22 +1054,31 @@ impl Component for HeaderText {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let rtl = cx.core.env.direction().is_rtl();
if let Some(field) = self.field.take() {
self.paint_remove(ui, cx);
self.paint_edge(ui, cx, rtl);
field(ui);
return;
}
let inner = Flow::new(Flow::new(cx.rect, rtl).inset(Insets::horizontal(self.inset)), rtl);
let ink = if self.sort.is_some() { cx.style.sorted } else { cx.style.ink };
let run = self.run(cx.core.resolved.label).color(ink);
// The mark follows the label's end; a label too long for the cell is cut to leave the mark its room. An
// end-aligned column puts the two at the cell's end.
let mark = self.sort.map(|descending| (descending, cx.style.mark, cx.style.gap));
let room = (inner.rect().width() - mark.map_or(0.0, |(_, side, gap)| side + gap)).max(0.0);
// The remove control sits at the cell's end: the label and the mark keep clear of it.
let width = inner.rect().width() - self.remove.map_or(0.0, |remove| remove.rect.width());
let room = (width - mark.map_or(0.0, |(_, side, gap)| side + gap)).max(0.0);
let label = ui.draw().layout(&run, room).size().x.min(room);
let lead = if self.align == ColumnAlign::End { room - label } else { 0.0 };
let (text, rest) = Flow::new(inner.span(lead, inner.rect().width() - lead), rtl).take_start(label);
let (text, rest) = Flow::new(inner.span(lead, width - lead), rtl).take_start(label);
ui.draw().text(text, &run);
if let Some((descending, side, gap)) = mark {
let slot = Flow::new(rest.span(gap, side), rtl);
let id = IconId::new(if descending { "sort_descending" } else { "sort_ascending" });
ui.draw().icon(slot.align(Vec2::splat(side), Align::Min, Align::Center), &IconSpec::svg(id));
}
self.paint_remove(ui, cx);
self.paint_edge(ui, cx, rtl);
}
@@ -103,7 +103,8 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
_ => ColumnLayout::default(),
});
self.column_layout_at_read = bound.clone();
self.header.read(stage, id, comp.items(), bound);
let hosted: Vec<_> = comp.items().columns.iter().map(|spec| spec.key.clone()).filter(|key| comp.hosts_header(key)).collect();
self.header.read(stage, id, comp.items(), bound, hosted);
self.drags = stage.session::<Drags<C::Key>>(sub(id, "drags")).clone();
self.lead = stage.session::<Lead<C::Key>>(sub(id, "lead")).clone();
// A collection in a layer starts from `lead_on_open` at every opening of the layer, not only the first.
@@ -475,7 +476,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
if let Some(scope) = command_scope {
crate::runtime::commands::register_instance(&ctx, scope, id);
}
self.header.paint(ui, cx, env, id, rtl);
self.header.paint(ui, cx, comp, env, id, rtl);
let len = self.source.len();
let tree = matches!(layout.nav(), craft_behavior::NavShape::Tree);
focus::registration::record_tree(&ctx, id, tree);
+3 -2
View File
@@ -662,9 +662,10 @@ pub trait Collection: Component + HasProps + Meta<Shape = shape::Items> {
false
}
/// Hosts a component in the header cell of `column`, in `rect`. Called only for a column `hosts_header` answers
/// Hosts a component in the header cell of `column`, in `rect`, measured and shown under `key` (the column's index
/// among the declared columns, so a move or a hide keeps it). Called only for a column `hosts_header` answers
/// `true` for.
fn header_cell(&mut self, _ui: &mut Ui, _column: &ColumnKey, _rect: Rect) {}
fn header_cell(&mut self, _ui: &mut PaintUi<'_>, _column: &ColumnKey, _key: HostedKey, _rect: Rect) {}
/// The text the rename field of the item `key` opens with; `None` for the item's own text.
fn rename_draft(&self, _key: &Self::Key) -> Option<String> {
+1 -1
View File
@@ -40,7 +40,7 @@ pub(crate) use scroll_owner::{child_reveal, peek_reveal, queue_child_reveal, rev
pub(crate) use sense::{part_state, register_wheel};
pub(crate) use settle::settle;
pub(crate) use state::{register_reset, state, value_flags};
pub(crate) use stops::{StopsIn, body_group, join_group, member_group, register_stops, takes_focus};
pub(crate) use stops::{StopsIn, body_group, join_group, member_group, parts_group, register_stops, takes_focus};
pub(crate) use style::{style, style_cx};
pub(crate) use update::{after_update, edit_intents, gesture_gate, key_activation, record_context, secondary_click, takes_activation, update_inputs};
pub(crate) use value::{Shown, ShownState, peek_value, value};
+13 -1
View File
@@ -49,6 +49,18 @@ pub(crate) fn join_group(ctx: &Context, group: Id, id: Id) {
crate::runtime::memory::adopt::<u64>(ctx, id, slot);
}
/// The roving group of a component's own parts.
fn roving_group(id: Id) -> Id {
sub(id, "roving")
}
/// The roving group a stop shown among a component's parts joins: the group of the component's own parts, or the body
/// group they joined. The one source for the parts' registration and for a component the header hosts in its cells.
pub(crate) fn parts_group(ctx: &Context, id: Id) -> Id {
let own = roving_group(id);
focus::registration::part_group(ctx, own).unwrap_or(own)
}
/// `group` when `id` joined it in this pass or the one before, else `None`: a component that is no member keeps its
/// own Tab stop.
pub(crate) fn member_group(ctx: &Context, group: Option<Id>, id: Id) -> Option<Id> {
@@ -68,7 +80,7 @@ pub(crate) fn register_stops(input: &StopsIn<'_>) -> Vec<Stop> {
let ctx = input.ctx;
debug_assert!(input.parts.rovings.len() <= 1, "a component declares one roving group; a second would be dropped");
let row_parts = if input.item { input.row } else { None };
let group = (!input.parts.rovings.is_empty() && row_parts.is_none()).then(|| sub(input.id, "roving"));
let group = (!input.parts.rovings.is_empty() && row_parts.is_none()).then(|| roving_group(input.id));
if let (Some(group), Some(roving)) = (group, input.parts.rovings.first()) {
let arrival = input.parts.decls.iter().rev().find(|(_, extras)| extras.selected && extras.focusable);
let group = Group::new(group, *roving).rtl(input.rtl);
+49 -11
View File
@@ -14,9 +14,10 @@ use crate::contract::{
use crate::layout_components::Stack;
use crate::primitives::IconSpec;
use crate::runtime::env::{Env, Label};
use crate::tabs::{Tab, TabKind, TabStrip};
use crate::text::TextField;
use crate::tile_grid::{CaptionPlace, GridEvent, Tile, TileGrid, TileGroup};
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection};
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection, SelectionChange, keyed};
use craft_i18n::matcher::Matcher;
use egui::{Response, Ui};
use std::borrow::Cow;
@@ -164,14 +165,21 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> IconPicker<'a, K> {
/// Shows the picker and returns what the user did this pass.
pub fn show(self, ui: &mut Ui) -> IconPickerOutput<K> {
let IconPicker { label, mut value, groups, .. } = self;
let shown = Stack::new().show(ui, |ui, cx| Self::body(ui, cx, &label, &mut value, groups));
let IconPicker { label, mut value, groups, group_display, empty } = self;
let shown = Stack::new().show(ui, |ui, cx| Self::body(ui, cx, &label, &mut value, groups, (group_display, empty.as_ref())));
shown.inner.unwrap_or_else(|| IconPickerOutput { response: shown.output.clone(), picked: None, search_changed: false })
}
/// The search field over the grid, inside the picker's root container. The names of the closed groups are kept in
/// the container's memory.
fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, label: &Label, value: &mut Bind<'a, Option<K>>, groups: &[IconPickerGroup<K>]) -> IconPickerOutput<K> {
fn body(
ui: &mut Ui,
cx: &mut BodyCx<'_>,
label: &Label,
value: &mut Bind<'a, Option<K>>,
groups: &[IconPickerGroup<K>],
(group_display, empty): (IconPickerGroups, Option<&Label>),
) -> IconPickerOutput<K> {
let env = Env::of(ui);
let words = env.words::<PickerWords>();
let grid_id = ui.scope_id().with("icons");
@@ -183,15 +191,41 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> IconPicker<'a, K> {
};
let matcher = (!query.is_empty()).then(|| Matcher::new(&env.folder(), &query));
// The chosen category under `Filter`: 0 is All, `n` the group at `n - 1`. The strip's change applies before the
// cells are built, so the grid shows the new category in the same pass.
let mut category = 0;
if group_display == IconPickerGroups::Filter {
category = cx.memory::<Category>().0.min(groups.len());
let tabs: Vec<(usize, String)> =
std::iter::once((0, words.all.as_str().to_owned())).chain(groups.iter().enumerate().map(|(at, group)| (at + 1, group.name.clone()))).collect();
let source = keyed(&tabs, |tab: &(usize, String)| tab.0).with_text(|tab| Cow::Borrowed(tab.1.as_str()));
let strip = TabStrip::new(label.clone())
.kind(TabKind::Text)
.shown(category)
.show_items(ui, &source, &mut |key, _| Tab::new(tabs[*key].1.clone()));
for event in &strip.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some(key) = keys.last()
{
category = (*key).min(groups.len());
}
}
// A tab the strip moved to its overflow menu is picked there, and reported as `picked`.
if let Some(key) = strip.picked {
category = key.min(groups.len());
}
cx.memory::<Category>().0 = category;
}
let mut items = Vec::new();
let mut named = Vec::new();
for group in groups {
for (at, group) in groups.iter().enumerate().filter(|(at, _)| category == 0 || at + 1 == category) {
let kept: Vec<&IconPickerItem<K>> =
group.items.iter().filter(|item| matcher.as_ref().is_none_or(|matcher| item.matches(matcher))).collect();
if kept.is_empty() {
continue;
}
if !group.name.is_empty() {
if group_display == IconPickerGroups::Headings && !group.name.is_empty() {
named.push((items.len(), kept.len(), group.name.clone()));
}
items.extend(kept);
@@ -219,8 +253,8 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> IconPicker<'a, K> {
.groups(&shown_groups)
.collapsible()
.selection(Bind::given(selection))
.rows_stamp(query_stamp(&query))
.empty(words.icon_no_match.clone())
.rows_stamp(query_stamp(&query, category))
.empty(empty.cloned().unwrap_or_else(|| words.icon_no_match.clone()))
.show_items(ui, &source, &mut |at, _| {
let item = source.items[*at];
let tile = Tile::new(item.label.clone());
@@ -262,10 +296,14 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> IconPicker<'a, K> {
#[derive(Clone, Default)]
struct ClosedGroups(HashSet<String>);
/// The rows stamp of a search text: the same text keeps the layout, another one rebuilds it.
fn query_stamp(query: &str) -> u64 {
/// The category the filter row shows: 0 is All, `n` the group at `n - 1`.
#[derive(Clone, Default)]
struct Category(usize);
/// The rows stamp of a search text inside a category: the same pair keeps the layout, another one rebuilds it.
fn query_stamp(query: &str, category: usize) -> u64 {
use std::hash::Hasher as _;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
query.hash(&mut hasher);
(query, category).hash(&mut hasher);
hasher.finish()
}
@@ -1,6 +1,6 @@
//! Stories of `IconPicker`.
use super::{IconPicker, IconPickerGroup, IconPickerItem};
use super::{IconPicker, IconPickerGroup, IconPickerGroups, IconPickerItem};
use crate::buttons::Button;
use crate::contract::{Bind, Show as _, ShowContainer as _};
use crate::popover::Popover;
@@ -55,6 +55,22 @@ fn icon_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
IconPicker::new("Tool", Bind::bound(data.value("tool", Some(3u8))), &groups()).show(ui).into()
}
/// The groups as a filter row: All first, then each group.
#[story(IconPicker<'static, u8>, covers = [], drive = Drive::Never)]
fn icon_picker_filter(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
IconPicker::new("Tool", Bind::bound(data.value("tool", Some(3u8))), &groups()).group_display(IconPickerGroups::Filter).show(ui).into()
}
/// The filter row with a search that matches nothing, and the app's own empty text.
#[story(IconPicker<'static, u8>, covers = [], drive = Drive::Type("zzz"))]
fn icon_picker_filter_no_match(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
IconPicker::new("Tool", Bind::bound(data.value("none", None)), &groups())
.group_display(IconPickerGroups::Filter)
.empty("No icons in this category")
.show(ui)
.into()
}
#[story(IconPicker<'static, u8>, covers = [Empty], drive = Drive::Type("zzz"))]
fn icon_picker_no_match(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
IconPicker::new("Tool", Bind::bound(data.value("none", None)), &groups()).show(ui).into()
+21
View File
@@ -4,6 +4,7 @@ use super::{Table, sort_rows};
use crate::contract::{Bind, CollectionEvent, ColumnEvent, ColumnKind, ColumnSort, ColumnSpec, ShowCollection as _, ToggleColumn};
use crate::list::{ListRow, ToggleCell};
use crate::testing::pointer::{moved, secondary};
use crate::text::TextField;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, ItemSource, Selection};
use craft_i18n::{AgeStyle, FileSize, SizeUnit};
@@ -173,6 +174,26 @@ fn table_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
table(ui, data, Vec::new(), None, false, false, Selection::default())
}
/// A grid whose header titles and cells are text fields, with a remove control on each column.
#[story(Table<'static, usize>, covers = [], drive = Drive::Never)]
fn table_editable_grid(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let rows = files(4);
let columns = vec![
ColumnSpec::new(NAME, "Name", ColumnWidth::Controls(10.0)).removable("Remove Name column", true),
ColumnSpec::new(PAGES, "Pages", ColumnWidth::Controls(8.0)).removable("Remove Pages column", false),
];
Table::<usize>::new("Grid", columns)
.header_field(NAME, TextField::new("Name title", Bind::kept()), |_| {})
.header_field(PAGES, TextField::new("Pages title", Bind::kept()), |_| {})
.show_items(ui, &Files(&rows), &mut |key, icx| {
ListRow::new(rows[*key].name.clone())
.cells(icx.cells())
.cell_field(NAME, TextField::new("Name", Bind::kept()), |_| {})
.cell_field(PAGES, TextField::new("Pages", Bind::kept()), |_| {})
})
.into()
}
#[story(Table<'static, usize>, covers = [], drive = Drive::Never)]
fn table_sorted_descending_with_toggles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
table(ui, data, files(12), Some(ColumnSort::descending(SIZE)), true, false, Selection::default())
+23 -5
View File
@@ -6,8 +6,8 @@ use super::words::TableWords;
use crate::contract::overlay::Anchor;
use crate::contract::{
Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnCommands, ColumnLayout, ColumnRequest, ColumnSpec, Common, Component,
ContainerProps, Cx, DropKind, EditResponse, ListDrag, OverlayUi, Overlays as _, Props as _, Role, RowState, SelectMode, Show as _,
ShowContainer as _, Sizing, WordSetCx as _,
ContainerProps, Cx, DropKind, EditResponse, Hosted, HostedKey, Hosting, ListDrag, OverlayUi, Overlays as _, PaintUi, Props as _, Role, RowState,
SelectMode, Show as _, ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::display::Divider;
use crate::list::{DropTest, ListRow, RowEvent, RowTest, RowText};
@@ -78,8 +78,13 @@ pub struct Table<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// dragged rows would go. A refused spot shows no drop mark.
#[prop(func = "Fn(&ListDrag<K>, Option<&K>, usize) -> bool")]
accepts: Option<DropTest<'a, K>>,
/// The components hosted in header cells, by column; each is shown once, in the pass that draws its cell.
header_fields: Vec<(ColumnKey, Option<HeaderField<'a, K>>)>,
}
/// A component and its output taker, hosted in a header cell.
type HeaderField<'a, K> = Box<dyn for<'r> Hosted<Table<'r, K>> + 'a>;
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Table<'a, K> {
/// A table named `label` over `columns`, with multiple selection.
pub fn new(label: impl Into<Label>, columns: Vec<ColumnSpec>) -> Self {
@@ -96,6 +101,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Table<'a, K> {
can_drag: None,
drops: Vec::new(),
accepts: None,
header_fields: Vec::new(),
}
.label(label)
}
@@ -103,9 +109,10 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Table<'a, K> {
/// Hosts `field` in the header cell of `column`, in place of its label; `output` gets what the field returns, once
/// per pass.
#[must_use]
pub fn header_field<C: crate::contract::Show + 'a>(self, column: ColumnKey, field: C, output: impl FnOnce(C::Output) + 'a) -> Self {
let _ = (column, field, output);
todo!("dg.F22")
pub fn header_field<C: crate::contract::Show + 'a>(mut self, column: ColumnKey, field: C, output: impl FnOnce(C::Output) + 'a) -> Self {
self.header_fields.retain(|(held, _)| *held != column);
self.header_fields.push((column, Some(Box::new(Hosting::new(field, output)))));
self
}
/// Takes the drops of `kind` from drags that did not start in the table; kinds given earlier come first.
@@ -242,4 +249,15 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for Table<'_, K> {
fn rename_editor(&mut self, ui: &mut Ui, draft: Bind<'_, String>, label: Rect, name: &str) -> Option<EditResponse<String>> {
Some(crate::text::rename_field(ui, draft, label, name))
}
fn hosts_header(&self, column: &ColumnKey) -> bool {
self.header_fields.iter().any(|(held, _)| held == column)
}
fn header_cell(&mut self, ui: &mut PaintUi<'_>, column: &ColumnKey, key: HostedKey, rect: Rect) {
let field = self.header_fields.iter_mut().find(|(held, _)| held == column).and_then(|(_, field)| field.take());
if let Some(field) = field {
Hosted::show(field, ui, key, rect);
}
}
}
@@ -0,0 +1,46 @@
//! The icon picker's filter row: a category shows only its group's tiles, All shows every group, the search narrows
//! inside the category, and the category outlives a pass.
use craft_ui::contract::Bind;
use craft_ui::pickers::{IconPicker, IconPickerGroup, IconPickerGroups, IconPickerItem};
use craft_ui::testing::{Fixture, Room, trial};
fn groups() -> Vec<IconPickerGroup<u8>> {
vec![
IconPickerGroup::new("Selection", vec![IconPickerItem::new(1, "Move"), IconPickerItem::new(2, "Marquee")]),
IconPickerGroup::new("Drawing", vec![IconPickerItem::new(3, "Brush"), IconPickerItem::new(4, "Eraser")]),
]
}
fn shows(fixture: &Fixture, name: &str) -> bool {
fixture.by_label(name).is_some()
}
#[trial]
fn the_category_row_filters_the_grid_and_search_stays_inside_it() {
let mut fixture = Fixture::new(|ui| {
let groups = groups();
let mut value = None;
IconPicker::new("Tool", Bind::bound(&mut value), &groups).group_display(IconPickerGroups::Filter).empty("Nothing here").show(ui);
});
fixture.in_room(Room::Dialog).settle();
assert!(shows(&fixture, "Move") && shows(&fixture, "Brush"), "All shows every group");
let drawing = fixture.by_label("Drawing").expect("the category's tab");
fixture.click(&drawing).settle();
assert!(shows(&fixture, "Brush") && shows(&fixture, "Eraser"), "the chosen category's tiles show");
assert!(!shows(&fixture, "Move"), "another category's tiles are hidden");
fixture.idle(2);
assert!(!shows(&fixture, "Move"), "the category survives a pass");
let search = fixture.by_label("Search icons").expect("the search field");
fixture.click(&search).type_text("era").settle();
assert!(shows(&fixture, "Eraser") && !shows(&fixture, "Brush"), "the search narrows inside the category");
fixture.type_text("zzz").settle();
assert!(fixture.texts().iter().any(|painted| painted.text == "Nothing here"), "no match shows the empty text");
let all = fixture.by_label("All").expect("the All tab");
fixture.click(&all).settle();
assert!(!shows(&fixture, "Move"), "the search still applies under All");
}
@@ -2,6 +2,7 @@
mod combo_list;
mod date;
mod icon_picker;
mod select_list;
mod select_steps;
mod select_width;
+59
View File
@@ -7,6 +7,7 @@ use craft_host::target::Os;
use craft_ui::contract::{Bind, CollectionEvent, ColumnEvent, ColumnSort, ColumnSpec, Role, ShowCollection as _};
use craft_ui::list::ListRow;
use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable, Table};
use craft_ui::text::TextField;
use craft_ui::testing::{Fixture, Room, pointer, trial};
use egui::{Key, Modifiers, Pos2, Rect};
use std::cell::{Cell, RefCell};
@@ -235,6 +236,64 @@ fn ctrl_or_cmd_with_an_arrow_moves_the_focused_column() {
}
}
/// A header cell hosts a text field that edits, its press does not sort and the header label stays its column's name;
/// a column built with `removable` shows a control that reports its column once when pressed, and none when disabled.
#[trial]
fn a_header_field_edits_and_a_header_remove_reports_its_column() {
let events = Rc::new(RefCell::new(Vec::<ColumnEvent>::new()));
let edits = Rc::new(Cell::new(0_u32));
let text = Rc::new(RefCell::new(String::new()));
let (seen, counted, held) = (events.clone(), edits.clone(), text.clone());
let mut fixture = Fixture::new(move |ui| {
let columns = vec![
ColumnSpec::new(NAME, "Name", ColumnWidth::Controls(10.0)).sortable().removable("Remove Name", true),
ColumnSpec::new(SIZE, "Size", ColumnWidth::Controls(6.0)).removable("Remove Size", false),
];
let keys = [0_usize];
let source = keyed(&keys, |key: &usize| *key);
let mut draft = held.borrow().clone();
let out = Table::new("Files", columns)
.header_field(NAME, TextField::new("Name title", Bind::bound(&mut draft)), |_| counted.set(counted.get() + 1))
.show_items(ui, &source, &mut |key, icx| ListRow::new(format!("File {key}")).cells(icx.cells()));
*held.borrow_mut() = draft;
for event in out.events {
if let CollectionEvent::Column(column) = event {
seen.borrow_mut().push(column);
}
}
});
fixture.in_room(Room::Dialog).settle();
assert!(fixture.by_label("Name").is_some(), "the column header keeps its name");
fixture.key(Key::Tab, Modifiers::NONE).settle();
let (table, part) = fixture.focused_stop().expect("Tab reaches the header's group");
assert!(part.is_some(), "Tab lands on a header part: {part:?}");
// The hosted field joins the header's roving group, so an arrow from the header parts reaches it.
let mut reached = false;
for _ in 0..4 {
fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
if fixture.focused_stop().is_some_and(|(id, _)| id != table) {
reached = true;
break;
}
}
assert!(reached, "an arrow from the header parts lands on the hosted field");
let field = fixture.by_label("Name title").expect("the hosted field's node");
fixture.click(&field).type_text("x").settle();
assert_eq!(text.borrow().as_str(), "x", "typing in the header cell edits the field");
assert!(edits.get() > 0, "the field's output reaches the closure");
assert!(events.borrow().iter().all(|event| !matches!(event, ColumnEvent::Sort { .. })), "a press on the field does not sort");
let remove = fixture.by_label("Remove Size").expect("the disabled remove control still shows");
fixture.click(&remove).settle();
assert!(events.borrow().iter().all(|event| !matches!(event, ColumnEvent::Removed { .. })), "a disabled control reports nothing");
let remove = fixture.by_label("Remove Name").expect("the remove control's node");
fixture.click(&remove).settle();
let removed: Vec<ColumnEvent> = events.borrow().iter().filter(|event| matches!(event, ColumnEvent::Removed { .. })).cloned().collect();
assert_eq!(removed, [ColumnEvent::Removed { key: NAME }], "one press reports its column once");
}
/// A table wider than its room: a fill name column and four numeric columns.
fn wide_table() -> Fixture {
let mut fixture = Fixture::new(|ui| {