panels-w8: written from its sheet

This commit is contained in:
aiongg
2026-11-14 17:56:00 +00:00
parent 67abb102f3
commit bc563b6c82
5 changed files with 407 additions and 35 deletions
+272 -34
View File
@@ -1,11 +1,34 @@
//! `HistoryPanel`: the undo history as a list of states and named snapshots, with a footer of snapshot buttons.
use crate::contract::{NoValue, Outcome, Pattern};
use crate::primitives::textures::{ThumbSource, Thumbnails};
use crate::runtime::env::Label;
use craft_behavior::IconId;
use super::words::PanelWords;
use crate::contract::{
Bind, CollectionEvent, ColumnSpec, ListDrag, NoValue, Outcome, Pattern, Props as _, SelectMode, ShowCollection as _, ShowContainer as _, Sizing,
ToggleColumn, request_rename,
};
use crate::layout_components::Stack;
use crate::list::{List, ListRow, RowInk, ThumbSize, ToggleCell, ToggleState};
use crate::menu::{Menu, MenuItem};
use crate::primitives::IconSpec;
use crate::primitives::textures::{Priority, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails};
use crate::runtime::env::{Env, Label};
use crate::sections::{FooterAction, FooterBar};
use craft_behavior::{ColumnKey, ColumnWidth, GesturePhase, IconId, Selection, SelectionChange, keyed};
use craft_keymap::Mods;
use egui::{Response, Ui};
use std::cell::RefCell;
use std::collections::HashSet;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::Arc;
#[cfg(feature = "testing")]
mod stories;
/// The column of the source marks.
const SOURCE: ColumnKey = ColumnKey::new("historySource");
/// The column of the names.
const NAME: ColumnKey = ColumnKey::new("historyName");
/// The width in points a snapshot's picture is requested for.
const THUMB_POINTS: f32 = 32.0;
/// What a history row stands for: a named snapshot or a state of the undo stack, by number.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -31,30 +54,32 @@ pub struct HistoryRow {
}
impl HistoryRow {
fn new(key: HistoryKey, label: Label) -> Self {
HistoryRow { key, label, icon: None, redo: false }
}
/// A row for the snapshot `id` named `label`.
pub fn snapshot(id: u64, label: impl Into<Label>) -> Self {
let _ = (id, label.into());
todo!("pn.C34")
Self::new(HistoryKey::Snapshot(id), label.into())
}
/// A row for the state `id` named `label`.
pub fn state(id: u64, label: impl Into<Label>) -> Self {
let _ = (id, label.into());
todo!("pn.C34")
Self::new(HistoryKey::State(id), label.into())
}
/// Shows `icon` before the name.
#[must_use]
pub fn icon(mut self, icon: IconId) -> Self {
let _ = (&mut self, icon);
todo!("pn.C34")
self.icon = Some(icon);
self
}
/// Marks the state as one that can be redone.
#[must_use]
pub fn redo(mut self, redo: bool) -> Self {
let _ = (&mut self, redo);
todo!("pn.C34")
self.redo = redo;
self
}
}
@@ -111,74 +136,287 @@ impl Outcome for HistoryPanelOutput {
}
}
/// The row a context menu was asked for; it lives in the panel's stack memory while the menu is open.
#[derive(Clone, Copy, Default)]
struct MenuTarget(Option<HistoryKey>);
/// The footer buttons, in the order they stand.
#[derive(Clone, Copy)]
enum Slot {
Delete,
NewSnapshot,
NewDocument,
}
/// The history panel: `rows` with the `current` one marked, thumbnails of the snapshots and a footer of buttons.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
#[allow(dead_code)] // P3(panels-w8): pn.C34
pub struct HistoryPanel<'a> {
rows: &'a [HistoryRow],
current: Option<HistoryKey>,
source: Option<HistoryKey>,
has_source: bool,
thumbs: Option<(&'a Thumbnails<u64>, &'a dyn ThumbSource<u64>)>,
can_delete: Option<Box<dyn Fn(&HistoryKey) -> bool + 'a>>,
footer: HistoryFooter,
reveal: Option<HistoryKey>,
rename: Option<u64>,
enabled: bool,
}
impl<'a> HistoryPanel<'a> {
/// A panel over `rows`, with `current` marked.
pub fn new(rows: &'a [HistoryRow], current: Option<HistoryKey>) -> Self {
let _ = (rows, current);
todo!("pn.C34")
HistoryPanel {
rows,
current,
source: None,
has_source: false,
thumbs: None,
can_delete: None,
footer: HistoryFooter::default(),
reveal: None,
rename: None,
enabled: true,
}
}
/// Marks the row that is the source of the history brush.
/// Shows the source column and marks the row that is the source of the history brush.
#[must_use]
pub fn source(mut self, source: Option<HistoryKey>) -> Self {
let _ = (&mut self, source);
todo!("pn.C34")
self.source = source;
self.has_source = true;
self
}
/// Shows the pictures of the rows from `source`.
/// Shows the pictures of the snapshot rows from `source`.
#[must_use]
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
let _ = (&mut self, thumbnails, source);
todo!("pn.C34")
self.thumbs = Some((thumbnails, source));
self
}
/// Which rows the Delete button and key take; the others refuse.
/// Which rows the Delete button and key take; the others refuse. Without it every row is taken.
#[must_use]
pub fn can_delete(mut self, can: impl Fn(&HistoryKey) -> bool + 'a) -> Self {
let _ = (&mut self, can);
todo!("pn.C34")
self.can_delete = Some(Box::new(can));
self
}
/// Which footer buttons show.
#[must_use]
pub fn footer(mut self, footer: HistoryFooter) -> Self {
let _ = (&mut self, footer);
todo!("pn.C34")
self.footer = footer;
self
}
/// Scrolls to `key` and shows it.
#[must_use]
pub fn reveal(mut self, key: HistoryKey) -> Self {
let _ = (&mut self, key);
todo!("pn.C34")
self.reveal = Some(key);
self
}
/// Opens the rename field of the snapshot `snapshot`.
#[must_use]
pub fn start_rename(mut self, snapshot: u64) -> Self {
let _ = (&mut self, snapshot);
todo!("pn.C34")
self.rename = Some(snapshot);
self
}
/// Whether the panel takes input.
#[must_use]
pub fn enabled(mut self, enabled: bool) -> Self {
let _ = (&mut self, enabled);
todo!("pn.C34")
self.enabled = enabled;
self
}
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> HistoryPanelOutput {
let _ = ui;
todo!("pn.C34")
let HistoryPanel { rows, current, source, has_source, thumbs, can_delete, footer, reveal, rename, enabled } = self;
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let words = env.words::<PanelWords>();
let list_id = ui.scope_id().with("history-rows");
let pixels_per_point = ui.ctx().pixels_per_point();
// PLAN: the drag path needs a `'static` rule, so the host's borrowed `can_delete` is evaluated once per pass
// into this set; the drag payload, the drop acceptance, the Delete key and the menu all read the set.
let deletable: Arc<HashSet<HistoryKey>> =
Arc::new(rows.iter().map(|row| row.key).filter(|key| can_delete.as_ref().is_none_or(|can| can(key))).collect());
let stamp = {
let mut hasher = DefaultHasher::new();
for row in rows {
row.key.hash(&mut hasher);
env.resolve(&row.label).as_str().hash(&mut hasher);
row.redo.hash(&mut hasher);
row.icon.hash(&mut hasher);
}
source.hash(&mut hasher);
hasher.finish()
};
let events: RefCell<Vec<HistoryEvent>> = RefCell::new(Vec::new());
if let Some(snapshot) = rename {
request_rename(&ctx, list_id, &HistoryKey::Snapshot(snapshot));
}
let slots: Vec<(Slot, FooterAction)> = {
let icon = |name: &'static str| IconSpec::svg(IconId::new(name));
let mut slots = Vec::new();
if footer.delete {
let takes = current.is_some_and(|key| deletable.contains(&key));
let set = Arc::clone(&deletable);
let action = FooterAction::new(icon("trash"), words.history_delete_tip.clone())
.enabled(enabled && takes)
.takes_drops_disabled(enabled)
.accepts_drops(move |drag: &ListDrag<HistoryKey>| drag.list == list_id && set.contains(&drag.grabbed));
slots.push((Slot::Delete, action));
}
if footer.new_snapshot {
slots.push((Slot::NewSnapshot, FooterAction::new(icon("scan"), words.history_new_snapshot.clone()).enabled(enabled)));
}
if footer.new_document {
slots.push((
Slot::NewDocument,
FooterAction::new(icon("new_file"), words.history_new_document.clone()).enabled(enabled && current.is_some()),
));
}
slots
};
let mut stack = Stack::new().fill();
if !slots.is_empty() {
stack = stack.footer(|ui, _| {
let out = FooterBar::actions(slots.iter().map(|(_, action)| action.clone())).show_footer(ui);
// The footer runs twice per pass: the sizing pass measures it and must report nothing.
if ui.is_sizing_pass() {
return;
}
let mut events = events.borrow_mut();
if let Some(picked) = out.picked.and_then(|at| slots.get(at)) {
match picked.0 {
Slot::Delete => events.push(HistoryEvent::Delete(None)),
Slot::NewSnapshot => events.push(HistoryEvent::NewSnapshot { mods: out.mods }),
Slot::NewDocument => events.push(HistoryEvent::NewDocument),
}
}
if let Some(dropped) = &out.dropped
&& matches!(slots.get(dropped.index), Some((Slot::Delete, _)))
&& let Some(drag) = dropped.payload::<ListDrag<HistoryKey>>()
&& deletable.contains(&drag.grabbed)
{
events.push(HistoryEvent::Delete(Some(drag.grabbed)));
}
});
}
let shown = stack.show(ui, |ui, stack| {
let mut target = stack.memory::<MenuTarget>().0;
let mut held = current.map_or_else(Selection::default, Selection::single);
let set = Arc::clone(&deletable);
let mut list = List::<HistoryKey>::new(words.history_list.clone())
.id(list_id)
.select(SelectMode::Single)
.rename(true)
.can_rename(|key: &HistoryKey| matches!(key, HistoryKey::Snapshot(_)))
.empty(words.history_empty.clone())
.selection(Bind::bound(&mut held))
.rows_stamp(stamp)
.sizing(Sizing::Fill)
.enabled(enabled)
.drag_payload(move |drag: &ListDrag<HistoryKey>| set.contains(&drag.grabbed).then(|| drag.clone()));
if has_source {
list = list.header(false).columns(vec![
ColumnSpec::toggle(SOURCE, words.history_source.clone(), ToggleColumn::exclusive()),
ColumnSpec::new(NAME, Label::Empty, ColumnWidth::fill(1.0)),
]);
}
if let Some(key) = reveal {
list = list.reveal(key);
}
let items = keyed(rows, |row: &HistoryRow| row.key).with_toggled(move |row, _| source == Some(row.key));
let out = list.show_items(ui, &items, &mut |_, icx| {
let row = &rows[icx.at];
let mut item = ListRow::new(row.label.clone()).cells(icx.cells()).state(icx.row.clone());
if let Some(icon) = row.icon {
item = item.icon(IconSpec::svg(icon));
}
if row.redo {
item = item.ink(RowInk::Dimmed);
}
if has_source {
let on = ToggleState::of(source == Some(row.key));
item = item.toggle(ToggleCell::check(SOURCE, on, words.history_source_cell.clone()));
}
if let (HistoryKey::Snapshot(id), Some((thumbnails, picture))) = (row.key, thumbs) {
let request = ThumbRequest::for_cell(THUMB_POINTS, pixels_per_point);
let state = thumbnails.state(&ctx, picture, &id, &request, Priority::VISIBLE);
item = item.thumb(ThumbSize::Small, move |cx, rect| {
thumbnails.paint(cx, rect, &state, &ThumbPaint::default());
});
}
item
});
let response = out.response.clone();
let mut picked = events.borrow_mut();
for event in out.events {
match event {
CollectionEvent::Selection(SelectionChange::Set(keys)) => {
if let Some(key) = keys.last() {
picked.push(HistoryEvent::Select(*key));
}
}
CollectionEvent::Toggle(edit) => {
let ended = matches!(edit.phase(), Some(GesturePhase::Commit) | None);
if let (true, Some(cell)) = (ended, edit.value())
&& cell.on
&& cell.column == SOURCE
{
picked.push(HistoryEvent::SetSource(cell.key));
}
}
CollectionEvent::Rename(edit) => {
let ended = matches!(edit.phase(), Some(GesturePhase::Commit) | None);
if let (true, Some(rename)) = (ended, edit.value())
&& let HistoryKey::Snapshot(snapshot) = rename.key
{
let text = rename.name.trim();
let changed = rows.iter().find(|row| row.key == rename.key).is_some_and(|row| env.resolve(&row.label).as_str() != text);
if changed && !text.is_empty() {
picked.push(HistoryEvent::Rename { snapshot, text: text.to_owned() });
}
}
}
CollectionEvent::Delete(keys) => {
picked.extend(keys.into_iter().filter(|key| deletable.contains(key)).map(|key| HistoryEvent::Delete(Some(key))));
}
CollectionEvent::ContextMenu(request) => target = Some(request.key),
_ => {}
}
}
drop(picked);
if let Some(key) = target {
let renamable = enabled && matches!(key, HistoryKey::Snapshot(_));
let removable = enabled && deletable.contains(&key);
let mut deleted = false;
let menu = Menu::context(words.history_list.clone(), &response).show(ui, |ui, _| {
if MenuItem::new(words.history_rename.clone()).enabled(renamable).show(ui).ran {
request_rename(&ctx, list_id, &key);
}
if MenuItem::new(words.history_delete.clone()).enabled(removable).show(ui).ran {
deleted = true;
}
});
if deleted {
events.borrow_mut().push(HistoryEvent::Delete(Some(key)));
}
if menu.output.closed.is_some() {
target = None;
}
}
stack.memory::<MenuTarget>().0 = target;
});
HistoryPanelOutput { response: shown.output, events: events.into_inner() }
}
}
@@ -0,0 +1,51 @@
//! Stories of `HistoryPanel`: states with redo rows dimmed, snapshots, the source column, empty and disabled.
use super::{HistoryFooter, HistoryKey, HistoryPanel, HistoryRow};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
/// The states of a short edit, the last two undone, and two snapshots.
fn rows() -> Vec<HistoryRow> {
vec![
HistoryRow::snapshot(1, "Snapshot 1"),
HistoryRow::state(1, "Open"),
HistoryRow::state(2, "Brush Tool"),
HistoryRow::state(3, "Gaussian Blur").redo(true),
HistoryRow::state(4, "Fill").redo(true),
HistoryRow::snapshot(2, "Before Crop"),
]
}
/// Shows the panel over `rows`; the oldest state is never deleted.
fn panel(ui: &mut Ui, rows: &[HistoryRow], current: Option<HistoryKey>, source: Option<Option<HistoryKey>>, enabled: bool) -> StoryOutput {
let mut panel = HistoryPanel::new(rows, current)
.can_delete(|key| *key != HistoryKey::State(1))
.footer(HistoryFooter { delete: true, new_snapshot: true, new_document: true })
.enabled(enabled);
if let Some(source) = source {
panel = panel.source(source);
}
let out = panel.show(ui);
let readout = format!("{:?}", out.events);
StoryOutput::from(out).readout(readout)
}
#[story(HistoryPanel<'static>, covers = [], drive = Drive::Never, title = "Snapshots and states")]
fn history_panel(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
panel(ui, &rows(), Some(HistoryKey::State(2)), None, true)
}
#[story(HistoryPanel<'static>, covers = [], drive = Drive::Never, title = "With the source column")]
fn history_panel_source(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
panel(ui, &rows(), Some(HistoryKey::State(2)), Some(Some(HistoryKey::Snapshot(1))), true)
}
#[story(HistoryPanel<'static>, covers = [], drive = Drive::Never, title = "Empty")]
fn history_panel_empty(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
panel(ui, &[], None, None, true)
}
#[story(HistoryPanel<'static>, covers = [], drive = Drive::Never, title = "Disabled")]
fn history_panel_disabled(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
panel(ui, &rows(), Some(HistoryKey::State(2)), Some(None), false)
}
@@ -1,4 +1,4 @@
//! Panel and overlay patterns: `Panel`, `Inspector`, `CommandPalette` and `Tour`.
//! Panel and overlay patterns: `Panel`, `Inspector`, `HistoryPanel`, `ModifierKeysPanel`, `CommandPalette` and `Tour`.
mod words;
@@ -4,6 +4,15 @@ craft_ui::words! {
/// The words of the panel patterns; each id is `<type>.<name>`.
pub struct PanelWords {
inspector_empty: "inspector.empty" = "No properties";
history_list: "history.list" = "History";
history_empty: "history.empty" = "No history";
history_delete_tip: "history.deleteTip" = "Delete Current State";
history_new_snapshot: "history.newSnapshot" = "Create New Snapshot";
history_new_document: "history.newDocument" = "Create New Document from Current State";
history_rename: "history.rename" = "Rename…";
history_delete: "history.delete" = "Delete";
history_source: "history.source" = "History Brush Source";
history_source_cell: "history.sourceCell" = "Set {row} as History Brush Source";
palette_search: "commandPalette.search" = "Search commands";
palette_placeholder: "commandPalette.placeholder" = "Search commands, tools and panels…";
palette_list: "commandPalette.list" = "Commands";
@@ -0,0 +1,74 @@
//! The history panel applies the host's delete rule on both paths a row can be deleted by, and a press on a row's
//! source cell sets the source without moving the document's history.
use craft_ui::patterns::panels::{HistoryEvent, HistoryFooter, HistoryKey, HistoryPanel, HistoryRow};
use craft_ui::testing::{Fixture, trial};
use std::cell::RefCell;
use std::rc::Rc;
type Seen = Rc<RefCell<Vec<HistoryEvent>>>;
/// A panel over four rows with the oldest state undeletable, the second state current and Delete in the footer;
/// `source` shows the source column with that row marked.
fn rig(source: Option<HistoryKey>, with_source: bool) -> (Fixture, Seen) {
let seen: Seen = Rc::new(RefCell::new(Vec::new()));
let sink = seen.clone();
let rows = vec![
HistoryRow::state(1, "Open"),
HistoryRow::state(2, "Brush"),
HistoryRow::state(3, "Fill"),
HistoryRow::snapshot(7, "Snapshot 1"),
];
let fixture = Fixture::new(move |ui| {
let mut panel = HistoryPanel::new(&rows, Some(HistoryKey::State(2)))
.can_delete(|key| *key != HistoryKey::State(1))
.footer(HistoryFooter { delete: true, new_snapshot: false, new_document: false });
if with_source {
panel = panel.source(source);
}
sink.borrow_mut().extend(panel.show(ui).events);
});
(fixture, seen)
}
fn deletes(seen: &Seen) -> Vec<HistoryEvent> {
seen.borrow().iter().filter(|event| matches!(event, HistoryEvent::Delete(_))).cloned().collect()
}
#[trial]
fn history_rows_drop_on_delete_by_the_hosts_rule() {
let (mut fixture, seen) = rig(None, false);
fixture.settle();
let button = fixture.by_label("Delete Current State").expect("the Delete button");
let fill = fixture.by_label("Fill").expect("the Fill row");
fixture.drag(&fill, button.center() - fill.center()).settle();
assert_eq!(deletes(&seen), vec![HistoryEvent::Delete(Some(HistoryKey::State(3)))], "a deletable row dropped on Delete is reported");
seen.borrow_mut().clear();
let open = fixture.by_label("Open").expect("the Open row");
fixture.drag(&open, button.center() - open.center()).settle();
assert_eq!(deletes(&seen), Vec::<HistoryEvent>::new(), "the oldest state starts no deleting drag and Delete takes no drop of it");
seen.borrow_mut().clear();
fixture.click(&button).settle();
assert_eq!(deletes(&seen), vec![HistoryEvent::Delete(None)], "the button press deletes the picked row");
}
#[trial]
fn history_source_cell_sets_the_source_without_selecting() {
let (mut fixture, seen) = rig(Some(HistoryKey::State(2)), true);
fixture.settle();
let cell = fixture.by_label("Set Fill as History Brush Source").expect("Fill's source cell");
fixture.click(&cell).settle();
{
let events = seen.borrow();
assert!(events.contains(&HistoryEvent::SetSource(HistoryKey::State(3))), "{events:?}");
assert!(!events.iter().any(|event| matches!(event, HistoryEvent::Select(_))), "the source press must not select: {events:?}");
}
seen.borrow_mut().clear();
let label = fixture.by_label("Fill").expect("the Fill row");
fixture.click(&label).settle();
assert!(seen.borrow().contains(&HistoryEvent::Select(HistoryKey::State(3))), "{:?}", seen.borrow());
}