panels-w10: written from its sheet

This commit is contained in:
aiongg
2026-11-14 17:56:01 +00:00
parent e93eaa8dfd
commit 0780608ff2
9 changed files with 829 additions and 97 deletions
+2 -1
View File
@@ -7,10 +7,11 @@ The Layers panel for Craft apps. The app implements `LayerTree`, a read-only vie
| `tree` | `LayerTree`, the one trait an app implements: children and parent, one `LayerInfo` per row (name, kind, visibility, label colour, locks, clipping, link, blend label, masks, effects, smart object source, warning), the selection and target, sub-rows, the active layer's properties, the blend modes (`Entry<String>` lists), the footer's state and the drop rules. |
| `panel` | `LayersPanel`: the filter bar, the blend and opacity row, the lock and fill row, the rows, the footer; one focus stop, keyboard, rename in place (double-click on the name, F2 or `start_rename`), drag and drop, AccessKit. `LayersEvent`s out; `panel_menu` and `run_command` for the panel menu; `LayersPanel::style(&UiTokens)` gives the look. |
| `rows` | `BlendRows`: Blend mode, Opacity, Lock and Fill as one block, usable alone (a Properties panel). |
| `comps` | `LayerCompsPanel` over the app's comp rows, reporting `LayerCompsEvent`s. |
| `filter` | `LayerFilter` and `LayerFilterBar`: filter by kind, name, effect, blend mode, attribute, label colour, smart object, artboard or group; the matching rule is plain code, and `LayerTree::listed` lets the app answer what only it knows (missing linked files, empty layers). |
| `options` | `LayersSettings` (the persisted section), `LayersOptions` and `LayersOptionsDialog` (Layers Panel Options: thumbnail size and contents, the five switches). |
| `thumbs` | `LayerThumb`, `LayerThumbKind`, `ThumbContents`: the key the panel gives `craft_ui::primitives::textures::Thumbnails` for each thumbnail of a row; the app implements `ThumbSource` for it. |
Its words are the `words!` structs of the parts: `LayersPanelWords`, `BlendRowsWords`, `LayerFilterWords` and `LayersOptionsWords`.
Its words are the `words!` structs of the parts: `LayersPanelWords`, `BlendRowsWords`, `LayerCompsWords`, `LayerFilterWords` and `LayersOptionsWords`.
The crate is UI-only: egui and craft-ui are plain dependencies, and `screen-testing` is its only feature.
+423
View File
@@ -0,0 +1,423 @@
//! The list of the Layer Comps panel: its columns and rows, the mapping of the list's events to
//! `LayerCompsEvent`s, the row menu and the footer.
use std::borrow::Cow;
use std::cell::RefCell;
use std::sync::Arc;
use craft_behavior::{ColumnKey, ColumnWidth, DisplayOrder, EditEvent, IconId, ItemSource, Mixed, Selection, SelectionChange};
use craft_ui::contract::{
Bind, BodyCx, CollectionEvent, ColumnSpec, Props as _, ReorderRule, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
ToggleColumn,
};
use craft_ui::display::{Shade, Text};
use craft_ui::list::{List, ListRow, RowEvent, ToggleCell, ToggleFace, ToggleState, TrailingFace, TrailingPart};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::memory::Remember as _;
use craft_ui::sections::{FooterAction, FooterBar};
use egui::{Id, Response, Ui};
use super::{CompOption, LayerCompRow, LayerCompsEvent, LayerCompsWords, Session};
use crate::ui::sweep::{SweepOut, sweep_events};
/// The apply marker column: one cell is on, the applied comp's or the Last Document State row's.
const APPLY: ColumnKey = ColumnKey::new("apply");
/// The name column, the one a double click renames in.
const NAME: ColumnKey = ColumnKey::new("name");
const VISIBILITY: ColumnKey = ColumnKey::new("visibility");
const POSITION: ColumnKey = ColumnKey::new("position");
const APPEARANCE: ColumnKey = ColumnKey::new("appearance");
/// The trailing warning part of a comp that lost layers.
const WARNING: u16 = 0;
// The footer's actions in the order given: previous and next at the start edge, then delete, new and update from the
// end edge, which puts update, new, delete left to right as Photoshop does.
const PREVIOUS: usize = 0;
const NEXT: usize = 1;
const DELETE: usize = 2;
const NEW: usize = 3;
const UPDATE: usize = 4;
const AT_START: usize = 2;
/// The option columns, in the order they show.
const OPTIONS: [CompOption; 3] = [CompOption::Visibility, CompOption::Position, CompOption::Appearance];
/// The column of `option`.
fn column_of(option: CompOption) -> ColumnKey {
match option {
CompOption::Visibility => VISIBILITY,
CompOption::Position => POSITION,
CompOption::Appearance => APPEARANCE,
}
}
/// The option whose column is `column`.
fn option_of(column: &ColumnKey) -> Option<CompOption> {
OPTIONS.into_iter().find(|option| column_of(*option) == *column)
}
/// The icons of `option`'s cell, on and off.
fn icons_of(option: CompOption) -> (&'static str, &'static str) {
match option {
CompOption::Visibility => ("eye", "eye_off"),
CompOption::Position => ("move", "move"),
CompOption::Appearance => ("sparkles", "sparkles"),
}
}
/// The column name and the name pattern of the cells of `option`.
fn words_of(words: &LayerCompsWords, option: CompOption) -> (&Label, &Label) {
match option {
CompOption::Visibility => (&words.visibility, &words.visibility_cell),
CompOption::Position => (&words.position, &words.position_cell),
CompOption::Appearance => (&words.appearance, &words.appearance_cell),
}
}
/// Whether `comp` records `option`.
fn records(comp: &LayerCompRow, option: CompOption) -> bool {
match option {
CompOption::Visibility => comp.visibility,
CompOption::Position => comp.position,
CompOption::Appearance => comp.appearance,
}
}
/// The key of a row: the fixed Last Document State row or a comp.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum CompKey {
LastState,
Comp(u64),
}
/// What the panel's pass shares: the list's id, the comps and the words.
pub(super) struct ListCx<'a> {
pub(super) list: Id,
pub(super) label: &'a Label,
pub(super) comps: &'a [LayerCompRow],
pub(super) last_state_applied: bool,
pub(super) words: &'a LayerCompsWords,
pub(super) env: &'a Env,
}
/// The comp shown at row `at`; `None` for the Last Document State row at 0.
fn comp_at(comps: &[LayerCompRow], at: usize) -> Option<&LayerCompRow> {
at.checked_sub(1).and_then(|index| comps.get(index))
}
/// The rows: Last Document State, then the comps.
struct CompRows<'a> {
comps: &'a [LayerCompRow],
last_state: &'a str,
last_state_applied: bool,
}
impl DisplayOrder<CompKey> for CompRows<'_> {
fn len(&self) -> usize {
self.comps.len() + 1
}
fn key(&self, at: usize) -> CompKey {
comp_at(self.comps, at).map_or(CompKey::LastState, |comp| CompKey::Comp(comp.id))
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
Some(Cow::Borrowed(comp_at(self.comps, at).map_or(self.last_state, |comp| comp.name.as_str())))
}
}
impl ItemSource<CompKey> for CompRows<'_> {
fn toggled(&self, at: usize, column: &ColumnKey) -> bool {
let Some(comp) = comp_at(self.comps, at) else { return *column == APPLY && self.last_state_applied };
if *column == APPLY { comp.applied } else { option_of(column).is_some_and(|option| records(comp, option)) }
}
}
/// `pattern` with `{row}` replaced by `row`.
fn named(pattern: &Label, row: &str) -> Label {
Label::from(craft_i18n::fmt(pattern.as_str(), &[("row", row)]))
}
fn apply_cell(words: &LayerCompsWords, on: bool, row: &str) -> ToggleCell {
ToggleCell::new(APPLY, ToggleFace::Check, ToggleState::of(on), named(&words.apply_cell, row))
}
fn option_cell(words: &LayerCompsWords, option: CompOption, on: bool, row: &str) -> ToggleCell {
let (column, cell) = words_of(words, option);
let (on_icon, off_icon) = icons_of(option);
ToggleCell::new(column_of(option), ToggleFace::icons(IconId::new(on_icon), IconId::new(off_icon)), ToggleState::of(on), named(cell, row))
.tooltip(column.clone())
.always_visible()
}
/// The row at `at`.
fn build_row(cx: &ListCx<'_>, at: usize) -> ListRow<'static> {
let words = cx.words;
let Some(comp) = comp_at(cx.comps, at) else {
return ListRow::new(words.last_state.clone()).toggle(apply_cell(words, cx.last_state_applied, words.last_state.as_str()));
};
let mut row = ListRow::new(comp.name.clone()).toggle(apply_cell(words, comp.applied, &comp.name));
for option in OPTIONS {
row = row.toggle(option_cell(words, option, records(comp, option), &comp.name));
}
if comp.missing > 0 {
let count = comp.missing as u64;
let tip = words.missing.text(count, &cx.env.format().integer(count));
// PLAN: a row's parts trail its name; production draws the warning before the name.
row = row.trailing_part(TrailingPart::new(WARNING), TrailingFace::Icon(IconSpec::svg(IconId::new("warning"))), Label::from(tip));
}
row
}
/// One step of the pass: an event, or the cells of a sweep that later cells of the same gesture join.
enum Step {
Event(LayerCompsEvent),
Toggle { rows: Vec<CompKey>, option: CompOption, edit: EditEvent<bool> },
}
/// The pass's events in order. The sweep helper writes its toggles here with the list's row keys; they become comp
/// ids when the pass ends.
#[derive(Default)]
struct Steps(Vec<Step>);
impl Steps {
fn push(&mut self, event: LayerCompsEvent) {
self.0.push(Step::Event(event));
}
/// Restores the last document state once per pass, and only while it is not the state shown.
fn restore(&mut self, cx: &ListCx<'_>) {
let reported = self.0.iter().any(|step| matches!(step, Step::Event(LayerCompsEvent::RestoreLastDocumentState)));
if !cx.last_state_applied && !reported {
self.push(LayerCompsEvent::RestoreLastDocumentState);
}
}
/// The comp the pass selected last.
fn selected(&self) -> Option<u64> {
self.0.iter().rev().find_map(|step| match step {
Step::Event(LayerCompsEvent::Select(id)) => Some(*id),
_ => None,
})
}
fn into_events(self) -> Vec<LayerCompsEvent> {
self.0
.into_iter()
.map(|step| match step {
Step::Event(event) => event,
Step::Toggle { rows, option, edit } => {
let comps = rows.into_iter().filter_map(|key| if let CompKey::Comp(id) = key { Some(id) } else { None }).collect();
LayerCompsEvent::SetOption { comps, option, edit }
}
})
.collect()
}
}
impl SweepOut<CompKey, CompOption> for Steps {
fn last_toggle(&mut self) -> Option<(CompOption, &EditEvent<bool>, &mut Vec<CompKey>)> {
match self.0.last_mut() {
Some(Step::Toggle { rows, option, edit }) => Some((*option, &*edit, rows)),
_ => None,
}
}
fn push_toggle(&mut self, rows: Vec<CompKey>, column: CompOption, edit: EditEvent<bool>) {
self.0.push(Step::Toggle { rows, option: column, edit });
}
}
/// The comp the selection binding holds, if it is one of `comps`.
fn held(bind: &mut Bind<'_, Option<u64>>, cx: &mut BodyCx<'_>, comps: &[LayerCompRow]) -> Option<u64> {
match bind.reborrow().read(cx) {
Some(Mixed::Same(Some(id))) if comps.iter().any(|comp| comp.id == id) => Some(id),
_ => None,
}
}
/// The comp the footer's Update and Delete act on: the selected one, else the applied one.
fn target(comps: &[LayerCompRow], selected: Option<u64>) -> Option<u64> {
selected.or_else(|| comps.iter().find(|comp| comp.applied).map(|comp| comp.id))
}
/// Shows the rows, the row menu and the hint of an empty list, and returns what the user did.
pub(super) fn show_list(ui: &mut Ui, stack: &mut BodyCx<'_>, selected: &RefCell<Bind<'_, Option<u64>>>, cx: &ListCx<'_>) -> Vec<LayerCompsEvent> {
let words = cx.words;
let before = held(&mut selected.borrow_mut(), stack, cx.comps);
let selection = before.map_or_else(Selection::default, |id| Selection::single(CompKey::Comp(id)));
let source = CompRows { comps: cx.comps, last_state: words.last_state.as_str(), last_state_applied: cx.last_state_applied };
let mut columns = vec![ColumnSpec::toggle(APPLY, Label::Empty, ToggleColumn::exclusive()), ColumnSpec::new(NAME, Label::Empty, ColumnWidth::fill(1.0))];
for option in OPTIONS {
let (name, _) = words_of(words, option);
columns.push(ColumnSpec::toggle(column_of(option), name.clone(), ToggleColumn::sweepable()).icon(IconId::new(icons_of(option).0)));
}
// PLAN: no `accepts` rule: a drop before Last Document State lands at index 0 and the row stays first, so every
// spot is a drop target and `can_drag` keeps the fixed row out of the drag.
let mut list = List::new(cx.label.clone())
.id(cx.list)
.select(SelectMode::Single)
.allow_empty(true)
.reorder(ReorderRule::new())
.rename(true)
.rename_column(NAME)
.columns(columns)
.selection(Bind::given(selection))
.can_rename(|key| matches!(key, CompKey::Comp(_)))
.can_drag(|key| matches!(key, CompKey::Comp(_)));
if cx.comps.is_empty() {
// The hint shows under the one row.
list = list.sizing(Sizing::Content);
}
let out = list.show_items(ui, &source, &mut |_, item| {
if let Some(comp) = comp_at(cx.comps, item.at)
&& !comp.comment.is_empty()
{
let comment: &str = &comp.comment;
item.tip(move |ui| {
ui.label(comment);
});
}
build_row(cx, item.at)
});
let mut steps = Steps::default();
let menu = {
let session = stack.memory::<Session>();
map_events(cx, session, out.events, &mut steps);
session.menu
};
show_menu(ui, &out.response, cx, menu, &mut steps);
if cx.comps.is_empty() {
let _ = Text::new(words.hint.clone()).shade(Shade::Muted).show(ui);
}
// A bound selection takes the pick; a given one leaves it to the app, which reads `Select`.
if let Some(id) = steps.selected().filter(|id| Some(*id) != before) {
let edit = EditEvent::set(Mixed::Same(before), Some(id), Arc::from(cx.label.as_str()), None);
selected.borrow_mut().reborrow().write(stack, &edit);
}
steps.into_events()
}
/// Maps the list's events to the panel's, in order.
fn map_events(cx: &ListCx<'_>, session: &mut Session, list: Vec<CollectionEvent<CompKey, RowEvent>>, steps: &mut Steps) {
let mut label: Arc<str> = Arc::from("");
for event in list {
match event {
CollectionEvent::Selection(change) => {
let key = match change {
SelectionChange::Set(keys) => keys.last().copied(),
SelectionChange::Toggle(key) => Some(key),
_ => None,
};
match key {
Some(CompKey::Comp(id)) => steps.push(LayerCompsEvent::Select(id)),
Some(CompKey::LastState) => steps.restore(cx),
None => {}
}
}
CollectionEvent::Activate(CompKey::Comp(id)) => steps.push(LayerCompsEvent::Apply(id)),
CollectionEvent::Activate(CompKey::LastState) => steps.restore(cx),
CollectionEvent::Reorder(edit) => {
// The move counts the remaining rows with Last Document State at 0, the comp index is one less.
if let EditEvent::Commit { after: moved, .. } | EditEvent::Set { after: moved, .. } = edit
&& let CompKey::Comp(comp) = moved.key
{
steps.push(LayerCompsEvent::Reorder { comp, index: moved.to.saturating_sub(1) });
}
}
CollectionEvent::Rename(edit) => {
if let EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } = edit
&& let CompKey::Comp(comp) = after.key
&& let Some(shown) = cx.comps.iter().find(|row| row.id == comp)
{
let name = after.name.trim();
if !name.is_empty() && name != shown.name {
steps.push(LayerCompsEvent::Rename { comp, name: name.to_owned() });
}
}
}
CollectionEvent::ContextMenu(request) => {
if let CompKey::Comp(comp) = request.key {
session.menu = Some(comp);
}
}
CollectionEvent::Item(CompKey::Comp(comp), RowEvent::Trailing { part, .. }) if part == TrailingPart::new(WARNING) => {
steps.push(LayerCompsEvent::ClearWarning(comp));
}
CollectionEvent::Toggle(edit) => {
if let EditEvent::Begin { label: named, .. } = &edit {
label = named.clone();
}
let column = match &edit {
EditEvent::Update { value: cell, .. } | EditEvent::Set { after: cell, .. } | EditEvent::Commit { after: cell, .. } => {
cell.column.clone()
}
EditEvent::Begin { before: Mixed::Same(cell), .. } | EditEvent::Cancel { before: Some(Mixed::Same(cell)), .. } => cell.column.clone(),
_ => continue,
};
if column == APPLY {
if let EditEvent::Set { after, .. } | EditEvent::Commit { after, .. } = &edit
&& after.on
{
match after.key {
CompKey::Comp(id) => steps.push(LayerCompsEvent::Apply(id)),
CompKey::LastState => steps.restore(cx),
}
}
} else if let Some(option) = option_of(&column) {
sweep_events(session.sweeps.of(option), option, edit, &mut label, steps);
}
}
_ => {}
}
}
}
/// The row menu of the comp the last context request named: Move Up and Move Down, each disabled at its end.
fn show_menu(ui: &mut Ui, opener: &Response, cx: &ListCx<'_>, comp: Option<u64>, steps: &mut Steps) {
let Some(comp) = comp else { return };
let Some(at) = cx.comps.iter().position(|row| row.id == comp) else { return };
let words = cx.words;
let picked = Menu::context(words.row_menu.clone(), opener)
.show(ui, |ui, _| {
let up = MenuItem::new(words.move_up.clone()).enabled(at > 0).show(ui).ran;
let down = MenuItem::new(words.move_down.clone()).enabled(at + 1 < cx.comps.len()).show(ui).ran;
if up { at.checked_sub(1) } else if down { Some(at + 1) } else { None }
})
.inner
.flatten();
if let Some(index) = picked {
steps.push(LayerCompsEvent::Reorder { comp, index });
}
}
/// Shows the footer: previous and next at the start, then update, new and delete at the end.
pub(super) fn show_footer(ui: &mut Ui, stack: &mut BodyCx<'_>, selected: &RefCell<Bind<'_, Option<u64>>>, cx: &ListCx<'_>) -> Vec<LayerCompsEvent> {
let words = cx.words;
let chosen = held(&mut selected.borrow_mut(), stack, cx.comps);
let target = target(cx.comps, chosen);
let any = !cx.comps.is_empty();
let icon = |name: &'static str| IconSpec::svg(IconId::new(name));
let actions = [
FooterAction::new(icon("chevrons_left"), words.previous.clone()).enabled(any),
FooterAction::new(icon("chevrons_right"), words.next.clone()).enabled(any),
FooterAction::new(icon("trash"), words.delete.clone()).enabled(target.is_some()),
FooterAction::new(icon("plus"), words.new_comp.clone()),
FooterAction::new(icon("rotate_cw"), words.update.clone()).enabled(target.is_some()),
];
let out = FooterBar::actions(actions).at_start(AT_START).show_footer(ui);
let event = match out.picked {
Some(PREVIOUS) => Some(LayerCompsEvent::Previous),
Some(NEXT) => Some(LayerCompsEvent::Next),
Some(DELETE) => target.map(LayerCompsEvent::Delete),
Some(NEW) => Some(LayerCompsEvent::New),
Some(UPDATE) => target.map(LayerCompsEvent::Update),
_ => None,
};
event.into_iter().collect()
}
+90
View File
@@ -0,0 +1,90 @@
//! What the Layer Comps panel reports and the commands of its row menu.
use craft_behavior::EditEvent;
use craft_ui::contract::{CommandSet, NoValue, Outcome};
use egui::Response;
use super::CompOption;
/// What the user did in the Layer Comps panel, in order.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum LayerCompsEvent {
/// The fixed Last Document State row was activated.
RestoreLastDocumentState,
/// A row was selected.
Select(u64),
/// A comp was applied (double click or its apply mark).
Apply(u64),
/// A rename ended.
#[non_exhaustive]
Rename {
/// The comp.
comp: u64,
/// The new name.
name: String,
},
/// A comp was dragged or moved by key to `index`, counted among the comps.
#[non_exhaustive]
Reorder {
/// The comp.
comp: u64,
/// Its new place.
index: usize,
},
/// An option toggle of one or more comps, one gesture per sweep (`Update`s, a `Commit` on
/// release, a `Cancel` carrying the earlier state).
#[non_exhaustive]
SetOption {
/// The comps the gesture touches.
comps: Vec<u64>,
/// The option.
option: CompOption,
/// The edit.
edit: EditEvent<bool>,
},
/// The warning on this comp was cleared.
ClearWarning(u64),
/// Apply the previous comp.
Previous,
/// Apply the next comp.
Next,
/// Update this comp from the document.
Update(u64),
/// Create a comp.
New,
/// Delete this comp.
Delete(u64),
}
/// What [`LayerCompsPanel::show`](super::LayerCompsPanel::show) returns.
#[derive(Debug)]
#[non_exhaustive]
#[must_use = "the app applies the panel's events"]
pub struct LayerCompsOutput {
/// The panel.
pub response: Response,
/// What the user did this pass, in order.
pub events: Vec<LayerCompsEvent>,
}
impl Outcome for LayerCompsOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// The row menu's commands: move the comp. They have no default chords: the list's stacking keys already move rows and
/// arrive as [`LayerCompsEvent::Reorder`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
#[command(prefix = "layerCompsPanel")]
pub enum LayerCompsRowCommands {
/// Move the comp up.
#[command(label = "Move Up")]
MoveUp,
/// Move the comp down.
#[command(label = "Move Down")]
MoveDown,
}
+70 -94
View File
@@ -1,10 +1,22 @@
//! `LayerCompsPanel`: the Layer Comps panel, a list of recorded layer states with sweepable
//! option toggles, rename, reorder and the footer actions.
use craft_behavior::EditEvent;
use craft_ui::contract::{Bind, CommandSet, NoValue, Outcome};
use craft_ui::runtime::env::Label;
use egui::{Response, Ui};
mod body;
mod events;
#[cfg(feature = "screen-testing")]
mod stories;
mod words;
pub use events::{LayerCompsEvent, LayerCompsOutput, LayerCompsRowCommands};
pub use words::LayerCompsWords;
use std::cell::RefCell;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _, SweepApply};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::{Env, Label};
use egui::Ui;
/// What a layer comp records of a layer: the options a comp row toggles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -82,67 +94,40 @@ impl LayerCompRow {
}
}
/// What the user did in the Layer Comps panel, in order.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum LayerCompsEvent {
/// The fixed Last Document State row was activated.
RestoreLastDocumentState,
/// A row was selected.
Select(u64),
/// A comp was applied (double click or its apply mark).
Apply(u64),
/// A rename ended.
#[non_exhaustive]
Rename {
/// The comp.
comp: u64,
/// The new name.
name: String,
},
/// A comp was dragged or moved by key to `index`.
#[non_exhaustive]
Reorder {
/// The comp.
comp: u64,
/// Its new place.
index: usize,
},
/// An option toggle of one or more comps, one gesture per sweep (`Update`s, a `Commit` on
/// release, a `Cancel` carrying the earlier state).
#[non_exhaustive]
SetOption {
/// The comps the gesture touches.
comps: Vec<u64>,
/// The option.
option: CompOption,
/// The edit.
edit: EditEvent<bool>,
},
/// The warning on this comp was cleared.
ClearWarning(u64),
/// Apply the previous comp.
Previous,
/// Apply the next comp.
Next,
/// Update this comp from the document.
Update(u64),
/// Create a comp.
New,
/// Delete this comp.
Delete(u64),
/// The sweeps in progress, one reader per option column: the host keeps one `SweepApply` per column.
#[derive(Clone)]
struct Sweeps {
visibility: SweepApply,
position: SweepApply,
appearance: SweepApply,
}
craft_ui::words! {
/// The words of the Layer Comps panel.
pub struct LayerCompsWords {
/// The fixed first row.
last_state: "layerComps.lastDocumentState" = "Last Document State";
/// The tooltip of the warning on a comp that lost layers.
missing: "layerComps.missing" = "Layers of this comp were deleted";
impl Default for Sweeps {
fn default() -> Self {
Sweeps { visibility: SweepApply::new(), position: SweepApply::new(), appearance: SweepApply::new() }
}
}
impl Sweeps {
/// The sweep reader of `option`'s column.
fn of(&mut self, option: CompOption) -> &mut SweepApply {
match option {
CompOption::Visibility => &mut self.visibility,
CompOption::Position => &mut self.position,
CompOption::Appearance => &mut self.appearance,
}
}
}
/// What the panel keeps between passes, in its root slot.
#[derive(Clone, Default)]
struct Session {
/// The option sweeps in progress.
sweeps: Sweeps,
/// The comp the last context request named, whose row menu shows.
menu: Option<u64>,
}
/// The Layer Comps panel: a list with three sweepable toggle columns, rename, reorder (Last
/// Document State fixed first), a warning trailing part and the footer actions.
#[must_use = "show the panel with `show`"]
@@ -156,25 +141,6 @@ pub struct LayerCompsPanel<'a> {
empty: Option<Label>,
}
/// What [`LayerCompsPanel::show`] returns.
#[derive(Debug)]
#[non_exhaustive]
#[must_use = "the app applies the panel's events"]
pub struct LayerCompsOutput {
/// The panel.
pub response: Response,
/// What the user did this pass, in order.
pub events: Vec<LayerCompsEvent>,
}
impl Outcome for LayerCompsOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
impl<'a> LayerCompsPanel<'a> {
/// The panel named `label` showing `rows`, with `selected` the selected comp.
pub fn new(label: impl Into<Label>, rows: &'a [LayerCompRow], selected: Bind<'a, Option<u64>>) -> Self {
@@ -202,22 +168,32 @@ impl<'a> LayerCompsPanel<'a> {
self
}
/// Draws the panel over the available rect.
/// Draws the panel over the available rect: the rows, then the footer. Events are reported in that order.
pub fn show(self, ui: &mut Ui) -> LayerCompsOutput {
let Self { label, rows, selected, last_state_applied, document, empty } = self;
let _ = (ui, label, rows, selected, last_state_applied, document, empty);
todo!("pn.C43")
if let Some(text) = empty {
let response = Text::new(text).shade(Shade::Muted).show(ui);
return LayerCompsOutput { response, events: Vec::new() };
}
let env = Env::of(ui);
let words = env.words::<LayerCompsWords>();
// Comp ids restart in every document, so the list's own state (rename, scroll) is keyed by the document.
let list = match document {
Some(document) => ui.scope_id().with(("layer-comps-rows", document)),
None => ui.scope_id().with("layer-comps-rows"),
};
let cx = body::ListCx { list, label: &label, comps: rows, last_state_applied, words: &words, env: &env };
let selected = RefCell::new(selected);
let footer_events = RefCell::new(Vec::new());
let shown = Stack::new()
.fill()
.footer(|ui, stack| {
let out = body::show_footer(ui, stack, &selected, &cx);
footer_events.borrow_mut().extend(out);
})
.show(ui, |ui, stack| body::show_list(ui, stack, &selected, &cx));
let mut events = footer_events.into_inner();
events.extend(shown.inner.unwrap_or_default());
LayerCompsOutput { response: shown.output, events }
}
}
/// The row menu's commands: move the selected comp.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
#[command(prefix = "layerCompsPanel")]
pub enum LayerCompsRowCommands {
/// Move the comp up.
#[command(label = "Move Up")]
MoveUp,
/// Move the comp down.
#[command(label = "Move Down")]
MoveDown,
}
+30
View File
@@ -0,0 +1,30 @@
//! Stories of `LayerCompsPanel`: no comps, two comps with one applied, a comp with a warning.
use craft_ui::contract::Bind;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use super::{LayerCompRow, LayerCompsPanel};
#[story(LayerCompsPanel<'static>, covers = [Default], drive = Drive::Never)]
fn layer_comps_panel_no_comps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let selected = data.value("selected", None::<u64>);
StoryOutput::from(LayerCompsPanel::new("Layer Comps", &[], Bind::bound(selected)).last_state_applied(true).show(ui))
}
#[story(LayerCompsPanel<'static>, covers = [], drive = Drive::Never)]
fn layer_comps_panel_two_comps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = vec![
LayerCompRow::new(1, "Daylight").applied(true).visibility(true).position(true).appearance(true),
LayerCompRow::new(2, "Night").comment("The scene with the lamps on").visibility(true),
];
let selected = data.value("selected", Some(1_u64));
StoryOutput::from(LayerCompsPanel::new("Layer Comps", &rows, Bind::bound(selected)).show(ui))
}
#[story(LayerCompsPanel<'static>, covers = [], drive = Drive::Never)]
fn layer_comps_panel_warning(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = vec![LayerCompRow::new(1, "Draft").missing(3).visibility(true), LayerCompRow::new(2, "Final").missing(1).position(true)];
let selected = data.value("selected", None::<u64>);
StoryOutput::from(LayerCompsPanel::new("Layer Comps", &rows, Bind::bound(selected)).show(ui))
}
+26
View File
@@ -0,0 +1,26 @@
//! The words of the Layer Comps panel.
craft_ui::words! {
/// The words of the Layer Comps panel's rows, footer and row menu. Patterns with `{row}` are whole phrases, so a
/// language puts the name where its grammar wants it.
pub struct LayerCompsWords {
last_state: "layerComps.lastDocumentState" = "Last Document State";
apply_cell: "layerComps.applyCell" = "Apply {row}";
visibility: "layerComps.visibility" = "Visibility";
position: "layerComps.position" = "Position";
appearance: "layerComps.appearance" = "Appearance (Layer Style)";
visibility_cell: "layerComps.visibilityCell" = "Visibility of {row}";
position_cell: "layerComps.positionCell" = "Position of {row}";
appearance_cell: "layerComps.appearanceCell" = "Appearance of {row}";
missing: count "layerComps.missing" = "{n} layer recorded by this comp was deleted. Update the comp, or clear the warning." | "{n} layers recorded by this comp were deleted. Update the comp, or clear the warning.";
row_menu: "layerComps.rowMenu" = "Layer Comp";
move_up: "layerComps.moveUp" = "Move Up";
move_down: "layerComps.moveDown" = "Move Down";
previous: "layerComps.previous" = "Apply previous selected layer comp";
next: "layerComps.next" = "Apply next selected layer comp";
update: "layerComps.update" = "Update layer comp (visibility, position and appearance)";
new_comp: "layerComps.new" = "Create new layer comp";
delete: "layerComps.delete" = "Delete layer comp";
hint: "layerComps.hint" = "Capture the visibility, position and style of every layer with + below, then switch between versions.";
}
}
+115
View File
@@ -0,0 +1,115 @@
//! `LayerCompsPanel`: reordering keeps Last Document State first, and a rename left open does not carry over to another
//! document.
use craft_layers::ui::comps::{LayerCompRow, LayerCompsEvent, LayerCompsPanel};
use craft_ui::contract::Bind;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// The room of the panel: wide enough for the columns, tall enough for the rows and the footer.
const PANEL: Vec2 = Vec2::new(420.0, 400.0);
type Seen = Rc<RefCell<Vec<LayerCompsEvent>>>;
/// The panel over the comps of the document the trial sets, with the events it reports.
struct Rig {
fixture: Fixture,
seen: Seen,
document: Rc<Cell<u32>>,
}
/// Two comps with ids 1 and 2, named by `names`: every document restarts its ids.
fn comps(names: [&str; 2]) -> Vec<LayerCompRow> {
names.iter().zip(1_u64..).map(|(name, id)| LayerCompRow::new(id, *name)).collect()
}
fn rig() -> Rig {
let seen: Seen = Rc::default();
let document = Rc::new(Cell::new(0_u32));
let selected = Rc::new(RefCell::new(None::<u64>));
let (sink, shown, choice) = (Rc::clone(&seen), Rc::clone(&document), Rc::clone(&selected));
let mut fixture = Fixture::new(move |ui| {
let rows = if shown.get() == 0 { comps(["Alpha", "Beta"]) } else { comps(["Gamma", "Delta"]) };
let mut chosen = choice.borrow_mut();
let out = LayerCompsPanel::new("Layer Comps", &rows, Bind::bound(&mut *chosen)).document(shown.get()).show(ui);
sink.borrow_mut().extend(out.events);
});
fixture.room(PANEL);
fixture.settle();
Rig { fixture, seen, document }
}
impl Rig {
/// The reorders reported since the last call, as comp and index.
fn reorders(&self) -> Vec<(u64, usize)> {
self.seen
.borrow_mut()
.drain(..)
.filter_map(|event| if let LayerCompsEvent::Reorder { comp, index, .. } = event { Some((comp, index)) } else { None })
.collect()
}
}
/// A drag reports the comp and its index among the comps, which leave Last Document State out: before the first comp is
/// index 0 and so is before Last Document State, and a drag moves nothing and applies nothing.
#[trial]
fn dragging_a_comp_row_reorders_without_applying_it() {
let mut rig = rig();
let lds = rig.fixture.by_label("Last Document State").expect("the fixed row shows");
let alpha = rig.fixture.by_label("Alpha").expect("the first comp shows");
let beta = rig.fixture.by_label("Beta").expect("the second comp shows");
assert!(lds.rect.top() < alpha.rect.top() && alpha.rect.top() < beta.rect.top(), "Last Document State is the first row");
let step = beta.rect.top() - alpha.rect.top();
rig.fixture.drag(&beta, Vec2::new(0.0, alpha.rect.center().y - beta.rect.center().y - step * 0.25));
rig.fixture.idle(3);
assert!(!rig.seen.borrow().iter().any(|event| matches!(event, LayerCompsEvent::Apply(_))), "a drag applies nothing");
assert_eq!(rig.reorders(), [(2, 0)], "Beta above Alpha is the first comp");
rig.fixture.drag(&alpha, Vec2::new(0.0, beta.rect.center().y - alpha.rect.center().y + step * 0.25));
rig.fixture.idle(3);
assert_eq!(rig.reorders(), [(1, 1)], "Alpha below Beta is the second comp");
rig.fixture.drag(&beta, Vec2::new(0.0, lds.rect.center().y - beta.rect.center().y - step * 0.25));
rig.fixture.idle(3);
assert_eq!(rig.reorders(), [(2, 0)], "above Last Document State is index 0");
let lds = rig.fixture.by_label("Last Document State").expect("the fixed row still shows");
let alpha = rig.fixture.by_label("Alpha").expect("the comp still shows");
assert!(lds.rect.top() < alpha.rect.top(), "Last Document State stays the first row");
}
/// Comp ids restart in every document, so the rename editor of comp 1 in one document is not the editor of comp 1 in
/// another.
#[trial]
fn a_rename_left_open_does_not_carry_over_to_another_document() {
let mut rig = rig();
let alpha = rig.fixture.by_label("Alpha").expect("the first comp shows");
rig.fixture.click(&alpha);
rig.fixture.idle(2);
rig.fixture.key(Key::F2, Modifiers::NONE);
rig.fixture.idle(2);
rig.fixture.type_text("X");
rig.fixture.key(Key::Enter, Modifiers::NONE);
rig.fixture.idle(2);
let renames = |seen: &Seen| -> Vec<(u64, String)> {
seen.borrow_mut()
.drain(..)
.filter_map(|event| if let LayerCompsEvent::Rename { comp, name, .. } = event { Some((comp, name)) } else { None })
.collect()
};
let first = renames(&rig.seen);
assert!(matches!(first.as_slice(), [(1, name)] if name.contains('X')), "F2 opens the editor of the selected comp: {first:?}");
rig.fixture.key(Key::F2, Modifiers::NONE);
rig.fixture.idle(2);
rig.document.set(1);
rig.fixture.idle(3);
assert!(rig.fixture.by_label("Gamma").is_some(), "the other document's comps show");
rig.fixture.type_text("Y");
rig.fixture.key(Key::Enter, Modifiers::NONE);
rig.fixture.idle(2);
let second = renames(&rig.seen);
assert!(second.is_empty(), "the editor of the first document does not open on the second's comp 1: {second:?}");
}
+1
View File
@@ -1,6 +1,7 @@
//! The integration binary of craft-layers: every test is a registered trial.
mod blend_rows;
mod comps;
mod panel_drag_menu;
mod panel_filter;
mod panel_input;
+72 -2
View File
@@ -2,10 +2,10 @@
//! Find Layers puts the caret in the Name field.
use craft_behavior::SelectionChange;
use craft_layers::ui::filter::{FilterBy, LayerAttribute, LayerFilter, SmartKind};
use craft_layers::ui::filter::{EffectKind, FilterBy, FilterKind, LayerAttribute, LayerFilter, SmartKind};
use craft_layers::ui::mock::FakeLayers;
use craft_layers::ui::panel::{LayersEvent, LayersPanel};
use craft_layers::ui::tree::{LayerPart, LayerSelection};
use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart, LayerSelection};
use craft_ui::contract::Bind;
use craft_ui::testing::{Fixture, trial};
use egui::Vec2;
@@ -113,6 +113,76 @@ fn the_app_decides_what_only_it_knows() {
assert_eq!(rig.rows(), ["Linked Logo"]);
}
/// The layers of the matching table, top first: a type layer, a group, two pixel layers (the lower one hidden and with
/// a stroke, Multiply) and a Normal group.
fn matching_layers() -> Vec<LayerInfo> {
let mut notes = LayerInfo::new("ink notes", LayerKind::Text);
notes.blend_key = String::from("normal");
let mut sheets = LayerInfo::new("Sheets", LayerKind::Group);
sheets.blend_key = String::from("pass_through");
let mut ink = LayerInfo::new("Ink", LayerKind::Pixel);
ink.blend_key = String::from("multiply");
ink.effect_kinds = vec![EffectKind::Stroke];
let mut paper = LayerInfo::new("Paper", LayerKind::Pixel);
paper.blend_key = String::from("normal");
paper.visible = false;
let mut normal = LayerInfo::new("Normal group", LayerKind::Group);
normal.blend_key = String::from("normal");
vec![notes, sheets, ink, paper, normal]
}
/// The names `filter` lists among `layers`.
fn listed<'a>(filter: &LayerFilter, layers: &'a [LayerInfo]) -> Vec<&'a str> {
layers.iter().filter(|info| filter.shows(info)).map(|info| info.name.as_str()).collect()
}
/// Each filter type lists the layers its rule matches: a group matches no kind, a name matches in any case with the
/// spaces trimmed, a group matches by name, the Mode select offers no Pass Through, and an opposite attribute lists
/// the rest, groups included.
#[trial]
fn each_filter_type_lists_its_matches() {
let layers = matching_layers();
let by = |edit: &dyn Fn(&mut LayerFilter)| {
let mut filter = LayerFilter::default();
edit(&mut filter);
filter
};
let cases: Vec<(LayerFilter, Vec<&str>, &str)> = vec![
(by(&|f| (f.by, f.kinds) = (FilterBy::Kind, vec![FilterKind::Pixel])), vec!["Ink", "Paper"], "Kind Pixel: groups match no kind"),
(by(&|f| (f.by, f.kinds) = (FilterBy::Kind, vec![FilterKind::Type])), vec!["ink notes"], "Kind Type"),
(
by(&|f| (f.by, f.name) = (FilterBy::Name, String::from(" INK "))),
vec!["ink notes", "Ink"],
"Name: part of it, any case, spaces trimmed",
),
(by(&|f| (f.by, f.name) = (FilterBy::Name, String::from("sheet"))), vec!["Sheets"], "Name: a group matches too"),
(by(&|f| (f.by, f.name) = (FilterBy::Name, String::from("nothing like it"))), vec![], "Name: no match"),
(by(&|f| (f.by, f.mode) = (FilterBy::Mode, String::from("multiply"))), vec!["Ink"], "Mode Multiply"),
(
by(&|f| (f.by, f.mode) = (FilterBy::Mode, String::from("normal"))),
vec!["ink notes", "Paper", "Normal group"],
"Mode Normal lists a Normal group and never a Pass Through one",
),
(by(&|f| (f.by, f.effect) = (FilterBy::Effect, EffectKind::Stroke)), vec!["Ink"], "Effect Stroke"),
(
by(&|f| (f.by, f.attribute) = (FilterBy::Attribute, LayerAttribute::NotVisible)),
vec![],
"Attribute Not Visible lists what Visible does not",
),
];
for (filter, want, case) in cases {
if filter.attribute == LayerAttribute::NotVisible && filter.by == FilterBy::Attribute {
let visible = by(&|f| (f.by, f.attribute) = (FilterBy::Attribute, LayerAttribute::Visible));
let shown = listed(&visible, &layers);
let rest: Vec<&str> = layers.iter().map(|info| info.name.as_str()).filter(|name| !shown.contains(name)).collect();
assert_eq!(listed(&filter, &layers), rest, "{case}");
assert!(rest.contains(&"Paper"), "{case}: the hidden layer is listed");
continue;
}
assert_eq!(listed(&filter, &layers), want, "{case}");
}
}
/// Find Layers switches to Name and selects the field's text, so typing replaces it.
#[trial]
fn find_layers_puts_the_caret_in_the_name_field_with_its_text_selected() {