appearance-w5: net change of 2 commits

- appearance-w5: written from its sheet
- appearance-w5: repair 1
This commit is contained in:
bflatastic
2026-11-21 21:27:15 +07:00
parent 43ed18ae66
commit 4d4790ee71
16 changed files with 543 additions and 162 deletions
+4 -4
View File
@@ -2,11 +2,11 @@
use std::hash::Hash;
use craft_behavior::{EditEvents, IconId};
use craft_behavior::{EditEvents, IconId, Selection};
use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::patterns::presets::{
PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetRowMenu, PresetState,
PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState,
};
use craft_ui::runtime::drag::DropZone;
use craft_ui::runtime::env::{Env, Label};
@@ -88,12 +88,12 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> {
}
let mut browser = PresetBrowser::new(label.clone(), state.reborrowed(), rows)
.toolbar(true)
.row_menu(PresetRowMenu::Standard) // P3(appearance-w5): ap.AP5
.reorder(PresetReorder::items_and_groups())
.thumb_range(BRUSH_THUMBS)
.footer(footer);
if let Some(key) = selected.take() {
browser = browser.selected(key);
browser = browser.selection(Bind::given(Selection::single(key)));
}
if let Some(zone) = drop_zone.take() {
browser = browser.drop_zone(zone);
+3 -3
View File
@@ -14,9 +14,9 @@ use craft_ui::form::SliderField;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::patterns::presets::{
CellShape, PickerField, PresetBrowser, PresetEvent, PresetFooterOptions, PresetPicker, PresetRow, PresetState, PresetView, PreviewPaint,
CellShape, PickerField, PresetBrowser, PresetEvent, PresetFooterOptions, PresetPicker, PresetRow, PresetState, PresetView,
};
use craft_ui::primitives::IconSpec;
use craft_ui::primitives::{FacePaint, IconSpec};
use craft_ui::runtime::env::{Env, Label, UnitKind};
use craft_ui::runtime::overlay::CloseReason;
use egui::{Pos2, Response, Ui};
@@ -283,7 +283,7 @@ pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
/// Paints the brush's current tip on the chip, as the app's engine draws it (its falloff, angle and roundness, a
/// sampled tip's shape); without it the chip shows the picked preset's tip.
#[prop]
tip: Option<PreviewPaint>,
tip: Option<FacePaint>,
}
/// The app's own rows of the picker's gear menu.
+19 -15
View File
@@ -1,11 +1,11 @@
//! The rows of the Brush Preset picker: a preset row shows the tip or the stroke by the parts the picker shows.
use craft_ui::list::ThumbAspect;
use craft_ui::patterns::presets::{PresetRow, PreviewPaint};
use craft_ui::primitives::ContentPainterCx;
use craft_ui::patterns::presets::PresetRow;
use craft_ui::primitives::FacePaint;
use craft_ui::runtime::env::Env;
use egui::Rect;
use std::sync::Arc;
use std::hash::{Hash, Hasher};
use super::settings::BrushCardParts;
use super::words::BrushPresetWords;
@@ -25,21 +25,25 @@ pub fn tip_thumb_scale(diameter: f64) -> f32 {
#[non_exhaustive]
pub struct BrushRowPaint {
/// The tip, white on dark themes as the engine renders it.
pub tip: PreviewPaint,
pub tip: FacePaint,
/// The stroke preview.
pub stroke: PreviewPaint,
pub stroke: FacePaint,
}
impl BrushRowPaint {
/// The painters of one preset.
pub fn new(
tip: impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static,
stroke: impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static,
) -> Self {
Self { tip: Arc::new(tip), stroke: Arc::new(stroke) }
/// The faces of one preset, each keyed by the host by the brush's identity.
pub fn new(tip: FacePaint, stroke: FacePaint) -> Self {
Self { tip, stroke }
}
}
/// The key of a tip drawn at `scale`: the tip's key and the scale, since one tip face draws at several scales.
fn scaled_key(tip: u64, scale: f32) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(tip, scale.to_bits()).hash(&mut hasher);
hasher.finish()
}
/// A preset row for the picker: `name` at `depth`, its size as the caption and in the accessible name
/// ("{name}, {size}"), and its picture by `parts`: the stroke band while the stroke shows, else the tip drawn at
/// [`tip_thumb_scale`] of `diameter`.
@@ -58,10 +62,10 @@ pub fn brush_row<K>(
let row =
PresetRow::item(key, name.clone(), depth).caption(size.clone()).accessible_name(words.preset_size.fill(&[("name", &name), ("size", &size)]));
if parts.normalised().stroke {
let stroke = Arc::clone(&paint.stroke);
row.preview(ThumbAspect::new(STROKE_ASPECT.0, STROKE_ASPECT.1), move |cx, rect| stroke(cx, rect))
row.preview_face(ThumbAspect::new(STROKE_ASPECT.0, STROKE_ASPECT.1), paint.stroke.clone())
} else {
let (tip, scale) = (Arc::clone(&paint.tip), tip_thumb_scale(diameter));
row.preview(ThumbAspect::SQUARE, move |cx, rect| tip(cx, Rect::from_center_size(rect.center(), rect.size() * scale)))
let (tip, scale) = (paint.tip.clone(), tip_thumb_scale(diameter));
let face = FacePaint::new(scaled_key(tip.key(), scale), move |cx, rect| tip.paint(cx, Rect::from_center_size(rect.center(), rect.size() * scale)));
row.preview_face(ThumbAspect::SQUARE, face)
}
}
+4 -3
View File
@@ -3,6 +3,7 @@
use craft_behavior::Mixed;
use craft_ui::contract::Bind;
use craft_ui::patterns::presets::PresetRow;
use craft_ui::primitives::FacePaint;
use craft_ui::runtime::env::Env;
use craft_ui::testing::pictures::{SampleTip, paint_tip, paint_wave};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
@@ -22,10 +23,10 @@ const MAX_SIZE: f64 = 5000.0;
/// The tip and stroke of a preset with `tip`, in the ink of the surface; a soft tip's stroke is wider and half
/// opaque.
fn paint(tip: SampleTip) -> BrushRowPaint {
let (width, alpha) = if tip == SampleTip::Soft { (0.19, 0.5) } else { (0.12, 1.0) };
let ((width, alpha), (tip_key, stroke_key)) = if tip == SampleTip::Soft { ((0.19, 0.5), (1, 2)) } else { ((0.12, 1.0), (3, 4)) };
BrushRowPaint::new(
move |cx, rect| paint_tip(cx, rect, tip, cx.ink()),
move |cx, rect| paint_wave(cx, rect, width, cx.ink().gamma_multiply(alpha)),
FacePaint::new(tip_key, move |cx, rect| paint_tip(cx, rect, tip, cx.ink())),
FacePaint::new(stroke_key, move |cx, rect| paint_wave(cx, rect, width, cx.ink().gamma_multiply(alpha))),
)
}
+2 -1
View File
@@ -2,6 +2,7 @@
//! family's [`PresetBrowser`]: the browser owns the grid, the list, the roving focus, the keys and the accessible tree;
//! the palette supplies the rows and paints each preset's thumbnail as a gradient ramp.
use craft_behavior::Selection;
use craft_ui::contract::{Bind, NoValue, Outcome, Pattern};
use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetRow, PresetState, PresetTiles};
use craft_ui::runtime::env::{Env, Label};
@@ -215,7 +216,7 @@ impl<'a> GradientPalette<'a> {
.room_height(most)
.thumb(thumb);
if let Some(selected) = self.selected {
browser = browser.selected(selected);
browser = browser.selection(Bind::given(Selection::single(selected)));
}
let out = browser.show(ui);
let mut picked = None;
+3 -3
View File
@@ -3,7 +3,7 @@
use std::sync::Arc;
use super::{PatternColors, PatternFillOptions, PatternSwatch, PatternWords};
use craft_behavior::{EditEvent, EditEvents, Mixed, NumberCodec};
use craft_behavior::{EditEvent, EditEvents, Mixed, NumberCodec, Selection};
use craft_color_ui::ui::{ColorPopover, PickedColor};
use craft_ui::buttons::Button;
use craft_ui::choice::Checkbox;
@@ -110,10 +110,10 @@ impl<'a> PatternFillEditor<'a> {
let browser = Field::new(words.pattern.clone()).id_salt("grid").show(ui, |ui, _| {
let thumbs = thumbnails.clone();
let mut browser = PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows)
.selected(current.pattern.clone())
.selection(Bind::given(Selection::single(current.pattern.clone())))
.cell_shape(CellShape::Square)
.view_lock(PresetView::Grid)
.row_menu(PresetRowMenu::Off); // P3(appearance-w5): ap.AP5
.row_menu(PresetRowMenu::Off);
if let Some(thumbs) = thumbs {
browser = browser.thumb(move |cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, String>| {
if let Some(swatch) = swatches.iter().find(|swatch| swatch.id == *info.key) {
+8 -2
View File
@@ -6,6 +6,7 @@ use craft_draw::ui::brush_presets::{BrushPick, BrushPickerState, BrushPickerValu
use craft_draw::ui::brush_settings::TipAngle;
use craft_ui::contract::{Bind, Role, SaveKey};
use craft_ui::patterns::presets::PresetEvent;
use craft_ui::primitives::FacePaint;
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
@@ -14,6 +15,11 @@ use std::rc::Rc;
const HARD: u32 = 2;
/// Rows whose tip and stroke paint nothing, each face with a key of its own.
fn silent() -> BrushRowPaint {
BrushRowPaint::new(FacePaint::new(1, |_, _| {}), FacePaint::new(2, |_, _| {}))
}
struct Host {
current: Option<u32>,
state: BrushPickerState<u32>,
@@ -26,7 +32,7 @@ fn rename_brush_opens_the_name_field_on_the_current_preset() {
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| {
let env = Env::of(ui);
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
let paint = silent();
let mut host = shown.borrow_mut();
let Host { current, state, picks } = &mut *host;
let rows =
@@ -89,7 +95,7 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc<RefCell<Opened>>)
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| {
let env = Env::of(ui);
let paint = BrushRowPaint::new(|_, _| {}, |_, _| {});
let paint = silent();
let mut host = shown.borrow_mut();
let Opened { current, state, values, open, tip_edits, at, offset } = &mut *host;
ui.add_space(*offset);
+1 -1
View File
@@ -46,7 +46,7 @@ pub(super) fn styles_page(ui: &mut Ui, presets: Option<&StylePresets<'_>>, words
if let Some(StylePresets { rows, thumb }) = presets {
let browser = PresetBrowser::new(words.styles.clone(), Bind::<PresetState<String>>::kept(), rows)
.thumb(move |cx, rect, info| thumb(cx, rect, info))
.row_menu(PresetRowMenu::Off) // P3(appearance-w5): ap.AP5
.row_menu(PresetRowMenu::Off)
.max_rows(STYLE_ROWS);
for event in browser.show(ui).events {
if let PresetEvent::Select { key, .. } | PresetEvent::Activate { key, .. } = event {
+1 -1
View File
@@ -16,7 +16,7 @@ pub struct FacePaint {
impl FacePaint {
/// A face identified by `key` that paints with `paint`.
pub fn new(key: u64, paint: impl Fn(&ContentPainterCx<'_>, Rect) + Send + Sync + 'static) -> Self {
FacePaint { key, paint: Arc::new(paint) }
Self { key, paint: Arc::new(paint) }
}
/// The key that identifies the face.
@@ -20,7 +20,8 @@ use super::words::PresetWords;
use crate::bars::{Bar, BarKind};
use crate::choice::Segmented;
use crate::contract::{
Bind, BodyCx, CollectionEvent, DropAt, DropMark, DropPlace, DropTarget, DropZone, Entry, ListDrag, OpenChange, Pattern, Props, Rename,
Bind, BodyCx, CollectionEvent, DropAt, DropKind, DropMark, DropPayload, DropPlace, DropTarget, DropZone, Entry, ListDrag, OpenChange, Pattern,
Props, Rename, TooltipSpec,
ReorderMove, ReorderRule, RowHeight, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename,
};
use crate::display::Divider;
@@ -33,13 +34,14 @@ use crate::runtime::drag;
use crate::runtime::env::{Env, Label};
use crate::runtime::memory::Remember as _;
use crate::text::TextField;
use crate::tile_grid::{CaptionPlace, GridEvent, TailRow, Tile, TileGrid, TileGroup, TileZoom};
use craft_behavior::{DisplayOrder, DropOperation, EditEvent, GesturePhase, IconId, ItemSource, Mixed, Selection, SelectionChange};
use crate::tile_grid::{CaptionPlace, GridEvent, GroupHeads, TailRow, Tile, TileGrid, TileGroup, TileZoom};
use craft_behavior::{DisplayOrder, DropOperation, EditEvent, GesturePhase, IconId, ItemSource, Mixed, Selection, SelectionChange, SelectionModel};
use craft_i18n::matcher::Matcher;
use craft_theme::variant::Tone;
use egui::{Id, Pos2, Rect, Ui};
use std::cell::RefCell;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::Arc;
/// The commands of a preset's context menu. They are app commands: the browser reports a run row as the event of the
@@ -81,6 +83,26 @@ impl<K> BrowserKey<K> {
BrowserKey::Action(_) => None,
}
}
/// The app's key of a preset or group row, `None` for an action row.
fn into_preset(self) -> Option<K> {
match self {
BrowserKey::Preset(key) => Some(key),
BrowserKey::Action(_) => None,
}
}
}
/// The app's change of a selection change the browser's collection reports: only the rows `selectable` accepts stay in
/// it, so action rows and groups are never part of the host's selection. Cell changes do not occur under the modes the
/// browser allows.
fn app_change<K>(change: SelectionChange<BrowserKey<K>>, selectable: impl Fn(&K) -> bool) -> Option<SelectionChange<K>> {
match change {
SelectionChange::Set(keys) => Some(SelectionChange::Set(keys.into_iter().filter_map(BrowserKey::into_preset).filter(|key| selectable(key)).collect())),
SelectionChange::Toggle(key) => key.into_preset().filter(|key| selectable(key)).map(SelectionChange::Toggle),
SelectionChange::Clear => Some(SelectionChange::Clear),
_ => None,
}
}
/// The app's drag of a drag the browser's collection carries: its presets and groups. `None` for a drag grabbed at an
@@ -113,10 +135,7 @@ impl<K: Clone + PartialEq> DropTarget<ListDrag<BrowserKey<K>>> for ZoneDrop<'_,
/// The app's move of a move the browser's collection reports. Only presets and groups drag, and only they take a drop
/// (`can_drag`, `accepts`), so every key of a move is one of the app's.
fn app_move<K>(mv: ReorderMove<BrowserKey<K>>) -> Option<ReorderMove<K>> {
let app = |key: BrowserKey<K>| match key {
BrowserKey::Preset(key) => Some(key),
BrowserKey::Action(_) => None,
};
let app = BrowserKey::into_preset;
Some(ReorderMove {
key: app(mv.key)?,
keys: mv.keys.into_iter().filter_map(app).collect(),
@@ -146,25 +165,63 @@ impl<'a, K> ThumbPainter<'a, K> {
type RowItemsFn<'a, K> = Box<dyn Fn(&K) -> Vec<Entry<String>> + 'a>;
/// The host's rows of the row menu for a target ([`PresetBrowser::row_items`]).
pub struct RowItems<'a, K>(#[allow(dead_code)] RowItemsFn<'a, K>); // P3(appearance-w5): ap.AP5
pub struct RowItems<'a, K>(RowItemsFn<'a, K>);
impl<'a, K> RowItems<'a, K> {
/// The rows that `items` gives for a target.
pub fn new(items: impl Fn(&K) -> Vec<Entry<String>> + 'a) -> Self {
RowItems(Box::new(items))
}
/// The rows for `key`: how the browser builds its row menu.
pub(super) fn items(&self, key: &K) -> Vec<Entry<String>> {
(self.0)(key)
}
}
/// Paints the tip of a tile or row on hover ([`PresetBrowser::tip`]).
pub(super) type TipFn<'a, K> = Box<dyn Fn(&mut Ui, &K) + 'a>;
/// The rows and the order the shown collection lists them in: what a drop needs to say where a payload landed in the
/// host's rows.
struct RowMap<'a, K> {
rows: &'a [PresetRow<K>],
/// The positions in `rows` of the collection's items, in display order.
displayed: Vec<usize>,
}
impl<K: Clone + Eq> RowMap<'_, K> {
/// The host's place of a place in the browser's collection; `None` where no drop lands: on a group or an action
/// row, or past the presets.
fn host(&self, at: &DropAt<BrowserKey<K>>) -> Option<DropAt<K>> {
match at {
DropAt::Onto(BrowserKey::Preset(key)) => self.rows.iter().any(|row| row.key == *key && !row.is_group()).then(|| DropAt::Onto(key.clone())),
DropAt::Gap { key, insert, .. } if *insert <= self.displayed.len() => {
let over = match key {
Some(BrowserKey::Action(_)) => return None,
Some(BrowserKey::Preset(key)) => Some(key.clone()),
None => None,
};
Some(DropAt::gap(over, full_position(self.rows, &self.displayed, &[], *insert)))
}
_ => None,
}
}
}
type DropMaker<'a, K> = Box<dyn Fn(Rc<RowMap<'a, K>>) -> DropKind<'a, BrowserKey<K>> + 'a>;
/// A drop target on the presets: a host payload of type `P` dropped onto a preset or between presets.
pub struct PresetDrop<'a, K> {
_marker: std::marker::PhantomData<(&'a (), K)>,
}
pub struct PresetDrop<'a, K>(DropMaker<'a, K>);
impl<'a, K> PresetDrop<'a, K> {
impl<'a, K: Clone + Eq + 'a> PresetDrop<'a, K> {
/// Takes payloads of type `P` at `place` where `accepts` agrees; the drop comes back as `PresetEvent::Dropped`.
pub fn new<P: Send + Sync + 'static>(place: DropPlace, accepts: impl Fn(&P, &DropAt<K>) -> bool + 'a) -> Self {
let _ = (place, accepts);
todo!("ap.AP2")
let accepts = Rc::new(accepts);
PresetDrop(Box::new(move |map| {
let accepts = Rc::clone(&accepts);
DropKind::new::<P>(place, move |payload, at| map.host(at).is_some_and(|at| accepts(payload, &at)))
}))
}
}
@@ -196,13 +253,15 @@ impl<'a> BrowserTools<'a> {
/// (Shift to the ends) reorder by the `reorder` rules. The host performs the delete, rename and move it is told of.
/// - **Search.** The toolbar's field keeps the presets whose name matches, with their groups, all open; Up, Down and
/// Enter go from the field to the presets.
/// - **Row menu.** Rename, Move to, Delete and the host's `extra_items` act on the row the menu was asked for, which the
/// browser keeps until the menu closes, else on `selected`.
/// - **Selection.** The host's `selection`, in the collection's modes (`select`): `Single` by default, `Multi` for
/// Shift ranges and Cmd/Ctrl toggles. `PresetEvent::Select` reports a plain pick only.
/// - **Row menu.** Rename, Move to, Delete and the host's `row_items` (`row_menu`) act on the row the menu was asked
/// for, which the browser keeps until the menu closes, else on the selection's lead.
/// - **Actions.** Rows after the presets, below a divider (`actions`): Down from the last preset reaches them, and a
/// click or Enter reports `PresetEvent::Action`. They are never selected, dragged or renamed.
///
/// ```ignore
/// let out = PresetBrowser::new("Swatches", Bind::bound(&mut state), &rows).selected(chosen.clone()).toolbar(true).show(ui);
/// let out = PresetBrowser::new("Swatches", Bind::bound(&mut state), &rows).selection(Bind::given(Selection::single(chosen.clone()))).toolbar(true).show(ui);
/// for event in out.events { /* the host applies Select, Activate, Reorder, ... */ }
/// ```
#[must_use = "show the browser with `show`"]
@@ -216,9 +275,7 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
browser_id: Option<Id>,
state: Bind<'a, PresetState<K>>,
rows: &'a [PresetRow<K>],
/// The selected preset, which the host keeps.
#[prop]
selected: Option<K>,
/// The host's selection. With `Bind::given`, every change comes out as `PresetEvent::Selection`; with
/// `Bind::bound`, the browser writes the binding.
#[prop]
@@ -251,8 +308,8 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// The host's controls at the reading end of the toolbar.
#[prop(func = "FnMut(&mut Ui)")]
tools: Option<BrowserTools<'a>>,
/// Whether a secondary click or the context-menu key opens the row menu: Rename, Move to, Delete and the host's
/// `extra_items`.
/// What a secondary click or the context-menu key opens: the standard row menu, the host's `row_items` alone, or
/// nothing.
#[prop]
row_menu: PresetRowMenu,
/// The host's rows of the row menu for a target, after the standard ones (or alone with `PresetRowMenu::Host`).
@@ -260,8 +317,10 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
row_items: Option<RowItems<'a, K>>,
/// Presets drag out as `ListDrag<K>`, without reorder or a drop zone.
#[prop]
#[allow(dead_code)] // P3(appearance-w5): ap.AP-drags
drags: bool,
/// How group heads show: titled rows, or full-width rules between the groups, which are always open.
#[prop]
group_heads: GroupHeads,
/// Fixes the view, whatever the state says; the toolbar then has no view buttons.
#[prop]
view_lock: Option<PresetView>,
@@ -285,8 +344,9 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// `reorder` presets still drag, to the zone and to the host's own drop targets only.
#[prop]
drop_zone: Option<DropZone>,
extra_items: Vec<Entry<String>>,
actions: Vec<Label>,
tip: Option<TipFn<'a, K>>,
drops: Vec<PresetDrop<'a, K>>,
/// A footer under the presets, made from these options with the browser's zoom bound to its slider and the count
/// of presets.
#[prop]
@@ -317,7 +377,6 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
browser_id: None,
state,
rows,
selected: None,
selection: None,
select: SelectMode::Single,
reveal: None,
@@ -331,6 +390,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
row_menu: PresetRowMenu::Standard,
row_items: None,
drags: false,
group_heads: GroupHeads::Titled,
view_lock: None,
can_rename: None,
can_delete: None,
@@ -338,8 +398,9 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
thumb: None,
reorder: None,
drop_zone: None,
extra_items: Vec::new(),
actions: Vec::new(),
tip: None,
drops: Vec::new(),
footer: None,
max_rows: None,
room_height: None,
@@ -350,16 +411,16 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
/// Takes host payloads dropped onto a preset or between presets; each drop comes back as `PresetEvent::Dropped`.
#[must_use]
pub fn takes_drop(self, drop: PresetDrop<'a, K>) -> Self {
let _ = (self, drop);
todo!("ap.AP2")
pub fn takes_drop(mut self, drop: PresetDrop<'a, K>) -> Self {
self.drops.push(drop);
self
}
/// Paints the tip that shows on hover over a tile or row.
#[must_use]
pub fn tip(self, f: impl Fn(&mut Ui, &K) + 'a) -> Self {
let _ = (self, f);
todo!("ap.AP3")
pub fn tip(mut self, f: impl Fn(&mut Ui, &K) + 'a) -> Self {
self.tip = Some(Box::new(f));
self
}
/// The id of the browser's list, the `ListDrag::list` of its drags: a footer action accepts only drags from its own
@@ -375,13 +436,6 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
self.actions = labels.into_iter().collect();
self
}
/// Rows added to the context menu after the standard ones; running one reports `PresetEvent::Menu` with the
/// entry's value.
pub fn extra_items(mut self, items: impl IntoIterator<Item = Entry<String>>) -> Self {
self.extra_items = items.into_iter().collect();
self
}
}
/// The rows the browser shows, as a display order over `rows`, then `actions` action rows.
@@ -506,17 +560,17 @@ fn grid_plan<K: Clone>(rows: &[PresetRow<K>], shown: &[usize], open: impl Fn(usi
plan
}
/// The position in the full row list that a reorder of the shown rows means: `mv.to` counts the rows that remain
/// shown once `mv.keys` are out; the result counts all rows that remain once the moved rows and the rows inside
/// moved groups are out, as the library's reorder takes it.
fn full_position<K: Eq>(rows: &[PresetRow<K>], shown: &[usize], mv: &ReorderMove<K>) -> usize {
/// The position in the full row list that a place `to` among the shown rows means: `to` counts the rows that remain
/// shown once `moved` are out (none for a drop); the result counts all rows that remain once the moved rows and the
/// rows inside moved groups are out, as the library's reorder takes it.
fn full_position<K: Eq>(rows: &[PresetRow<K>], shown: &[usize], moved: &[K], to: usize) -> usize {
let mut gone = vec![false; rows.len()];
for key in &mv.keys {
for key in moved {
if let Some(at) = rows.iter().position(|row| row.key == *key) {
gone[at..children_end(rows, at)].fill(true);
}
}
let anchor = shown.iter().copied().filter(|&at| !mv.keys.contains(&rows[at].key)).nth(mv.to);
let anchor = shown.iter().copied().filter(|&at| !moved.contains(&rows[at].key)).nth(to);
match anchor {
Some(anchor) => (0..anchor).filter(|&at| !gone[at]).count(),
None => gone.iter().filter(|gone| !**gone).count(),
@@ -554,7 +608,9 @@ struct Pass<K> {
}
enum Seen<K> {
Selection(SelectionChange<K>),
Select(K),
Dropped(DropAt<K>, DropOperation, DropPayload),
Activate(K),
Open(OpenChange<K>),
Menu(K),
@@ -564,20 +620,29 @@ enum Seen<K> {
}
/// The events of a collection that the browser acts on, whatever its items report.
fn seen<K, E>(events: Vec<CollectionEvent<K, E>>) -> Vec<Seen<K>> {
events
.into_iter()
.filter_map(|event| match event {
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.into_iter().last().map(Seen::Select), // P3(mechanical): dp.C12
CollectionEvent::Activate(key) => Some(Seen::Activate(key)),
CollectionEvent::Open(change) => Some(Seen::Open(change)),
CollectionEvent::ContextMenu(request) => Some(Seen::Menu(request.key)),
CollectionEvent::Reorder(edit) => Some(Seen::Reorder(edit)),
CollectionEvent::Rename(edit) => Some(Seen::Rename(edit)),
CollectionEvent::Delete(keys) => Some(Seen::Delete(keys)),
_ => None,
})
.collect()
fn seen<K: Clone, E>(events: Vec<CollectionEvent<K, E>>) -> Vec<Seen<K>> {
let mut out = Vec::with_capacity(events.len());
for event in events {
match event {
CollectionEvent::Selection { change, .. } => {
let picked = match &change {
SelectionChange::Set(keys) => keys.last().cloned(),
_ => None,
};
out.push(Seen::Selection(change));
out.extend(picked.map(Seen::Select)); // P3(mechanical): dp.C12
}
CollectionEvent::Activate(key) => out.push(Seen::Activate(key)),
CollectionEvent::Open(change) => out.push(Seen::Open(change)),
CollectionEvent::ContextMenu(request) => out.push(Seen::Menu(request.key)),
CollectionEvent::Reorder(edit) => out.push(Seen::Reorder(edit)),
CollectionEvent::Rename(edit) => out.push(Seen::Rename(edit)),
CollectionEvent::Delete(keys) => out.push(Seen::Delete(keys)),
CollectionEvent::Dropped { at, op, payload, .. } => out.push(Seen::Dropped(at, op, payload)),
_ => {}
}
}
out
}
/// What the browser keeps in its container's memory: the row the open menu was asked for, and the state as read and
@@ -611,7 +676,7 @@ fn commit<K: Clone + Eq + Hash + Send + Sync + 'static>(cx: &mut BodyCx<'_>, sta
}
}
impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
/// Asks the browser with the id `browser` (the one given to `browser_id`, or the `scope_id` of the `Ui`
/// it is shown in) to start renaming the row `key` at its next pass, as the row menu's Rename does. A key the
/// browser lacks or may not rename is ignored; the request is taken once.
@@ -626,10 +691,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
browser_id,
state,
rows,
selected,
selection: _,
select: _,
reveal: _,
selection,
select,
reveal,
cell_shape,
tiles: tile_size,
thumb_range,
@@ -638,8 +702,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
search,
mut tools,
row_menu,
row_items: _,
drags: _,
row_items,
drags,
group_heads,
view_lock,
can_rename,
can_delete,
@@ -647,8 +712,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
thumb,
reorder,
drop_zone,
extra_items,
actions,
tip: tip_painter,
drops,
footer,
max_rows,
room_height,
@@ -662,6 +728,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
let name = label.as_str().to_owned();
let has_footer = footer.is_some();
let state = RefCell::new(state);
let selection = RefCell::new(selection);
let footer_events: RefCell<Vec<PresetFooterEvent<K>>> = RefCell::new(Vec::new());
#[expect(
@@ -713,13 +780,26 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
let query = local.filter.trim().to_owned();
let matcher = (!query.is_empty()).then(|| Matcher::new(&env.folder(), &query));
let shown = shown_rows(rows, &local, default_open, matcher.as_ref());
// Under `Rule` every group is open and the state's open groups are not read.
let ruled_heads = group_heads == GroupHeads::Rule;
let all_open = PresetState::<K>::new();
let (opens, opens_default) = if ruled_heads { (&all_open, DefaultOpen::All) } else { (&local, default_open) };
let shown = shown_rows(rows, opens, opens_default, matcher.as_ref());
let open_flags: Vec<bool> = {
let test = local.open_test(rows, default_open);
let test = opens.open_test(rows, opens_default);
(0..rows.len()).map(test).collect()
};
let counted = |at: usize| rows[at].count.map(|n| words.group_count.text(n as u64, &env.format().integer(n as u64)));
let selection = selected.clone().map_or_else(|| Selection::new(Vec::new(), None, None), |key| Selection::single(BrowserKey::Preset(key)));
let mut held: Selection<K> = match selection.borrow_mut().as_mut().map(|bind| bind.reborrow().read(cx)) {
Some(Some(Mixed::Same(held))) => held,
_ => Selection::default(),
};
let shown_selection = Selection::new(
held.items.iter().cloned().map(BrowserKey::Preset).collect(),
held.lead.clone().map(BrowserKey::Preset),
held.anchor.clone().map(BrowserKey::Preset),
);
let payload_drag = reorder.is_some() || drop_zone.is_some() || !drops.is_empty() || drags;
let stamp = query_stamp(&query);
let zoom = local.zoom;
@@ -751,21 +831,22 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
};
let (response, displayed, pass) = if shown.is_empty() && actions.is_empty() {
let (response, map, pass) = if shown.is_empty() && actions.is_empty() {
let message = if query.is_empty() { empty_text.clone().unwrap_or_else(|| words.empty.clone()) } else { words.no_match.clone() };
let response = Notice::new(Tone::Neutral, message).layout(NoticeLayout::Centred).show(ui).response;
(response, Vec::new(), Pass { seen: Vec::new(), grid: Vec::new() })
(response, Rc::new(RowMap { rows, displayed: Vec::new() }), Pass { seen: Vec::new(), grid: Vec::new() })
} else if view == PresetView::Grid {
let plan = grid_plan(rows, &shown, |at| open_flags[at], counted);
let tiles = Shown { rows, at: plan.tiles.clone(), open: vec![false; plan.tiles.len()], tree: false, actions: 0 };
let map = Rc::new(RowMap { rows, displayed: plan.tiles.clone() });
let tail: Vec<TailRow<BrowserKey<K>>> =
actions.iter().enumerate().map(|(at, label)| TailRow::new(BrowserKey::Action(at), label.clone())).collect();
let aspect = card_aspect(cell_shape);
let grid = TileGrid::<BrowserKey<K>>::new(label.clone())
.id(list_id)
.select(SelectMode::Single)
.select(select)
.arrows_select(false)
.selection(Bind::given(selection))
.selection(Bind::given(shown_selection))
.aspect(aspect);
let grid = match tile_size {
PresetTiles::Thumbnails => {
@@ -780,7 +861,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
let mut grid = grid
.groups(&plan.groups)
.tail(&tail)
.collapsible()
.group_heads(group_heads)
.rename(true)
.deletable(true)
.rows_stamp(stamp)
@@ -791,15 +872,28 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
if reorder.is_some() {
grid = grid.reorder(ReorderRule::new());
}
if reorder.is_some() || drop_zone.is_some() {
if !ruled_heads {
grid = grid.collapsible();
}
if payload_drag {
grid = grid.drag_payload(app_drag::<K>);
}
for drop in &drops {
grid = grid.takes_drop((drop.0)(Rc::clone(&map)));
}
if let Some(key) = &reveal {
grid = grid.reveal(BrowserKey::Preset(key.clone()));
}
if let Some(rows) = max_rows {
grid = grid.max_rows(rows);
}
let aspect = cell_shape.aspect();
let out = grid.show_items(ui, &tiles, &mut |key, icx| {
let Some(row) = tiles.index_of(key).and_then(|at| tiles.row(at)) else { return Tile::new(Label::default()) };
if let Some(tip) = tip_painter.as_ref() {
let key = row.key.clone();
icx.tip(move |ui| tip(ui, &key));
}
let mut tile = Tile::new(row.label.clone());
if let Some(detail) = &row.caption {
tile = tile.detail(detail.clone());
@@ -817,17 +911,19 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
let draw = paint(row, selected);
tile.thumb(row.preview.as_ref().map_or(aspect, |preview| preview.aspect), move |cx, rect| draw(cx, rect, painter))
});
(out.response.response.clone(), plan.tiles.clone(), Pass { seen: seen(out.response.events), grid: out.events })
(out.response.response.clone(), map, Pass { seen: seen(out.response.events), grid: out.events })
} else {
let open: Vec<bool> = shown.iter().map(|&at| open_flags[at]).collect();
let source = Shown { rows, at: shown.clone(), open, tree: true, actions: actions.len() };
let map = Rc::new(RowMap { rows, displayed: shown.clone() });
let thumb_size = list_thumb(zoom);
let mut list = List::<BrowserKey<K>>::new(label.clone())
.id(list_id)
.tree(true)
.select(SelectMode::Single)
.group_heads(group_heads)
.select(select)
.arrows_select(false)
.selection(Bind::given(selection))
.selection(Bind::given(shown_selection))
.rename(true)
.deletable(true)
.rows_stamp(stamp)
@@ -837,9 +933,15 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
if reorder.is_some() {
list = list.reorder(ReorderRule::new().into_groups());
}
if reorder.is_some() || drop_zone.is_some() {
if payload_drag {
list = list.drag_payload(app_drag::<K>);
}
for drop in &drops {
list = list.takes_drop((drop.0)(Rc::clone(&map)));
}
if let Some(key) = &reveal {
list = list.reveal(BrowserKey::Preset(key.clone()));
}
if let Some(rows) = max_rows {
list = list.max_rows(rows);
}
@@ -863,6 +965,10 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
return line;
}
if let Some(tip) = tip_painter.as_ref() {
let key = row.key.clone();
icx.tip(move |ui| tip(ui, &key));
}
let mut line = ListRow::new(row.label.clone()).depth(row.depth).rule(ruled(icx.at));
if let Some(caption) = &row.caption {
line = line.detail(caption.clone());
@@ -876,15 +982,19 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
if let Some(name) = &row.accessible_name {
line = line.accessible_name(name.clone());
}
for (icon, name) in &row.trailing {
line = line.trailing_icon(icon.clone(), name.clone());
}
let draw = paint(row, icx.row.selected);
line.thumb_aspect(thumb_size, row.preview.as_ref().map_or(aspect, |preview| preview.aspect), move |cx, rect| {
draw(cx, rect, painter)
})
});
(out.response.clone(), shown.clone(), Pass { seen: seen(out.events), grid: Vec::new() })
(out.response.clone(), map, Pass { seen: seen(out.events), grid: Vec::new() })
};
let mods = crate::runtime::pointer::frame(ui.ctx()).mods;
let frame = crate::runtime::pointer::frame(ui.ctx());
let mods = frame.pick_mods;
let row_of = |key: &K| rows.iter().position(|row| row.key == *key);
if let Some(zone) = drop_zone {
let target = ZoneDrop { source: response.id, rows, zone };
@@ -893,6 +1003,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
}
let toggle = |local: &mut PresetState<K>, events: &mut Vec<PresetEvent<K>>, at: usize, open: Option<bool>| {
if ruled_heads {
return;
}
let open = open.unwrap_or_else(|| !local.is_open(rows, at, default_open));
let change = OpenChange::new(rows[at].key.clone(), open);
local.apply_open(rows, &change, default_open);
@@ -920,7 +1033,6 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
// A secondary press or release selects the row it lands on so that the row's menu acts on it; that selection
// is not a pick, and a picker would commit it.
let frame = crate::runtime::pointer::frame(ui.ctx());
let secondary =
frame.buttons.contains(craft_behavior::Buttons::SECONDARY) || frame.release == Some(craft_behavior::PointerButton::Secondary);
// An action row of the list is a plain row: a single press picks it, and Enter activates it. Its selection by
@@ -936,11 +1048,28 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
};
for event in pass.seen {
match event {
Seen::Selection(change) => {
let selectable = |key: &K| row_of(key).is_some_and(|at| !rows[at].is_group());
if let Some(change) = app_change(change, selectable) {
let before = held.clone();
held.apply(change.clone());
let edit = EditEvent::set(Mixed::Same(before), held.clone(), Arc::from(name.as_str()), None);
let written = selection.borrow_mut().as_mut().is_some_and(|bind| bind.reborrow().write(cx, &edit));
if !written {
events.push(PresetEvent::Selection(change));
}
}
}
Seen::Select(BrowserKey::Preset(key)) => {
if !secondary && row_of(&key).is_some_and(|at| !rows[at].is_group()) {
if !secondary && !mods.shift && !mods.cmd && row_of(&key).is_some_and(|at| !rows[at].is_group()) {
events.push(PresetEvent::Select { key, mods });
}
}
Seen::Dropped(at, op, payload) => {
if let Some(at) = map.host(&at) {
events.push(PresetEvent::Dropped { at, op, payload, mods });
}
}
Seen::Select(BrowserKey::Action(at)) => {
if list && first_press && !secondary {
action(&mut events, at);
@@ -957,7 +1086,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
}
Seen::Open(change) => {
if let BrowserKey::Preset(key) = change.key {
if !ruled_heads && let BrowserKey::Preset(key) = change.key {
let change = OpenChange { key, open: change.open, all: change.all };
local.apply_open(rows, &change, default_open);
events.push(PresetEvent::Open(change));
@@ -971,7 +1100,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
Seen::Reorder(edit) => {
let moved = |mv: ReorderMove<BrowserKey<K>>| {
let mv = app_move(mv)?;
let to = full_position(rows, &displayed, &mv);
let to = full_position(rows, &map.displayed, &mv.keys, mv.to);
Some(ReorderMove { to, ..mv })
};
events.extend(edit.filter_map(moved).map(PresetEvent::Reorder));
@@ -1002,8 +1131,8 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
}
if row_menu != PresetRowMenu::Off // P3(appearance-w5): ap.AP5
&& let Some(target) = menu_target.clone().or_else(|| selected.clone()).filter(|key| row_of(key).is_some())
if row_menu != PresetRowMenu::Off
&& let Some(target) = menu_target.clone().or_else(|| held.lead.clone()).filter(|key| row_of(key).is_some())
{
let at = row_of(&target).unwrap_or_default();
let group = rows[at].is_group();
@@ -1012,6 +1141,8 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
let movable = !group && can_move.as_ref().is_none_or(|test| test.passes(&target));
let home = rows[..at].iter().rposition(|row| row.is_group() && row.depth < rows[at].depth);
let destinations: Vec<usize> = (0..rows.len()).filter(|&to| rows[to].is_group() && Some(to) != home).collect();
let standard = row_menu == PresetRowMenu::Standard;
let host_rows = row_items.as_ref().map(|items| items.items(&target)).unwrap_or_default();
let mut ran: Vec<PresetEvent<K>> = Vec::new();
let menu = Menu::context(words.menu.clone(), &response).show(ui, |ui, _| {
let (rename, delete) = if group {
@@ -1019,10 +1150,10 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
} else {
(PresetItemCommands::Rename, PresetItemCommands::Delete)
};
if MenuItem::command(rename).enabled(renamable).show(ui).ran {
if standard && MenuItem::command(rename).enabled(renamable).show(ui).ran {
request_rename(ui.ctx(), list_id, &BrowserKey::Preset(target.clone()));
}
if movable && !destinations.is_empty() {
if standard && movable && !destinations.is_empty() {
let _ = Menu::submenu_row(ui, words.move_to.clone(), |ui, _| {
for &to in &destinations {
if MenuItem::new(Label::from(rows[to].label.clone())).show(ui).ran {
@@ -1031,17 +1162,20 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
});
}
if MenuItem::command(delete).enabled(deletable).show(ui).ran {
if standard && MenuItem::command(delete).enabled(deletable).show(ui).ran {
ran.push(PresetEvent::Delete(target.clone()));
}
if !extra_items.is_empty() {
if standard && !host_rows.is_empty() {
Divider::horizontal().show(ui);
}
for entry in &extra_items {
for entry in &host_rows {
if entry.is_separator() {
Divider::horizontal().show(ui);
} else if let Some(value) = entry.value() {
let row = MenuItem::new(entry.label().clone()).enabled(entry.is_enabled());
let mut row = MenuItem::new(entry.label().clone()).enabled(entry.is_enabled()).check(entry.is_checked());
if let Some(reason) = entry.why_disabled() {
row = row.tooltip(TooltipSpec::new(reason.clone()).disabled_text(reason.clone()));
}
if row.show(ui).ran {
ran.push(PresetEvent::Menu { target: target.clone(), command: value.clone() });
}
@@ -1,11 +1,16 @@
//! Stories of `PresetBrowser`.
use super::{PresetBrowser, PresetReorder};
use super::{PresetBrowser, PresetDrop, PresetReorder};
use crate::choice::SwatchFace;
use crate::contract::Bind;
use crate::contract::{Bind, DropAt, DropPlace, Entry, ListDrag, SelectMode};
use crate::list::ThumbAspect;
use crate::patterns::presets::{PresetEvent, PresetFooterOptions, PresetRow, PresetState, PresetTiles};
use crate::patterns::presets::{
CellShape, GroupHeads, PresetEvent, PresetFooterOptions, PresetRow, PresetRowMenu, PresetState, PresetTiles, PresetView,
};
use crate::primitives::IconSpec;
use crate::runtime::env::Label;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_behavior::{IconId, Selection, SelectionModel};
use craft_theme::Srgba;
use egui::Ui;
use egui::ecolor::{Color32, Hsva};
@@ -64,7 +69,7 @@ fn preset_browser(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.reorder(PresetReorder::items_and_groups().nest(NESTING))
.footer(PresetFooterOptions::new().slider(slider).new_group(new_group).can_delete(selected.is_some()));
if let Some(key) = selected {
browser = browser.selected(key);
browser = browser.selection(Bind::given(Selection::single(key)));
}
let out = browser.show(ui);
let selected = data.value("selected", None::<u32>);
@@ -80,6 +85,83 @@ fn preset_browser(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
StoryOutput::from(out).readout(readout)
}
/// Three presets selected under `SelectMode::Multi`, in both views: Shift extends from the anchor, Cmd/Ctrl toggles.
#[story(PresetBrowser<'static, u32>, covers = [], drive = Drive::Never)]
fn preset_browser_multi(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = library_rows();
let shown = data.value("selection", Selection::new(vec![1, 2, 3], Some(3), Some(1))).clone();
let out = PresetBrowser::new("Swatches", Bind::bound(data.value("state", PresetState::<u32>::new())), &rows)
.toolbar(true)
.select(SelectMode::Multi)
.selection(Bind::given(shown))
.show(ui);
let held = data.value("selection", Selection::<u32>::default());
for event in &out.events {
if let PresetEvent::Selection(change) = event {
held.apply(change.clone());
}
}
let readout = format!("Selected: {} presets", held.items.len());
StoryOutput::from(out).readout(readout)
}
/// Group heads as full-width rules between the groups, over wide chips, with no row menu.
#[story(PresetBrowser<'static, u32>, covers = [], drive = Drive::Never)]
fn preset_browser_rule_groups(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = library_rows();
PresetBrowser::new("Gradients", Bind::bound(data.value("state", PresetState::<u32>::new())), &rows)
.tiles(PresetTiles::Chips)
.cell_shape(CellShape::ratio(64, 28))
.group_heads(GroupHeads::Rule)
.row_menu(PresetRowMenu::Off)
.show(ui)
.into()
}
/// A drop target on the presets (a preset dragged onto another), and a row menu of the host's own rows.
// PLAN: the sheet's `DropAction` around the browser and `FooterBar` in a `Panel` footer are not shown: their builders are not in this set's bundle.
#[story(PresetBrowser<'static, u32>, covers = [], drive = Drive::Never)]
fn preset_browser_drops(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = library_rows();
let out = PresetBrowser::new("Swatches", Bind::bound(data.value("state", PresetState::<u32>::new())), &rows)
.view_lock(PresetView::List)
.drags(true)
.takes_drop(PresetDrop::new::<ListDrag<u32>>(DropPlace::Onto, |drag, at| matches!(at, DropAt::Onto(key) if *key != drag.grabbed)))
.row_menu(PresetRowMenu::Host)
.row_items(|key| {
vec![
Entry::new(String::from("use"), Label::from(format!("Use Preset {key}"))).checked(*key == 1),
Entry::new(String::from("lock"), Label::from(String::from("Lock"))).enabled(false).disabled_reason(Label::from(String::from("Already locked"))),
]
})
.show(ui);
let dropped = data.value("dropped", String::new());
for event in &out.events {
match event {
PresetEvent::Dropped { at, .. } => *dropped = format!("Dropped {at:?}"),
PresetEvent::Menu { target, command } => *dropped = format!("Menu {command} on Preset {target}"),
_ => {}
}
}
let readout = if dropped.is_empty() { String::from("Nothing dropped.") } else { dropped.clone() };
StoryOutput::from(out).readout(readout)
}
/// Trailing icons after a row's label in the list view, and a preset scrolled into view once.
#[story(PresetBrowser<'static, u32>, covers = [], drive = Drive::Never)]
fn preset_browser_trailing_and_reveal(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut rows = library_rows();
for row in rows.iter_mut().filter(|row| !row.is_group() && row.key % 5 == 0) {
row.trailing.push((IconSpec::svg(IconId::new("lock")), String::from("Locked")));
}
PresetBrowser::new("Swatches", Bind::bound(data.value("state", PresetState::<u32>::new())), &rows)
.view_lock(PresetView::List)
.max_rows(8)
.reveal(28)
.show(ui)
.into()
}
/// The chips variant: the same library as small bare chips under text-high group names, as a palette in a popover.
#[story(PresetBrowser<'static, u32>, covers = [], drive = Drive::Never)]
fn preset_browser_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
@@ -87,7 +169,7 @@ fn preset_browser_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let selected = *data.value("selected", None::<u32>);
let mut browser = PresetBrowser::new("Swatches", Bind::bound(data.value("state", PresetState::<u32>::new())), &rows).tiles(PresetTiles::Chips);
if let Some(key) = selected {
browser = browser.selected(key);
browser = browser.selection(Bind::given(Selection::single(key)));
}
let out = browser.show(ui);
let selected = data.value("selected", None::<u32>);
@@ -7,7 +7,7 @@ mod stories;
use super::browser::PresetBrowser;
use super::event::PresetEvent;
use super::footer::PresetFooterOptions;
use super::model::{PresetRow, PresetRowMenu};
use super::model::PresetRow;
use super::state::{PresetState, PresetView};
use super::words::PresetWords;
use crate::contract::{Bind, Entry, NoValue, Outcome, Pattern, Props, Show as _, ShowContainer as _};
@@ -152,7 +152,7 @@ impl<'a, G: Value, K: Clone + Eq + Hash + Send + Sync + 'static> PresetManager<'
PresetBrowser::new(title.clone(), Bind::<PresetState<K>>::kept(), rows)
.view_lock(PresetView::List)
.toolbar(false)
.row_menu(PresetRowMenu::Standard) // P3(appearance-w5): ap.AP5
.can_rename(|key| can_rename.as_ref().is_none_or(|test| test.passes(key)))
.can_delete(|key| can_delete.as_ref().is_none_or(|test| test.passes(key)))
.empty(empty.clone())
@@ -19,6 +19,7 @@ mod manager;
mod named;
mod picker;
pub use crate::tile_grid::GroupHeads;
pub use browser::{BrowserTools, PresetBrowser, PresetDrop, PresetItemCommands, PresetReorder, RowItems, ThumbPainter};
pub use event::{PresetEvent, PresetOutput};
pub use files::{PresetExport, PresetFileEvent, PresetFileFailure, PresetFileRequest, PresetFiles};
@@ -26,7 +27,7 @@ pub use footer::{PresetFooter, PresetFooterEvent, PresetFooterOptions, PresetFoo
pub use manager::{HostedPresetManager, PresetManager, PresetManagerOutput, PresetManagerTaken};
pub use model::{
CellShape, GroupPath, PresetChange, PresetError, PresetGroup, PresetId, PresetItem, PresetKey, PresetKind, PresetLibrary, PresetRow,
PresetRowMenu, PresetTiles, Preview, PreviewPaint, ThumbInfo, children_end, has_captions, nest_allowed,
PresetRowMenu, PresetTiles, Preview, ThumbInfo, children_end, has_captions, nest_allowed,
};
pub use named::{NameCheck, NamedPresetCommands, NamedPresetEvent, NamedPresetOutput, NamedPresetRow, NamedPresetStyle};
pub use panel_menu::{PresetCommands, PresetMenuAction, PresetPanelMenu};
@@ -7,11 +7,11 @@ mod library;
pub use library::{GroupPath, PresetChange, PresetError, PresetGroup, PresetId, PresetItem, PresetKey, PresetLibrary};
use crate::list::ThumbAspect;
use crate::primitives::{ContentPainterCx, IconSpec};
use crate::primitives::{ContentPainterCx, FacePaint, IconSpec};
use craft_behavior::IconId;
use egui::Rect;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
/// The shape of a grid cell's thumbnail.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -77,8 +77,11 @@ impl<'a, K> ThumbInfo<'a, K> {
}
}
/// Paints a [`Preview`] band into its rect.
pub type PreviewPaint = Arc<dyn Fn(&ContentPainterCx, Rect) + Send + Sync>;
/// The key of a face that no host named: one per call, counted down from the top so it cannot meet a host's own.
fn anonymous_face_key() -> u64 {
static NEXT: AtomicU64 = AtomicU64::new(0);
u64::MAX - NEXT.fetch_add(1, Ordering::Relaxed)
}
/// A second band of a list row, in list view only: the brush's stroke preview.
#[derive(Clone)]
@@ -87,7 +90,7 @@ pub struct Preview {
/// Width over height of the band.
pub aspect: ThumbAspect,
/// Paints the band into the rect, clipped to it.
pub paint: PreviewPaint,
pub paint: FacePaint,
}
impl fmt::Debug for Preview {
@@ -203,10 +206,18 @@ impl<K> PresetRow<K> {
self
}
/// Adds a band of `aspect` in list view, painted by `paint`.
/// Adds a band of `aspect` in list view, painted by `paint`. Each call makes a face of its own; a host that can
/// name the picture's identity gives a keyed face through [`preview_face`](Self::preview_face).
// PLAN: wg.W04's `FacePaint::new` needs a key and this builder has none to give; a counted key keeps every caller as it is.
#[must_use]
pub fn preview(mut self, aspect: ThumbAspect, paint: impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static) -> Self {
self.preview = Some(Preview { aspect, paint: Arc::new(paint) });
pub fn preview(self, aspect: ThumbAspect, paint: impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static) -> Self {
self.preview_face(aspect, FacePaint::new(anonymous_face_key(), paint))
}
/// Adds a band of `aspect` in list view, painted by `face`, which the host keys by the picture's identity.
#[must_use]
pub fn preview_face(mut self, aspect: ThumbAspect, face: FacePaint) -> Self {
self.preview = Some(Preview { aspect, paint: face });
self
}
@@ -10,10 +10,10 @@ mod stories;
use std::sync::Arc;
use super::browser::{BrowserTools, PresetBrowser, ThumbPainter};
use super::browser::{BrowserTools, PresetBrowser, ThumbPainter, TipFn};
use super::event::{PresetEvent, PresetOutput};
use super::footer::PresetFooterOptions;
use super::model::{CellShape, PresetRow, PresetRowMenu, PreviewPaint, ThumbInfo};
use super::model::{CellShape, PresetRow, PresetRowMenu, ThumbInfo};
use super::state::{DefaultOpen, PresetState, PresetView};
use super::words::PresetWords;
use crate::contract::{
@@ -24,13 +24,13 @@ use crate::layout_components::Stack;
use crate::list::RowTest;
use crate::pickers::{FaceKind, SelectFace};
use crate::popover::Popover;
use crate::primitives::ContentPainterCx;
use crate::primitives::{ContentPainterCx, FacePaint};
use crate::runtime::env::{EnvView, Label};
use crate::runtime::memory::StageAccess;
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceLook, UiTokens};
use crate::tile_grid::TileZoom;
use craft_behavior::{EditEvent, EditEvents, HitLevel, HitPriority, Intent, Metrics, Mixed, PartKey, PressPhase, Sense, Value};
use craft_behavior::{EditEvent, EditEvents, HitLevel, HitPriority, Intent, Metrics, Mixed, PartKey, PressPhase, Selection, Sense, Value};
use craft_keymap::Mods;
use egui::{Pos2, Rect, Response, Ui, Vec2};
use std::hash::Hash;
@@ -187,6 +187,7 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + 'static> {
/// Whether a secondary click or the context-menu key opens the browser's row menu.
#[prop]
row_menu: PresetRowMenu,
tip: Option<TipFn<'a, K>>,
/// Shown, muted, while the value is no preset of the rows.
#[prop(into)]
placeholder: Option<Label>,
@@ -228,7 +229,7 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + 'static> {
/// value the host holds when it is more than a preset (a brush's current tip). Without it the field shows the
/// picked preset's preview.
#[prop]
face_thumb: Option<PreviewPaint>,
face_thumb: Option<FacePaint>,
/// The columns of the popover's grid: the popover is as wide as this many tiles, at least its field.
#[prop]
columns: u16,
@@ -247,9 +248,9 @@ struct Session {
impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
/// Paints the tip that shows on hover over a tile or row of the picker's browser.
#[must_use]
pub fn tip(self, f: impl Fn(&mut Ui, &K) + 'a) -> Self {
let _ = (self, f);
todo!("ap.AP3")
pub fn tip(mut self, f: impl Fn(&mut Ui, &K) + 'a) -> Self {
self.tip = Some(Box::new(f));
self
}
/// A picker of patterns, built as [`new`](PresetPicker::new) is: the face shows the picked pattern's tile.
@@ -277,6 +278,7 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
can_delete: None,
can_move: None,
row_menu: PresetRowMenu::Standard,
tip: None,
placeholder: None,
display_name: None,
caption: None,
@@ -336,6 +338,7 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
can_delete,
can_move,
row_menu,
tip,
placeholder,
display_name,
caption,
@@ -420,7 +423,10 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
browser = browser.browser_id(id);
}
if let Some(key) = current.clone() {
browser = browser.selected(key);
browser = browser.selection(Bind::given(Selection::single(key)));
}
if let Some(tip) = tip.as_ref() {
browser = browser.tip(|ui, key| tip(ui, key));
}
if let Some(test) = can_rename.as_ref() {
browser = browser.can_rename(|key| test.passes(key));
@@ -484,9 +490,15 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
if let Some(browsed) = browsed {
for event in browsed.events {
match event {
PresetEvent::Select { key, .. } => pick = Some((key, !keep_open)),
PresetEvent::Activate { key, .. } => pick = Some((key, true)),
PresetEvent::Open(_) => {}
PresetEvent::Select { key, mods } => {
pick = Some((key, !keep_open));
out.mods = mods;
}
PresetEvent::Activate { key, mods } => {
pick = Some((key, true));
out.mods = mods;
}
PresetEvent::Open(_) | PresetEvent::Selection(_) => {}
PresetEvent::Action(at) => match actions.get(at) {
Some(&(_, true)) => out.create = true,
Some(&(_, false)) => out.detach = true,
@@ -546,7 +558,7 @@ struct PickerFace<'a, K: Value + Eq + Hash + 'static> {
placeholder: Option<Label>,
display_name: Option<Label>,
caption: Option<Label>,
face_thumb: Option<PreviewPaint>,
face_thumb: Option<FacePaint>,
edit_face: bool,
open: bool,
toggle: bool,
@@ -611,11 +623,11 @@ impl<K: Value + Eq + Hash + 'static> PickerFace<'_, K> {
let face = SelectFace::new(text);
if let Some(thumb) = self.face_thumb.as_ref().filter(|_| self.field != PickerField::Name) {
let face = if row.is_some() { face } else { face.placeholder() };
let draw = paint.then(|| Arc::clone(thumb));
let draw = paint.then(|| thumb.clone());
let face = face
.thumb(self.cell_shape.aspect(), move |cx, rect| {
if let Some(draw) = &draw {
draw(cx, rect);
draw.paint(cx, rect);
}
})
.name(!self.thumb_only());
@@ -631,7 +643,7 @@ impl<K: Value + Eq + Hash + 'static> PickerFace<'_, K> {
let face = face
.thumb(preview.aspect, move |cx, rect| {
if let Some(draw) = &draw {
draw(cx, rect);
draw.paint(cx, rect);
}
})
.name(field == PickerField::ThumbnailAndName);
+132 -3
View File
@@ -1,10 +1,11 @@
//! `PresetBrowser::drop_zone`: a preset dragged from the browser and released over the zone reports `DropAt`.
use craft_ui::contract::{Bind, DropZone};
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetRow, PresetState, PresetView};
use craft_behavior::{Selection, SelectionChange, SelectionModel};
use craft_ui::contract::{Bind, DropAt, DropPlace, DropZone, ListDrag, SelectMode};
use craft_ui::patterns::presets::{PresetBrowser, PresetDrop, PresetEvent, PresetRow, PresetState, PresetView};
use craft_ui::runtime::drag;
use craft_ui::testing::{Fixture, trial};
use egui::{Id, Key, Modifiers, Pos2, Rect, Sense, UiBuilder, pos2, vec2};
use egui::{Event, Id, Key, Modifiers, Pos2, PointerButton, Rect, Sense, UiBuilder, pos2, vec2};
use std::cell::RefCell;
use std::rc::Rc;
@@ -98,6 +99,134 @@ fn the_footer_stays_in_the_room_and_a_room_height_sizes_the_browser_to_its_prese
assert!(footer.bottom() <= 240.0, "a long library scrolls within the room height: {footer:?}");
}
type Events = Rc<RefCell<Vec<PresetEvent<u32>>>>;
/// Presets 1 to 4 in `view` under `SelectMode::Multi`, the selection kept by the test and given with `Bind::given`.
fn multi_rig(view: PresetView) -> (Fixture, Rc<RefCell<Selection<u32>>>, Events) {
let selection = Rc::new(RefCell::new(Selection::<u32>::default()));
let events: Events = Rc::new(RefCell::new(Vec::new()));
let (held, seen) = (selection.clone(), events.clone());
let rows: Vec<PresetRow<u32>> = (1..=4).map(|key| PresetRow::item(key, format!("Preset {key}"), 0)).collect();
let mut state = PresetState::<u32>::new();
let mut fixture = Fixture::new(move |ui| {
ui.scope_builder(UiBuilder::new().max_rect(BROWSER), |ui| {
let given = held.borrow().clone();
let out = PresetBrowser::new("Patterns", Bind::bound(&mut state), &rows)
.view_lock(view)
.select(SelectMode::Multi)
.selection(Bind::given(given))
.show(ui);
for event in out.events {
if let PresetEvent::Selection(change) = &event {
held.borrow_mut().apply(change.clone());
}
seen.borrow_mut().push(event);
}
});
});
fixture.room(vec2(480.0, 320.0)).settle();
(fixture, selection, events)
}
/// A primary click on preset `key` with `mods` held.
fn click_preset(fixture: &mut Fixture, key: u32, mods: Modifiers) {
let row = fixture.by_label(&format!("Preset {key}")).expect("the preset is shown");
fixture.hold(mods).click(&row);
fixture.hold(Modifiers::NONE);
fixture.idle(2);
}
/// A secondary press and release on preset `key`.
fn secondary_click_preset(fixture: &mut Fixture, key: u32) {
let at = fixture.by_label(&format!("Preset {key}")).expect("the preset is shown").center();
let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
fixture.frame(vec![Event::PointerMoved(at)]);
fixture.frame(vec![button(true)]);
fixture.frame(vec![button(false)]);
fixture.idle(2);
}
#[trial]
fn multi_selection_ranges_toggles_and_reports_select_only_for_a_plain_pick() {
for view in [PresetView::List, PresetView::Grid] {
let (mut fixture, selection, events) = multi_rig(view);
let items = || {
let mut items = selection.borrow().items.clone();
items.sort_unstable();
items
};
let selects = || events.borrow().iter().filter(|event| matches!(event, PresetEvent::Select { .. })).count();
click_preset(&mut fixture, 1, Modifiers::NONE);
assert_eq!((items(), selects()), (vec![1], 1), "a plain click selects and reports Select in {view:?}");
events.borrow_mut().clear();
click_preset(&mut fixture, 3, Modifiers::SHIFT);
assert_eq!((items(), selects()), (vec![1, 2, 3], 0), "Shift extends from the anchor and reports no Select in {view:?}");
click_preset(&mut fixture, 2, Modifiers::COMMAND);
assert_eq!((items(), selects()), (vec![1, 3], 0), "Cmd/Ctrl toggles and reports no Select in {view:?}");
let before = items();
fixture.key(Key::Space, Modifiers::COMMAND);
fixture.idle(2);
assert_ne!(items(), before, "Cmd/Ctrl+Space toggles the lead in {view:?}");
assert_eq!(selects(), 0, "Cmd/Ctrl+Space is no pick in {view:?}");
click_preset(&mut fixture, 4, Modifiers::NONE);
events.borrow_mut().clear();
secondary_click_preset(&mut fixture, 2);
assert!(
events.borrow().contains(&PresetEvent::Selection(SelectionChange::Set(vec![2]))),
"a secondary press on an unselected preset selects it first in {view:?}: {:?}",
events.borrow()
);
assert_eq!(selects(), 0, "a secondary press is no pick in {view:?}");
click_preset(&mut fixture, 3, Modifiers::COMMAND);
events.borrow_mut().clear();
secondary_click_preset(&mut fixture, 3);
assert_eq!(items(), vec![2, 3], "a secondary press on a selected preset leaves the selection whole in {view:?}");
}
}
#[trial]
fn a_payload_dropped_onto_a_preset_reports_dropped_and_wins_over_an_enclosing_drop_action() {
// (row grabbed, row released over, the preset reported)
let cases: [(&str, &str, Option<u32>); 2] = [("Preset 1", "Preset 2", Some(2)), ("Preset 1", "Group", None)];
for (grabbed, over, expected) in cases {
let events: Events = Rc::new(RefCell::new(Vec::new()));
let seen = events.clone();
let rows = vec![PresetRow::item(1, "Preset 1", 0), PresetRow::item(2, "Preset 2", 0), PresetRow::group(GROUP, "Group", 0), PresetRow::item(3, "Preset 3", 1)];
let mut state = PresetState::<u32>::new();
let mut fixture = Fixture::new(move |ui| {
ui.scope_builder(UiBuilder::new().max_rect(BROWSER), |ui| {
let out = PresetBrowser::new("Patterns", Bind::bound(&mut state), &rows)
.view_lock(PresetView::List)
.drags(true)
.takes_drop(PresetDrop::new::<ListDrag<u32>>(DropPlace::Onto, |drag, at| matches!(at, DropAt::Onto(key) if *key != drag.grabbed)))
.show(ui);
seen.borrow_mut().extend(out.events);
});
});
fixture.room(vec2(480.0, 320.0)).settle();
let from = fixture.by_label(grabbed).expect("the grabbed row is shown").center();
let to = fixture.by_label(over).expect("the row released over is shown").center();
fixture.hold(Modifiers::ALT).drag_at(from, to - from);
fixture.hold(Modifiers::NONE);
let dropped: Vec<(DropAt<u32>, bool)> = events
.borrow()
.iter()
.filter_map(|event| match event {
PresetEvent::Dropped { at, mods, .. } => Some((at.clone(), mods.alt)),
_ => None,
})
.collect();
let expected: Vec<(DropAt<u32>, bool)> = expected.into_iter().map(|key| (DropAt::Onto(key), true)).collect();
assert_eq!(dropped, expected, "{grabbed} released over {over}");
}
}
/// Delete and Backspace on the selected preset report the same `Delete` the row menu and the footer give, in both views.
#[trial]
fn delete_and_backspace_on_a_selected_preset_report_delete() {