mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
pdf-workflows-w2: net change of 3 commits
- pdf-workflows-w2: finished by an agent - pdf-workflows-w2: finished by an agent - pdf-workflows-w2: review fixes (review-1)
This commit is contained in:
@@ -172,7 +172,7 @@ where
|
||||
.caption(CaptionPlace::Below)
|
||||
.detail_line()
|
||||
.aspect(ASPECT)
|
||||
.zoom(GridZoom::Fixed(f64::from(state.settings.zoom))) // P3(pdf-workflows-w2): WF-W12
|
||||
.zoom(GridZoom::Fixed(state.settings.zoom))
|
||||
.rename(true)
|
||||
.deletable(true)
|
||||
.rows_stamp(stamp_of(state.shown.as_ref(), &state.search, state.settings.icon_sort.as_ref()))
|
||||
|
||||
@@ -172,7 +172,7 @@ const RECENT_LIMIT: usize = 25;
|
||||
/// The cell size of the grid and its zoom: factors of the medium thumbnail.
|
||||
pub const ZOOM: TileZoom = TileZoom::bounded(1.0, 2.625, 0.125, 1.25);
|
||||
/// The cells of the recents strip, as a factor of the medium thumbnail.
|
||||
const RECENT_ZOOM: f32 = 0.75;
|
||||
const RECENT_ZOOM: f64 = 0.75;
|
||||
/// The room round a glyph in its cell, as a fraction of the cell.
|
||||
const GLYPH_INSET_RATIO: f32 = 0.1;
|
||||
|
||||
@@ -382,7 +382,7 @@ impl<'a> GlyphsPanel<'a> {
|
||||
let mut activated: Option<String> = None;
|
||||
let strip = TileGrid::<usize>::new(words.recent.clone())
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.zoom(GridZoom::Fixed(f64::from(RECENT_ZOOM))) // P3(pdf-workflows-w2): WF-W12
|
||||
.zoom(GridZoom::Fixed(RECENT_ZOOM))
|
||||
.caption(CaptionPlace::None)
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
@@ -409,7 +409,7 @@ impl<'a> GlyphsPanel<'a> {
|
||||
let mut marked = cx.memory::<Marked>().clone();
|
||||
let grid = TileGrid::<usize>::new(words.grid.clone())
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.zoom(GridZoom::Fixed(f64::from(size as f32))) // P3(pdf-workflows-w2): WF-W12
|
||||
.zoom(GridZoom::Fixed(size))
|
||||
.caption(CaptionPlace::None)
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut marked.0))
|
||||
|
||||
@@ -698,14 +698,14 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
|
||||
let grid = match tile_size {
|
||||
PresetTiles::Thumbnails => {
|
||||
let captions = if has_captions(rows) { CaptionPlace::Below } else { CaptionPlace::None };
|
||||
grid.caption(captions).thumb_size(ThumbSize::Large).zoom(GridZoom::Fixed(zoom)) // P3(pdf-workflows-w2): L-64
|
||||
grid.caption(captions).thumb_size(ThumbSize::Large).zoom(GridZoom::Fixed(zoom))
|
||||
}
|
||||
// The zoom is a factor on the picture's width: a wide chip is the small thumbnail high.
|
||||
PresetTiles::Chips => {
|
||||
grid.caption(CaptionPlace::None)
|
||||
.thumb_size(ThumbSize::Small)
|
||||
.zoom(GridZoom::Fixed(f64::from(aspect.max(1.0))))
|
||||
.row_height(RowHeight::Text) // P3(pdf-workflows-w2): L-64
|
||||
.row_height(RowHeight::Text)
|
||||
}
|
||||
};
|
||||
let mut grid = grid
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! does the work: virtualisation, lead and selection rules, arrow, Home, End and page keys over the layout, type-ahead,
|
||||
//! drag with drop marks, OS file drops, the rename lifecycle and the context-menu request. The grid adds the layout,
|
||||
//! the pinned group headers and the tail rows after the tiles, which are rows of the grid's outline (section rows of
|
||||
//! the item step that hold the lead), and the rating keys. It owns what its cards have in common: where the
|
||||
//! caption goes, whether a detail line is reserved, and the zoom.
|
||||
//! the item step that hold the lead), the insert gaps between tiles and the rating keys. It owns what its cards have
|
||||
//! in common: where the caption goes, whether a detail line is reserved, where the hover actions sit, and the zoom.
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
mod stories;
|
||||
@@ -18,23 +18,27 @@ use crate::contract::{
|
||||
Role, RowHeight, RowState, SelectMode, Sizing, SpaceAction, SweepApply, SweepStep, ToggleColumn, section_part,
|
||||
};
|
||||
use crate::controls::disclosure::Disclosure;
|
||||
use crate::list::{DropTest, ListRow, ListRowStyle, RowTest, ThumbSize};
|
||||
use crate::primitives::{IconSpec, PaintShape, RectSide};
|
||||
use crate::list::{DropTest, ListRow, ListRowStyle, RowTest, ThumbSize, ToggleState};
|
||||
use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth};
|
||||
use crate::runtime::access::Name;
|
||||
use crate::runtime::commands::FireSource;
|
||||
use crate::runtime::env::Label;
|
||||
use crate::style::{ComponentStyle, RuleKind, StyleColor, StyleCx};
|
||||
use craft_behavior::{
|
||||
ColumnKey, ColumnWidth, HitLevel, HitPriority, Intent, ItemSource, Metrics, Mixed, PartKey, PointerButton, PressPhase, Selection, Sense,
|
||||
ColumnKey, ColumnWidth, EditEvent, HitLevel, HitPriority, Intent, ItemLayout as _, ItemSource, Metrics, Mixed, NavShape, PartKey, PointerButton,
|
||||
PressPhase, Roving, Selection, Sense,
|
||||
};
|
||||
use craft_keymap::{Chord, Key, Mods};
|
||||
use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2, pos2, vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The heading level of a group header: the grid's groups are its top-level sections.
|
||||
const GROUP_LEVEL: usize = 1;
|
||||
const TOGGLE: PartKey = PartKey::new("group_toggle");
|
||||
/// An insert gap, indexed by the display position it inserts before.
|
||||
const GAP: PartKey = PartKey::new("insert_gap");
|
||||
/// The keyboard path of the header parts: the header is a row of the outline, and the lead on it takes these keys.
|
||||
const HEADER_KEYS: &str = "Up and Down move to a group header; Enter picks it and Left and Right close and open it";
|
||||
/// The keyboard path of a tail row's part: the row is a row of the outline, and the lead on it takes Enter.
|
||||
@@ -58,10 +62,12 @@ pub enum RatingKeys {
|
||||
/// The size of a grid's tiles.
|
||||
#[non_exhaustive]
|
||||
pub enum GridZoom<'a> {
|
||||
/// A picture side factor the host holds.
|
||||
/// A picture side factor the host holds; the grid takes no zoom keys or wheel.
|
||||
Fixed(f64),
|
||||
/// A factor the grid steps itself: Cmd/Ctrl `=`, `-` and `0` and Ctrl/Cmd with the wheel or a pinch, through
|
||||
/// `TileZoom::step`, keeping the tile under the pointer in place.
|
||||
/// A factor the grid steps itself: Cmd/Ctrl `=` and `+`, `-` and `0` through `TileZoom::step`, and Ctrl/Cmd with
|
||||
/// the wheel or a pinch by the gesture's factor, inside the zoom's range, keeping the tile under the pointer in
|
||||
/// place. Cmd/Ctrl+0 is a rating key under `RatingKeys::CommandDigits`, so it clears the rating there instead of
|
||||
/// resetting the size. A binding that holds no single value reads as the zoom's default.
|
||||
Bound(Bind<'a, f64>, TileZoom),
|
||||
}
|
||||
|
||||
@@ -100,9 +106,6 @@ pub enum GridEvent<K> {
|
||||
/// The state asked for.
|
||||
open: bool,
|
||||
},
|
||||
/// Cmd/Ctrl with `=` or `+`, `-` or `0` on a grid that `zooms`: a step of the tile size. Cmd/Ctrl+0 is a rating key
|
||||
/// under `RatingKeys::CommandDigits`, so it clears the rating there instead of resetting the size.
|
||||
Zoom(ZoomStep),
|
||||
/// The insert gap before display position `at` was activated ([`TileGrid::insert_gaps`]).
|
||||
#[non_exhaustive]
|
||||
Insert {
|
||||
@@ -153,6 +156,10 @@ pub struct TileGridStyle {
|
||||
pinned: StyleColor,
|
||||
/// The look of a group header: a heading row, which places the disclosure the grid declares.
|
||||
header: ListRowStyle,
|
||||
/// The line down the middle of an insert gap under the pointer.
|
||||
insert: StyleColor,
|
||||
/// The width of an insert gap, centred on the edge of the tile it precedes.
|
||||
insert_width: f32,
|
||||
}
|
||||
|
||||
/// The sizes the grid lays its tiles out with.
|
||||
@@ -208,7 +215,8 @@ const WHEEL_SHARE: f32 = 1.0 / 3.0;
|
||||
/// menu. A double click on the background reports `CollectionEvent::EmptyActivated` (an import, in FilmCraft). One wheel
|
||||
/// notch scrolls a third of the grid's view.
|
||||
///
|
||||
/// The picture side is `zoom` times the thumbnail side (the card thumbnail unless `thumb_size` names one): the factor the app's zoom control holds. A card is the
|
||||
/// The picture side is `zoom` times the thumbnail side (the card thumbnail unless `thumb_size` names one): a factor the
|
||||
/// app holds, or one the grid steps itself through a binding (`GridZoom`). A card is the
|
||||
/// picture plus what the tile adds around it, whatever the layout. Pictures are `aspect` wide over high; with
|
||||
/// `justified` the tiles keep their own aspects (the source's `ItemSource::size_hint` as `SizeHint::Aspect`) and fill
|
||||
/// rows. `groups` put headers over runs of tiles; a header stays pinned at the top while its group scrolls. The grid
|
||||
@@ -240,10 +248,16 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
|
||||
aspect: f32,
|
||||
/// The picture side as a multiple of the thumbnail side the grid sizes from; 1 is that side.
|
||||
zoom: GridZoom<'a>,
|
||||
/// The zoom's factor as this pass was built with it: the layout of the pass reads it, and a step the pass takes
|
||||
/// shows in the next pass's layout, so the anchor is named against the layout the step changes from.
|
||||
factor: f64,
|
||||
/// Where the pointer was when `update` took a zoom chord in this pass: the point a key zoom keeps in place.
|
||||
chord_at: Option<Pos2>,
|
||||
/// Where every tile's hover actions sit.
|
||||
#[allow(dead_code)] // P3(pdf-workflows-w2): CV-C25
|
||||
#[prop]
|
||||
action_place: TileActionPlace,
|
||||
/// The names of the insert gaps, by the display position each inserts before; `None` shows no gaps.
|
||||
insert_gaps: Option<&'a dyn Fn(usize) -> Label>,
|
||||
/// The thumbnail size the zoom is a factor of; `None` is the card thumbnail.
|
||||
#[prop]
|
||||
thumb_size: Option<ThumbSize>,
|
||||
@@ -276,10 +290,6 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
|
||||
tail: &'a [TailRow<K>],
|
||||
/// Which keys rate the selected tiles.
|
||||
rating_keys: RatingKeys,
|
||||
/// The grid reports zoom steps: Cmd/Ctrl with `=`, `-` and `0` as `GridEvent::Zoom`, and Ctrl/Cmd with the wheel or a
|
||||
/// pinch as `CollectionEvent::Zoom`.
|
||||
#[prop(flag)]
|
||||
zooms: bool,
|
||||
/// Tiles show a check box and Space toggles the lead tile's check.
|
||||
checks: bool,
|
||||
/// Which tiles may be renamed; a rename request on another tile does nothing.
|
||||
@@ -300,6 +310,8 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
|
||||
placed: Vec<Placed>,
|
||||
/// The tail rows this pass shows, in the grid's layer space: the row's index and its rect.
|
||||
placed_tail: Vec<(usize, Rect)>,
|
||||
/// The insert gaps this pass shows, in the grid's layer space: the display position and the gap's rect.
|
||||
placed_gaps: Vec<(usize, Rect)>,
|
||||
/// The tail rows clicked this pass, in order.
|
||||
tail_clicked: Vec<K>,
|
||||
events: Vec<GridEvent<K>>,
|
||||
@@ -318,7 +330,7 @@ struct Placed {
|
||||
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
/// A grid named `label`, with multiple selection and equal square cards of the card thumbnail. Space picks the lead and
|
||||
/// no key rates or zooms; Bridge's keys are `rating_keys(RatingKeys::CommandDigits)`, `space(SpaceAction::Preview)`
|
||||
/// and `zooms()`.
|
||||
/// and a `GridZoom::Bound` zoom.
|
||||
pub fn new(label: impl Into<Label>) -> Self {
|
||||
TileGrid {
|
||||
common: Common::new(),
|
||||
@@ -330,7 +342,10 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
fill_row: false,
|
||||
aspect: 1.0,
|
||||
zoom: GridZoom::Fixed(1.0),
|
||||
factor: 1.0,
|
||||
chord_at: None,
|
||||
action_place: TileActionPlace::Corner,
|
||||
insert_gaps: None,
|
||||
thumb_size: None,
|
||||
content_cells: false,
|
||||
card_columns: 0,
|
||||
@@ -341,7 +356,6 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
collapsible: false,
|
||||
tail: &[],
|
||||
rating_keys: RatingKeys::None,
|
||||
zooms: false,
|
||||
checks: false,
|
||||
can_rename: None,
|
||||
can_drag: None,
|
||||
@@ -350,6 +364,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
laid: RefCell::new(None),
|
||||
placed: Vec::new(),
|
||||
placed_tail: Vec::new(),
|
||||
placed_gaps: Vec::new(),
|
||||
tail_clicked: Vec::new(),
|
||||
events: Vec::new(),
|
||||
}
|
||||
@@ -358,17 +373,47 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
|
||||
/// The size of the tiles: a factor the host holds, or one the grid steps itself through a binding.
|
||||
#[must_use]
|
||||
pub fn zoom(self, zoom: GridZoom<'a>) -> Self {
|
||||
let _ = zoom;
|
||||
todo!("WF-W12")
|
||||
pub fn zoom(mut self, mut zoom: GridZoom<'a>) -> Self {
|
||||
self.factor = match &mut zoom {
|
||||
GridZoom::Fixed(factor) => *factor,
|
||||
GridZoom::Bound(bind, steps) => Self::bound_factor(bind, *steps),
|
||||
};
|
||||
self.zoom = zoom;
|
||||
self
|
||||
}
|
||||
|
||||
/// Insert gaps between tiles, keyed by display position; `label` names the gap before a position. None show
|
||||
/// while a drag is held. A press on one reports [`GridEvent::Insert`].
|
||||
///
|
||||
/// The gap before position `at` sits on the reading-start edge of tile `at`, between tiles `at - 1` and `at`; the
|
||||
/// gap `at` = the tile count sits on the end edge of the last tile. A gap shows while its tile is in view, so the
|
||||
/// end gap shows only with the last tile in view.
|
||||
#[must_use]
|
||||
pub fn insert_gaps(self, label: &'a dyn Fn(usize) -> Label) -> Self {
|
||||
let _ = label;
|
||||
todo!("CV-C26")
|
||||
pub fn insert_gaps(mut self, label: &'a dyn Fn(usize) -> Label) -> Self {
|
||||
self.insert_gaps = Some(label);
|
||||
self
|
||||
}
|
||||
|
||||
/// The value a bound zoom holds; the zoom's default while the binding holds no single value.
|
||||
fn bound_factor(bind: &mut Bind<'_, f64>, steps: TileZoom) -> f64 {
|
||||
match bind.reborrow().get() {
|
||||
Some(Mixed::Same(factor)) if factor.is_finite() => factor,
|
||||
_ => steps.default_value(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a bound zoom's next factor, `to` of its value and the zoom, inside the zoom's range, as a `Set` named
|
||||
/// `label`. A fixed zoom is the host's: it takes nothing. Several steps in one pass chain on the written value.
|
||||
fn step_zoom(&mut self, label: &Arc<str>, to: impl FnOnce(f64, TileZoom) -> f64) {
|
||||
let GridZoom::Bound(bind, steps) = &mut self.zoom else { return };
|
||||
let steps = *steps;
|
||||
let before = Self::bound_factor(bind, steps);
|
||||
let range = steps.range();
|
||||
let after = to(before, steps).clamp(*range.start(), *range.end());
|
||||
if !after.is_finite() || after == before {
|
||||
return;
|
||||
}
|
||||
bind.reborrow().apply(&EditEvent::set(Mixed::Same(before), after, label.clone(), None));
|
||||
}
|
||||
|
||||
/// Which keys rate the selected tiles. Digit keys reach the grid as digits only while this is on.
|
||||
@@ -488,14 +533,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
fn picture_side(&self, style: &GridSizes, item: Option<Vec2>, around: Around) -> f32 {
|
||||
match item.filter(|_| self.content_cells) {
|
||||
Some(item) => (item.x - around.size().x).max(1.0),
|
||||
None => {
|
||||
// P3(pdf-workflows-w2): CV-C27: a bound zoom reads its binding's value.
|
||||
let zoom = match &self.zoom {
|
||||
GridZoom::Fixed(factor) => *factor as f32,
|
||||
_ => 1.0,
|
||||
};
|
||||
style.picture_side(zoom, self.thumb_size)
|
||||
}
|
||||
None => style.picture_side(self.factor as f32, self.thumb_size),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -523,6 +561,42 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares the insert gaps of the tiles in view, none while the grid's own drag is held: the gap before each tile
|
||||
/// in view, and the end gap with the last tile in view. The gaps are named by display position, so rows scrolled
|
||||
/// out of view change no position.
|
||||
fn place_gaps(&mut self, clip: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let dragging = crate::runtime::drag::active::<ListDrag<K>>(cx.ui.ctx()).is_some_and(|drag| drag.list == cx.id);
|
||||
if self.insert_gaps.is_none() || dragging {
|
||||
return;
|
||||
}
|
||||
let gaps = {
|
||||
let laid = self.laid.borrow();
|
||||
let Some(layout) = laid.as_ref() else { return };
|
||||
let (view, offset) = (cx.content_rect, cx.offset());
|
||||
let mut shown = Vec::new();
|
||||
layout.visible(offset, view.size(), &mut shown);
|
||||
let tiles: Vec<usize> = shown.into_iter().filter_map(|at| layout.tile_at(at)).collect();
|
||||
let count = layout.tiles();
|
||||
let end = (count > 0 && tiles.last() == Some(&(count - 1))).then_some(count);
|
||||
let width = cx.style.insert_width;
|
||||
let rtl = cx.flow.is_rtl();
|
||||
tiles
|
||||
.into_iter()
|
||||
.chain(end)
|
||||
.filter_map(|at| layout.gap(at, offset, width).map(|gap| (at, Self::group_rect(gap.translate(view.min.to_vec2()), view, rtl))))
|
||||
.filter(|(_, rect)| rect.intersects(clip))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let priority = HitPriority::new(HitLevel::Edge, 0);
|
||||
for &(at, rect) in &gaps {
|
||||
cx.part(GAP.at(at as u64), rect).sense(Sense::CLICK | Sense::FOCUS).priority(priority).over().focusable().state_layer();
|
||||
}
|
||||
if !gaps.is_empty() {
|
||||
cx.roving(Roving::new(NavShape::Flat));
|
||||
}
|
||||
self.placed_gaps = gaps;
|
||||
}
|
||||
|
||||
/// The header row of `group`: a heading at the group's depth, with its icon and its detail at the end, and a
|
||||
/// disclosure column the grid owns when the groups open and close.
|
||||
fn header_row(&self, group: &TileGroup<K>, state: RowState) -> ListRow<'static> {
|
||||
@@ -551,14 +625,18 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
|
||||
metrics: Metrics::new(),
|
||||
pinned: cx.color(cx.tokens.color.surface.panel),
|
||||
header: ListRow::style(cx, ListRow::new(Label::default()).heading().style_key()),
|
||||
insert: cx.color(cx.tokens.color.accent.solid),
|
||||
insert_width: cx.tokens.space.gap.stack,
|
||||
}
|
||||
}
|
||||
|
||||
/// One pointer part per header in view, over the tiles, and a disclosure part in it when headers collapse; one
|
||||
/// pointer part per tail row in view.
|
||||
/// pointer part per tail row in view; one focusable part per insert gap in view.
|
||||
fn parts(&mut self, area: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
self.placed.clear();
|
||||
self.placed_tail.clear();
|
||||
self.placed_gaps.clear();
|
||||
self.place_gaps(area, cx);
|
||||
let Some(arrangement) = self.laid.borrow().as_ref().and_then(|layout| layout.arrangement().cloned()) else { return };
|
||||
let (view, offset, rtl) = (cx.content_rect, cx.offset(), cx.flow.is_rtl());
|
||||
let pinned = arrangement.pinned(offset.y as f32);
|
||||
@@ -621,16 +699,24 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.zooms {
|
||||
if matches!(self.zoom, GridZoom::Bound(..)) {
|
||||
// A chord is input: a second pass of the frame takes none, so it neither steps again nor names a point.
|
||||
let reset = (self.rating_keys != RatingKeys::CommandDigits).then_some((Key::Num0, ZoomStep::Reset));
|
||||
let label = cx.core.label_arc();
|
||||
for (key, step) in [(Key::Equals, ZoomStep::In), (Key::Plus, ZoomStep::In), (Key::Minus, ZoomStep::Out)].into_iter().chain(reset) {
|
||||
let chord = Chord::new(Mods::CMD, key);
|
||||
cx.claim(chord);
|
||||
while cx.take_claimed(chord) {
|
||||
self.events.push(GridEvent::Zoom(step));
|
||||
self.step_zoom(&label, |value, steps| steps.step(value, step));
|
||||
self.chord_at = crate::runtime::pointer::frame(&cx.core.ctx).pos;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (at, _) in self.placed_gaps.clone() {
|
||||
if cx.part_activated(GAP.at(at as u64)).is_some() {
|
||||
self.events.push(GridEvent::Insert { at });
|
||||
}
|
||||
}
|
||||
let placed = self.placed.clone();
|
||||
for Placed { group, rect, .. } in placed {
|
||||
let Some(declared) = self.groups.get(group) else { continue };
|
||||
@@ -684,8 +770,13 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
|
||||
}
|
||||
}
|
||||
|
||||
/// A heading node per header and a list item node per tail row in view.
|
||||
/// A heading node per header, a list item node per tail row and a button per insert gap in view.
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
if let Some(label) = self.insert_gaps {
|
||||
for &(at, _) in &self.placed_gaps {
|
||||
access.node(GAP.at(at as u64), Role::BUTTON).name = Name::Text(cx.env.resolve(&label(at)).as_str().to_owned());
|
||||
}
|
||||
}
|
||||
let headers = self.placed.iter().map(|placed| Slot::Header(placed.group));
|
||||
let tails = self.placed_tail.iter().map(|&(at, _)| Slot::Tail(at));
|
||||
for slot in headers.chain(tails) {
|
||||
@@ -734,15 +825,33 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for TileGrid<'_, K>
|
||||
let state = RowState { emphasized: lead == Some(Slot::Tail(at)), ..RowState::default() };
|
||||
ui.face(section_part(&row.key), ListRow::new(row.label.clone()).rows(self.items.row_height).node(false).state(state));
|
||||
}
|
||||
// The gap under the pointer shows where an insertion lands; the part's state layer shows hover and focus.
|
||||
for &(at, rect) in &self.placed_gaps {
|
||||
if cx.hover_pos(GAP.at(at as u64)).is_some() {
|
||||
let line = PaintShape::Path(vec![rect.center_top(), rect.center_bottom()]);
|
||||
ui.draw().stroke(&line, StrokeWidth::Thick, style.insert);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid's events are the digits' and the stars' ratings, in that order, besides the collection's own. The
|
||||
/// collection's events on a header row are the group events instead: Enter picks the group, the context-menu
|
||||
/// key asks for its menu, Left and Right open and close it, and the lead on it is not reported. A tail row keeps its
|
||||
/// Enter and the lead on it, and adds its click as `CollectionEvent::Activate`; it has no menu.
|
||||
/// Enter and the lead on it, and adds its click as `CollectionEvent::Activate`; it has no menu. A bound zoom takes
|
||||
/// the wheel's and the pinch's `CollectionEvent::Zoom` here, after `content` named the point it keeps in place, and
|
||||
/// the event is not reported.
|
||||
fn finish(mut self, mut cx: Cx<'_, Self>) -> TileGridOutput<K> {
|
||||
let selected = self.rated(&cx);
|
||||
let mut response = cx.collection_response();
|
||||
let label = cx.core.label_arc();
|
||||
for event in &response.events {
|
||||
if let CollectionEvent::Zoom { factor, .. } = event {
|
||||
self.step_zoom(&label, |value, _| value * f64::from(*factor));
|
||||
}
|
||||
}
|
||||
if matches!(self.zoom, GridZoom::Bound(..)) {
|
||||
response.events.retain(|event| !matches!(event, CollectionEvent::Zoom { .. }));
|
||||
}
|
||||
let mut events = self.events;
|
||||
let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods;
|
||||
let group_of = |key: &K| self.groups.iter().position(|group| group.key == *key);
|
||||
@@ -818,13 +927,18 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
|
||||
self.reveal.as_ref()
|
||||
}
|
||||
|
||||
/// A bound zoom takes the wheel's zoom share; a fixed one is the host's.
|
||||
fn zooms(&self) -> bool {
|
||||
self.zooms
|
||||
matches!(self.zoom, GridZoom::Bound(..))
|
||||
}
|
||||
|
||||
/// While the zoom is bound: the point of this pass's wheel or pinch zoom, else the pointer a zoom chord was taken
|
||||
/// at in this pass's `update`; `None` keeps the first row in view.
|
||||
fn zoom_anchor(&self, wheel: Option<Pos2>) -> Option<Pos2> {
|
||||
let _ = wheel;
|
||||
todo!("WF-W12")
|
||||
match self.zoom {
|
||||
GridZoom::Bound(..) => wheel.or(self.chord_at),
|
||||
GridZoom::Fixed(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tiles with a header row before each group, then the tail rows: the rows the item step walks and the layout
|
||||
@@ -842,11 +956,12 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
|
||||
self.content_cells
|
||||
}
|
||||
|
||||
/// The caption place, the detail line and the card look, which `dress` gives every tile.
|
||||
/// The caption place, the detail line, the card look, the actions' place and whether checks show, which `dress`
|
||||
/// gives every tile.
|
||||
fn dress_inputs(&self) -> u64 {
|
||||
use std::hash::{Hash as _, Hasher as _};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
(self.caption, self.detail_line, self.card).hash(&mut hasher);
|
||||
(self.caption, self.detail_line, self.card, self.action_place, self.checks).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
@@ -876,9 +991,11 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
|
||||
self.laid_out(previous, source, width, item, cx)
|
||||
}
|
||||
|
||||
/// Every tile gets the grid's caption place and detail line, the card look, and its row's rename state.
|
||||
/// Every tile gets the grid's caption place, detail line and actions' place, the card look, and its row's rename
|
||||
/// state. Under `checks` a tile's check is its own selection, so the app keeps no second copy of it.
|
||||
fn dress<'r>(&self, tile: Self::Item<'r>, row: &RowState) -> Self::Item<'r> {
|
||||
let tile = tile.caption(self.caption).detail_line(self.detail_line).renaming(row.renaming);
|
||||
let tile = tile.caption(self.caption).detail_line(self.detail_line).action_place(self.action_place).renaming(row.renaming);
|
||||
let tile = if self.checks { tile.check(if row.selected { ToggleState::On } else { ToggleState::Off }) } else { tile };
|
||||
if self.card { tile.card() } else { tile }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! Stories of `TileGrid`.
|
||||
|
||||
use super::{GridEvent, GridZoom, RatingKeys, TileGrid, TileGridOutput, TileGroup};
|
||||
use crate::contract::{ShowCollection as _, SpaceAction};
|
||||
use crate::contract::{Bind, CollectionEvent, MiddleButton, ShowCollection as _, SpaceAction};
|
||||
use crate::list::ThumbAspect;
|
||||
use crate::runtime::env::Label;
|
||||
use crate::testing::pictures::StoryPictures;
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use crate::tile_grid::{BadgeKind, BadgeSlot, Tile, TileBadge, TileFlag, TileZoom};
|
||||
use craft_behavior::{DisplayOrder, ItemSource, SizeHint};
|
||||
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, pointer, story};
|
||||
use crate::tile_grid::stories::{ACTIONS, TileStoryCommand};
|
||||
use crate::tile_grid::{BadgeKind, BadgeSlot, Tile, TileActionPlace, TileBadge, TileFlag, TilePartEvent, TileZoom};
|
||||
use craft_behavior::{DisplayOrder, IconId, ItemSource, SizeHint};
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use egui::Ui;
|
||||
use egui::{Key, Modifiers, Ui, Vec2};
|
||||
|
||||
/// The keys of the group header rows, apart from the tiles' own.
|
||||
const GROUP_KEYS: [usize; 3] = [1000, 1001, 1002];
|
||||
@@ -98,21 +100,18 @@ impl ItemSource<usize> for Photos {
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid with Bridge's keys (Cmd/Ctrl+digit ratings, Space previews, Cmd/Ctrl + = / - / 0 zoom) at a zoom kept in the
|
||||
/// story's data, starting at `zoom`.
|
||||
/// The grid with Bridge's keys (Cmd/Ctrl+digit ratings, Space previews, Cmd/Ctrl + = / - / 0 and Ctrl/Cmd with the
|
||||
/// wheel zoom) over a ladder zoom bound to the story's data, starting at `zoom`.
|
||||
fn grid(ui: &mut Ui, data: &mut StoryData, grid: TileGrid<'_, usize>, count: usize, zoom: f64) -> TileGridOutput<usize> {
|
||||
let pictures = StoryPictures::of(ui.ctx());
|
||||
let zoom = data.value("zoom", zoom);
|
||||
let grid = grid.rating_keys(RatingKeys::CommandDigits).space(SpaceAction::Preview).zooms().zoom(GridZoom::Fixed(*zoom)); // P3(pdf-workflows-w2): WF-W12
|
||||
// The grid writes a copy of the story's zoom, which goes back after the pass, so the ratings can borrow the data.
|
||||
let mut held = *data.value("zoom", zoom);
|
||||
let bound = GridZoom::Bound(Bind::bound(&mut held), TileZoom::Ladder);
|
||||
let grid = grid.rating_keys(RatingKeys::CommandDigits).space(SpaceAction::Preview).zoom(bound);
|
||||
let mut ratings = Ratings::of(data, count);
|
||||
let out = grid.show_items(ui, &Photos(count), &mut |key, _| photo(&pictures, *key, ratings.0[*key]));
|
||||
ratings.apply(&out.events);
|
||||
let zoom = data.value("zoom", 1.0);
|
||||
for event in &out.events {
|
||||
if let GridEvent::Zoom(step) = event {
|
||||
*zoom = TileZoom::Ladder.step(*zoom, *step);
|
||||
}
|
||||
}
|
||||
*data.value("zoom", zoom) = held;
|
||||
out
|
||||
}
|
||||
|
||||
@@ -153,3 +152,101 @@ fn tile_grid_groups(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
|
||||
/// Focuses the grid and steps its zoom in.
|
||||
fn zoom_in(fixture: &mut Fixture) {
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(1);
|
||||
fixture.key(Key::Equals, Modifiers::COMMAND).idle(2);
|
||||
}
|
||||
|
||||
/// A zoom the grid steps itself: Cmd/Ctrl + = / - / 0 and Ctrl/Cmd with the wheel, keeping the tile under the pointer
|
||||
/// in place; the readout shows the bound factor.
|
||||
#[story(TileGrid<'static, usize>, covers = [], drive = Drive::Custom(zoom_in))]
|
||||
fn tile_grid_bound_zoom(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let out = grid(ui, data, TileGrid::new("Library"), 40, 1.0);
|
||||
let zoom = *data.value("zoom", 1.0);
|
||||
StoryOutput::from(out).readout(format!("Tile size: {zoom:.2}×"))
|
||||
}
|
||||
|
||||
/// Pages of the band story.
|
||||
const PAGES: usize = 12;
|
||||
|
||||
/// Hovers the second page, so its actions show, and clicks the first.
|
||||
fn band_action(fixture: &mut Fixture) {
|
||||
let Some(page) = fixture.by_label("Page 2") else { return };
|
||||
fixture.frame(vec![pointer::moved(page.center())]).idle(1);
|
||||
if let Some(action) = fixture.by_label(&format!("{:?}", ACTIONS[0])) {
|
||||
fixture.click(&action);
|
||||
}
|
||||
}
|
||||
|
||||
/// Page tiles whose hover actions sit in a band along the picture's lower edge, the place the grid gives every tile;
|
||||
/// the readout names the last action and its page.
|
||||
#[story(TileGrid<'static, usize>, covers = [], drive = Drive::Custom(band_action))]
|
||||
fn tile_grid_band_actions(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let pictures = StoryPictures::of(ui.ctx());
|
||||
let grid = TileGrid::new("Pages").action_place(TileActionPlace::Band);
|
||||
let out = grid.show_items(ui, &Photos(PAGES), &mut |key, _| {
|
||||
Tile::new(format!("Page {}", key + 1))
|
||||
.thumb(ThumbAspect::new(3, 4), pictures.thumb(*key as u64))
|
||||
.action(IconId::new("rotate_cw"), TileStoryCommand::Rotate)
|
||||
.action(IconId::new("trash"), TileStoryCommand::Remove)
|
||||
});
|
||||
let last = data.value("last", None::<String>);
|
||||
for event in &out.response.events {
|
||||
if let CollectionEvent::Item(key, TilePartEvent::Action(at)) = event
|
||||
&& let Some(name) = ACTIONS.get(*at)
|
||||
{
|
||||
*last = Some(format!("{name:?} page {}", key + 1));
|
||||
}
|
||||
}
|
||||
let readout = format!("Last action: {}", last.as_deref().unwrap_or("none"));
|
||||
StoryOutput::from(out).readout(readout)
|
||||
}
|
||||
|
||||
/// Photos of the insert gap story.
|
||||
const GAP_PHOTOS: usize = 12;
|
||||
|
||||
/// Clicks the gap before the third photo.
|
||||
fn insert_gap(fixture: &mut Fixture) {
|
||||
if let Some(gap) = fixture.by_label("Insert before photo 3") {
|
||||
fixture.click(&gap);
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert gaps between the tiles: the gap before each tile in view and the end gap with the last tile in view, each
|
||||
/// named by the display position it inserts before; the readout names the last one pressed.
|
||||
#[story(TileGrid<'static, usize>, covers = [], drive = Drive::Custom(insert_gap))]
|
||||
fn tile_grid_insert_gaps(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let name = |at: usize| {
|
||||
if at == GAP_PHOTOS { Label::from("Insert at the end") } else { Label::from(format!("Insert before photo {}", at + 1)) }
|
||||
};
|
||||
let out = grid(ui, data, TileGrid::new("Library").insert_gaps(&name), GAP_PHOTOS, 1.0);
|
||||
let inserted = data.value("inserted", None::<usize>);
|
||||
for event in &out.events {
|
||||
if let GridEvent::Insert { at, .. } = event {
|
||||
*inserted = Some(*at);
|
||||
}
|
||||
}
|
||||
let readout = match *inserted {
|
||||
Some(at) => format!("Inserted at position {}", at + 1),
|
||||
None => "Nothing inserted".to_owned(),
|
||||
};
|
||||
StoryOutput::from(out).readout(readout)
|
||||
}
|
||||
|
||||
/// A middle click in the grid latches auto-scroll, and the pointer below the latch point scrolls the grid down.
|
||||
fn middle_scroll(fixture: &mut Fixture) {
|
||||
let at = fixture.shown().center();
|
||||
fixture.frame(vec![pointer::moved(at)]);
|
||||
fixture.frame(vec![pointer::middle(at, true)]);
|
||||
fixture.frame(vec![pointer::middle(at, false)]);
|
||||
fixture.frame(vec![pointer::moved(at + Vec2::new(0.0, 60.0))]).idle(4);
|
||||
}
|
||||
|
||||
/// The middle button latches auto-scroll instead of panning: the items step paints the latch mark at the press point
|
||||
/// while the grid scrolls toward the pointer.
|
||||
#[story(TileGrid<'static, usize>, covers = [], drive = Drive::Custom(middle_scroll))]
|
||||
fn tile_grid_middle_button_scroll(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
grid(ui, data, TileGrid::new("Library").middle_button(MiddleButton::AutoScroll), 120, 1.0).into()
|
||||
}
|
||||
|
||||
@@ -563,6 +563,44 @@ impl GridLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many tiles the layout places, not counting group headers and tail rows.
|
||||
pub(super) fn tiles(&self) -> usize {
|
||||
match &self.kind {
|
||||
Kind::Equal { tiles, .. } => tiles.count,
|
||||
Kind::Arranged { arrangement, .. } => arrangement.tiles.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tile's display position at layout position `at`; `None` for a group header or a tail row.
|
||||
pub(super) fn tile_at(&self, at: usize) -> Option<usize> {
|
||||
match &self.kind {
|
||||
Kind::Equal { .. } => Some(at),
|
||||
Kind::Arranged { arrangement, starts, .. } => match slot_at(starts, arrangement.tiles.len(), at) {
|
||||
Slot::Tile(tile) => Some(tile),
|
||||
Slot::Header(_) | Slot::Tail(_) => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The insert gap before display position `at`, at `offset`, `width` wide and as high as the card it borders,
|
||||
/// left to right as `rect` places the cards: on the left edge of tile `at`, and for `at` = the tile count on the
|
||||
/// right edge of the last tile. Every row is cut the same way, so a gap names its position whichever rows are in
|
||||
/// view. `None` past the end and beside a tile the layout does not show (in a closed group).
|
||||
pub fn gap(&self, at: usize, offset: ScrollPos, width: f32) -> Option<Rect> {
|
||||
let count = self.tiles();
|
||||
let (tile, at_end) = if at < count { (at, false) } else if at == count { (count.checked_sub(1)?, true) } else { return None };
|
||||
let position = match &self.kind {
|
||||
Kind::Equal { .. } => tile,
|
||||
Kind::Arranged { starts, .. } => outline_position(starts, tile),
|
||||
};
|
||||
let card = self.rect(position, offset);
|
||||
if card == Rect::NOTHING {
|
||||
return None;
|
||||
}
|
||||
let x = if at_end { card.right() } else { card.left() };
|
||||
Some(Rect::from_center_size(pos2(x, card.center().y), vec2(width, card.height())))
|
||||
}
|
||||
|
||||
/// The card of tile `at` in the arrangement: its picture and what the tile adds around it.
|
||||
fn card(arrangement: &TileArrangement, around: Around, at: usize) -> Rect {
|
||||
let picture = arrangement.tiles.get(at).copied().unwrap_or(Rect::NOTHING);
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
//! Stories of `Tile` and `ThumbnailSlider`.
|
||||
|
||||
use super::{
|
||||
BadgeKind, BadgeSlot, BadgeVisibility, CaptionPlace, ThumbnailSlider, Tile, TileBadge, TileFlag, TileMark, TilePartEvent, TileStatus, TileZoom,
|
||||
BadgeKind, BadgeSlot, BadgeVisibility, CaptionPlace, StackLook, ThumbnailSlider, Tile, TileBadge, TileFlag, TileMark, TilePartEvent, TileStatus,
|
||||
TileZoom,
|
||||
};
|
||||
use crate::contract::{Bind, Props as _, Show as _, Validity};
|
||||
use crate::list::{ThumbAspect, ToggleState};
|
||||
use crate::runtime::env::Message;
|
||||
use crate::style::DataColor;
|
||||
use crate::testing::pictures::StoryPictures;
|
||||
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, pointer, story};
|
||||
use craft_behavior::{IconId, Mixed};
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use egui::Ui;
|
||||
use egui::{Color32, Ui};
|
||||
|
||||
const CAP: f64 = 4.0;
|
||||
const ZOOM_RANGE: TileZoom = TileZoom::bounded(0.5, 4.0, 0.25, 1.0);
|
||||
|
||||
/// The hover actions of the tile and grid action stories, in the order the tiles add them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui_macros::CommandSet)]
|
||||
#[command(prefix = "tileStory", story)]
|
||||
pub(super) enum TileStoryCommand {
|
||||
#[command(label = "Rotate", icon = "rotate_cw")]
|
||||
Rotate,
|
||||
#[command(label = "Remove", icon = "trash")]
|
||||
Remove,
|
||||
}
|
||||
|
||||
/// The action stories' actions, by the index `TilePartEvent::Action` reports. A variant is named as its label, so the
|
||||
/// stories find an action by the variant's name.
|
||||
pub(super) const ACTIONS: [TileStoryCommand; 2] = [TileStoryCommand::Rotate, TileStoryCommand::Remove];
|
||||
|
||||
#[story(Tile<'static>, covers = [Default], drive = Drive::Activate)]
|
||||
fn tile(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Tile::new("IMG_0001.jpg").detail("00:12").show(ui).into()
|
||||
@@ -50,6 +66,52 @@ fn tile_badges_and_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
out.into()
|
||||
}
|
||||
|
||||
/// A stack of pages shown as two offset sheets behind the picture instead of the ×N badge; the count stays in the
|
||||
/// tile's accessible name.
|
||||
#[story(Tile<'static>, covers = [], drive = Drive::Never)]
|
||||
fn tile_stack_sheets(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Tile::new("Scans.pdf")
|
||||
.thumb(ThumbAspect::new(3, 4), StoryPictures::of(ui.ctx()).thumb(5))
|
||||
.stack(3)
|
||||
.stack_look(StackLook::Sheets)
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Hovers the tile, so its actions show, and clicks the first.
|
||||
fn click_action(fixture: &mut Fixture) {
|
||||
let Some(tile) = fixture.by_label("IMG_0005.jpg") else { return };
|
||||
fixture.frame(vec![pointer::moved(tile.center())]).idle(1);
|
||||
if let Some(action) = fixture.by_label(&format!("{:?}", ACTIONS[0])) {
|
||||
fixture.click(&action);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two hover actions in the picture's corner, shown while the pointer is over the tile or it has visible focus; the
|
||||
/// readout names the last one run.
|
||||
#[story(Tile<'static>, covers = [], drive = Drive::Custom(click_action))]
|
||||
fn tile_actions(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let out = Tile::new("IMG_0005.jpg")
|
||||
.thumb(ThumbAspect::new(3, 2), StoryPictures::of(ui.ctx()).thumb(5))
|
||||
.action(IconId::new("rotate_cw"), TileStoryCommand::Rotate)
|
||||
.action(IconId::new("trash"), TileStoryCommand::Remove)
|
||||
.show(ui);
|
||||
let last = data.value("last", None::<String>);
|
||||
if let Some(TilePartEvent::Action(at)) = out.event
|
||||
&& let Some(name) = ACTIONS.get(at)
|
||||
{
|
||||
*last = Some(format!("{name:?}"));
|
||||
}
|
||||
let readout = format!("Last action: {}", last.as_deref().unwrap_or("none"));
|
||||
StoryOutput::from(out).readout(readout)
|
||||
}
|
||||
|
||||
/// An icon tile whose glyph takes a data hue, inked for contrast on the picture's surface.
|
||||
#[story(Tile<'static>, covers = [], drive = Drive::Never)]
|
||||
fn tile_hue(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Tile::new("Quarterly report.pdf").icon(IconId::new("file")).hue(DataColor::new(Color32::from_rgb(196, 64, 52))).show(ui).into()
|
||||
}
|
||||
|
||||
fn click_check(fixture: &mut Fixture) {
|
||||
if let Some(check) = fixture.by_label("Select IMG_0003.jpg") {
|
||||
fixture.click(&check);
|
||||
|
||||
@@ -46,15 +46,13 @@ pub enum TilePartEvent {
|
||||
},
|
||||
/// The pointer is over the picture: how far across it, from the reading start, 0 to 1.
|
||||
Scrub(f32),
|
||||
/// An activation of the corner action ([`Tile::corner_action`]).
|
||||
CornerAction,
|
||||
/// An activation of the `i`-th hover action ([`Tile::action`]), counted from 0 in the order added.
|
||||
Action(usize),
|
||||
}
|
||||
|
||||
/// Where a tile's hover actions sit.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum TileActionPlace {
|
||||
/// In the picture's end-top corner.
|
||||
#[default]
|
||||
@@ -111,7 +109,7 @@ const RATING: PartKey = PartKey::new("rating");
|
||||
const PILL: PartKey = PartKey::new("pill");
|
||||
const MARK: PartKey = PartKey::new("mark");
|
||||
const PICTURE: PartKey = PartKey::new("picture");
|
||||
const CORNER: PartKey = PartKey::new("corner");
|
||||
const ACTION: PartKey = PartKey::new("action");
|
||||
|
||||
const CHECK_REASON: &str = "In a tile grid with checks, Space toggles the lead tile's check";
|
||||
const RATING_REASON: &str = "In a tile grid with rating keys, the digits rate the selected tiles";
|
||||
@@ -133,6 +131,10 @@ struct Sizes {
|
||||
start: f32,
|
||||
/// The picture width of a tile measured on its own: least, and ideal (a grid's card thumbnail at zoom 1).
|
||||
thumbs: [f32; 2],
|
||||
/// How far each sheet of a stack shown as sheets lies from the one in front of it.
|
||||
sheet: f32,
|
||||
/// What the picture gives up at its reading end and bottom for the two sheets behind it.
|
||||
sheet_room: f32,
|
||||
}
|
||||
|
||||
/// What a tile adds around its picture for each caption arrangement, from the sizes: the grid sizes its cards with it.
|
||||
@@ -192,6 +194,8 @@ impl Sizes {
|
||||
detail_line: line,
|
||||
start: control.height,
|
||||
thumbs: [tokens.size.thumb.sm, tokens.size.thumb.card],
|
||||
sheet: tokens.space.gap.tight,
|
||||
sheet_room: 2.0 * tokens.space.gap.tight,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +280,10 @@ pub struct TileStyle {
|
||||
range: StyleColor,
|
||||
scrub: StyleColor,
|
||||
dot_edge: StyleColor,
|
||||
/// The fill of the sheets behind a stack shown as sheets.
|
||||
sheet: StyleColor,
|
||||
/// The edge of those sheets: the frame a picture has.
|
||||
sheet_edge: StyleColor,
|
||||
pill_radius: CornerRadius,
|
||||
plate_radius: CornerRadius,
|
||||
sizes: Sizes,
|
||||
@@ -292,12 +300,15 @@ struct Faces {
|
||||
check: Vec2,
|
||||
stars: Vec2,
|
||||
pill: f32,
|
||||
corner: Vec2,
|
||||
/// The largest face of the hover actions.
|
||||
action: Vec2,
|
||||
}
|
||||
|
||||
/// Where the parts of a tile lie in its content rect.
|
||||
struct Placed {
|
||||
picture: Rect,
|
||||
/// The sheets behind a stack shown as sheets, farthest first.
|
||||
sheets: Vec<Rect>,
|
||||
caption: Rect,
|
||||
name: Rect,
|
||||
detail: Option<Rect>,
|
||||
@@ -309,7 +320,8 @@ struct Placed {
|
||||
dot: Option<Rect>,
|
||||
check: Option<(Rect, Rect)>,
|
||||
pills: Vec<Rect>,
|
||||
corner: Option<Rect>,
|
||||
/// The hover actions, in the order added; empty while they are hidden.
|
||||
actions: Vec<Rect>,
|
||||
}
|
||||
|
||||
/// One tile of a tile grid.
|
||||
@@ -360,9 +372,12 @@ pub struct Tile<'a> {
|
||||
/// When the badge bar shows.
|
||||
#[prop]
|
||||
bar: BadgeVisibility,
|
||||
/// The size of the stack this tile stands for: a "×N" badge in the end-top corner.
|
||||
/// The size of the stack this tile stands for: a "×N" badge in the end-top corner, or sheets behind the picture
|
||||
/// (`stack_look`).
|
||||
#[prop]
|
||||
stack: Option<usize>,
|
||||
/// How the stack shows.
|
||||
stack_look: StackLook,
|
||||
/// The picture under a veil, still selectable.
|
||||
#[prop(flag)]
|
||||
dimmed: bool,
|
||||
@@ -382,11 +397,9 @@ pub struct Tile<'a> {
|
||||
#[prop]
|
||||
check: Option<ToggleState>,
|
||||
/// Where the hover actions sit: the grid's, applied to its tiles.
|
||||
#[allow(dead_code)] // P3(pdf-workflows-w2): CV-C25
|
||||
#[prop]
|
||||
action_place: TileActionPlace,
|
||||
/// The icon face reads in this colour from data in place of the face colour.
|
||||
#[allow(dead_code)] // P3(pdf-workflows-w2): CH-C10b
|
||||
#[prop]
|
||||
hue: Option<DataColor>,
|
||||
aspect: ThumbAspect,
|
||||
@@ -395,7 +408,7 @@ pub struct Tile<'a> {
|
||||
badges: Vec<TileBadge>,
|
||||
marks: Vec<TileMark>,
|
||||
pills: Vec<TileBadge>,
|
||||
corner: Option<(IconId, CommandRef)>,
|
||||
actions: Vec<(IconId, CommandRef)>,
|
||||
placed: Option<Placed>,
|
||||
event: Option<TilePartEvent>,
|
||||
caption_rect: Option<Rect>,
|
||||
@@ -420,6 +433,7 @@ impl<'a> Tile<'a> {
|
||||
scrub: None,
|
||||
bar: BadgeVisibility::Auto,
|
||||
stack: None,
|
||||
stack_look: StackLook::Badge,
|
||||
dimmed: false,
|
||||
rejected: false,
|
||||
hidden: false,
|
||||
@@ -434,7 +448,7 @@ impl<'a> Tile<'a> {
|
||||
badges: Vec::new(),
|
||||
marks: Vec::new(),
|
||||
pills: Vec::new(),
|
||||
corner: None,
|
||||
actions: Vec::new(),
|
||||
placed: None,
|
||||
event: None,
|
||||
caption_rect: None,
|
||||
@@ -461,19 +475,22 @@ impl<'a> Tile<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A hover action: an `IconButton::command` face shown while the pointer is over the tile or it has visible focus;
|
||||
/// repeatable. Its activation is [`TilePartEvent::Action`] with its index.
|
||||
/// A hover action: an `IconButton::command` face shown while the pointer is over the tile or it has visible focus,
|
||||
/// where `action_place` puts it, and reached by the keys as a part of the tile; repeatable. Its activation is
|
||||
/// [`TilePartEvent::Action`] with its index; `command` gives its label, tooltip and enabled state, and the tile
|
||||
/// does not fire it.
|
||||
#[must_use]
|
||||
pub fn action(self, icon: IconId, command: impl Into<CommandRef>) -> Self {
|
||||
let _ = (icon, command);
|
||||
todo!("CV-C25")
|
||||
pub fn action(mut self, icon: IconId, command: impl Into<CommandRef>) -> Self {
|
||||
self.actions.push((icon, command.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// How the stack of a stacked tile shows.
|
||||
/// How the stack of a stacked tile shows: the "×N" badge, or two sheets behind a picture that shrinks inside its
|
||||
/// cell to make room for them. The count stays in the accessible name either way.
|
||||
#[must_use]
|
||||
pub fn stack_look(self, look: StackLook) -> Self {
|
||||
let _ = look;
|
||||
todo!("WF-W11")
|
||||
pub fn stack_look(mut self, look: StackLook) -> Self {
|
||||
self.stack_look = look;
|
||||
self
|
||||
}
|
||||
|
||||
/// A corner badge.
|
||||
@@ -490,16 +507,6 @@ impl<'a> Tile<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// A button in the picture's end-top corner that shows while the pointer is over the tile or the tile has the
|
||||
/// keyboard focus, and is reached by the keys as a part of the tile. Its activation is
|
||||
/// [`TilePartEvent::CornerAction`]; `command` gives its label, tooltip and enabled state, and the tile does not
|
||||
/// fire it.
|
||||
#[must_use]
|
||||
pub fn corner_action(mut self, icon: IconId, command: impl Into<CommandRef>) -> Self {
|
||||
self.corner = Some((icon, command.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// What a tile adds around its picture: its padding, the caption band under the picture or the column at its
|
||||
/// reading start. A tile grid sizes a tile as the picture plus this.
|
||||
pub fn around_picture(cx: &StyleCx<'_>, place: CaptionPlace, detail: bool) -> Around {
|
||||
@@ -524,10 +531,10 @@ impl<'a> Tile<'a> {
|
||||
self.rating.is_some_and(|rating| rating > 0) || self.flag.is_some() || self.label_color.is_some()
|
||||
}
|
||||
|
||||
/// The corner badges: the app's, the stack badge and the file status badge.
|
||||
/// The corner badges: the app's, the stack badge unless the stack shows as sheets, and the file status badge.
|
||||
fn corner_badges(&self, words: &TileWords, units: &Units) -> Vec<TileBadge> {
|
||||
let mut all = self.badges.clone();
|
||||
if let Some(n) = self.stack {
|
||||
if let Some(n) = self.stack.filter(|_| self.stack_look == StackLook::Badge) {
|
||||
all.push(TileBadge::new(BadgeSlot::EndTop, BadgeKind::Text(Label::from(units.times(n as f64))), Tone::Neutral, None));
|
||||
}
|
||||
let failure = |text: &Label| TileBadge::new(BadgeSlot::StartBottom, BadgeKind::Text(text.clone()), Tone::Bad, None);
|
||||
@@ -573,6 +580,8 @@ impl<'a> Tile<'a> {
|
||||
}
|
||||
CaptionPlace::None => (Rect::NOTHING, Rect::NOTHING, None, Vec::new()),
|
||||
};
|
||||
// The sheets fit inside the cell the grid sizes, so the grid's card sizes stay those of a tile without them.
|
||||
let (picture, sheets) = self.stacked(picture, sizes, rtl);
|
||||
let pictures = Flow::new(picture, rtl);
|
||||
let mut floor = picture.bottom();
|
||||
let band_rect = matches!(self.status, TileStatus::Offline(_)).then(|| {
|
||||
@@ -613,10 +622,29 @@ impl<'a> Tile<'a> {
|
||||
let at = Rect::from_min_size(egui::pos2(across.min.x, picture.top() + margin), faces.check);
|
||||
(at, at.expand(sizes.tight))
|
||||
});
|
||||
let corner = self.corner.as_ref().map(|_| {
|
||||
let across = Flow::new(picture, rtl).span((picture.width() - margin - faces.corner.x).max(0.0), faces.corner.x);
|
||||
Rect::from_min_size(egui::pos2(across.min.x, picture.top() + margin), faces.corner)
|
||||
});
|
||||
let face = faces.action;
|
||||
let actions: Vec<Rect> = match self.action_place {
|
||||
// Stacked down from the end-top corner, `tight` apart, as the badges stack.
|
||||
TileActionPlace::Corner => (0..self.actions.len())
|
||||
.map(|at| {
|
||||
let across = pictures.span((picture.width() - margin - face.x).max(0.0), face.x);
|
||||
Rect::from_min_size(egui::pos2(across.min.x, picture.top() + margin + at as f32 * (face.y + sizes.tight)), face)
|
||||
})
|
||||
.collect(),
|
||||
// A row centred over the picture's lower edge, above the badge bar and the offline band.
|
||||
TileActionPlace::Band => {
|
||||
let count = self.actions.len() as f32;
|
||||
let row = count * face.x + (count - 1.0).max(0.0) * sizes.tight;
|
||||
let lead = (picture.width() - row) / 2.0;
|
||||
(0..self.actions.len())
|
||||
.map(|at| {
|
||||
let across = pictures.span(lead + at as f32 * (face.x + sizes.tight), face.x);
|
||||
Rect::from_min_size(egui::pos2(across.min.x, floor - margin - face.y), face)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
let action_plate = actions.iter().copied().reduce(|all, rect| all.union(rect)).map(|all| all.expand(sizes.tight));
|
||||
let corners = Rect::from_min_max(picture.min, egui::pos2(picture.right(), floor));
|
||||
let mut pills = vec![Rect::NOTHING; self.pills.len()];
|
||||
for slot in [BadgeSlot::StartTop, BadgeSlot::EndTop, BadgeSlot::StartBottom, BadgeSlot::EndBottom] {
|
||||
@@ -628,13 +656,30 @@ impl<'a> Tile<'a> {
|
||||
};
|
||||
let members: Vec<usize> = (0..self.pills.len()).filter(|&at| self.pills[at].slot == slot).collect();
|
||||
let widths: Vec<f32> = members.iter().map(|&at| pill_widths[at]).collect();
|
||||
let plate = if is_start { check.map(|(_, plate)| plate) } else { corner.map(|at| at.expand(sizes.tight)) };
|
||||
let plate = match (is_start, top, self.action_place) {
|
||||
(_, false, TileActionPlace::Band) | (false, _, TileActionPlace::Corner) => action_plate,
|
||||
(true, _, _) => check.map(|(_, plate)| plate),
|
||||
_ => None,
|
||||
};
|
||||
let rects = badge_rects(Flow::new(corners, rtl), &widths, faces.pill, sizes, plate, (is_start, top));
|
||||
for (at, rect) in members.into_iter().zip(rects) {
|
||||
pills[at] = rect;
|
||||
}
|
||||
}
|
||||
Placed { picture, caption, name, detail, marks, band: band_rect, bar, stars, flag, dot, check, pills, corner }
|
||||
Placed { picture, sheets, caption, name, detail, marks, band: band_rect, bar, stars, flag, dot, check, pills, actions }
|
||||
}
|
||||
|
||||
/// The picture and the sheets behind it: with `StackLook::Sheets` on a stack the picture gives up `sheet_room` at
|
||||
/// its reading end and bottom, and the sheets sit one and two `sheet` steps toward them, farthest first.
|
||||
fn stacked(&self, picture: Rect, sizes: &Sizes, rtl: bool) -> (Rect, Vec<Rect>) {
|
||||
if self.stack.is_none() || self.stack_look != StackLook::Sheets {
|
||||
return (picture, Vec::new());
|
||||
}
|
||||
let (front, _) = Flow::new(picture, rtl).take_start((picture.width() - sizes.sheet_room).max(0.0));
|
||||
let front = Rect::from_min_max(front.min, egui::pos2(front.max.x, (front.max.y - sizes.sheet_room).max(front.min.y)));
|
||||
let toward_end = if rtl { -1.0 } else { 1.0 };
|
||||
let sheets = [sizes.sheet_room, sizes.sheet].into_iter().map(|by| front.translate(Vec2::new(toward_end * by, by))).collect();
|
||||
(front, sheets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -735,6 +780,8 @@ impl Component for Tile<'_> {
|
||||
range: c(colors.accent.solid),
|
||||
scrub: c(colors.accent.solid),
|
||||
dot_edge: c(colors.line.mark),
|
||||
sheet: c(colors.surface.raised),
|
||||
sheet_edge: c(colors.line.frame),
|
||||
pill_radius: UiTokens::corner(tokens.shape.radius.pill),
|
||||
plate_radius: UiTokens::corner(tokens.shape.radius.sm),
|
||||
sizes,
|
||||
@@ -770,7 +817,10 @@ impl Component for Tile<'_> {
|
||||
check: cx.face(Checkbox::new(Bind::given(Mixed::Same(false)))),
|
||||
stars: cx.face(Rating::new(Bind::given(0u8), STARS).compact(true)),
|
||||
pill: cx.face(Badge::new("0")).y,
|
||||
corner: self.corner.as_ref().map_or(Vec2::ZERO, |(icon, command)| cx.face(IconButton::command(icon.clone(), command.clone()))),
|
||||
action: self
|
||||
.actions
|
||||
.iter()
|
||||
.fold(Vec2::ZERO, |most, (icon, command)| most.max(cx.face(IconButton::command(icon.clone(), command.clone())))),
|
||||
};
|
||||
let pill_widths: Vec<f32> = self.pills.iter().map(|badge| Self::badge_face(badge).map_or(faces.pill, |face| cx.face(face).x)).collect();
|
||||
let bar_shown = self.has_bar_content()
|
||||
@@ -800,11 +850,13 @@ impl Component for Tile<'_> {
|
||||
for (at, (mark, rect)) in self.marks.iter().zip(&placed.marks).enumerate() {
|
||||
let _ = cx.part(MARK.at(at as u64), *rect).tooltip(mark.tip.clone());
|
||||
}
|
||||
if let Some(at) = placed.corner.filter(|_| cx.hovered() || cx.focus_visible()) {
|
||||
cx.part(CORNER, at).sense(Sense::CLICK | Sense::FOCUS).focusable();
|
||||
if !placed.actions.is_empty() && (cx.hovered() || cx.focus_visible()) {
|
||||
for (at, rect) in placed.actions.iter().enumerate() {
|
||||
cx.part(ACTION.at(at as u64), *rect).sense(Sense::CLICK | Sense::FOCUS).focusable();
|
||||
}
|
||||
cx.roving(Roving::new(NavShape::Flat));
|
||||
} else {
|
||||
placed.corner = None;
|
||||
placed.actions.clear();
|
||||
}
|
||||
self.placed = Some(placed);
|
||||
}
|
||||
@@ -828,8 +880,10 @@ impl Component for Tile<'_> {
|
||||
if cx.part_activated(CHECK).is_some() {
|
||||
self.event = Some(TilePartEvent::Check { mods: cx.part(CHECK).press.mods });
|
||||
}
|
||||
if cx.part_activated(CORNER).is_some() {
|
||||
self.event = Some(TilePartEvent::CornerAction);
|
||||
for at in 0..self.actions.len() {
|
||||
if cx.part_activated(ACTION.at(at as u64)).is_some() {
|
||||
self.event = Some(TilePartEvent::Action(at));
|
||||
}
|
||||
}
|
||||
let current = self.rating.unwrap_or(0);
|
||||
while let Some(request) = cx.intents().take_access() {
|
||||
@@ -860,6 +914,13 @@ impl Component for Tile<'_> {
|
||||
let style = cx.style;
|
||||
let picture = placed.picture;
|
||||
let flat = CornerRadius::ZERO;
|
||||
{
|
||||
let draw = ui.draw();
|
||||
for sheet in &placed.sheets {
|
||||
draw.fill(&PaintShape::Rect(*sheet, flat), style.sheet);
|
||||
draw.stroke(&PaintShape::Rect(*sheet, flat), StrokeWidth::Thin, style.sheet_edge);
|
||||
}
|
||||
}
|
||||
{
|
||||
// Filled from the outside in, under the picture, so the rings sit outside its edge.
|
||||
let (ring, halo) = (cx.resolve(&style.ring_width), cx.resolve(&style.halo_width));
|
||||
@@ -871,21 +932,26 @@ impl Component for Tile<'_> {
|
||||
draw.fill(&PaintShape::Rect(picture.expand(ring), flat), cx.resolve(&style.ring));
|
||||
}
|
||||
}
|
||||
// A card's picture is the sunken surface, which the placeholder's fill matches.
|
||||
let placeholder = if !style.sizes.card && cx.env.surface() == SurfaceKind::Sunken { style.placeholder_on_sunken } else { style.placeholder };
|
||||
if style.sizes.card {
|
||||
ui.draw().surface(picture, SurfaceKind::Sunken, Corners::All);
|
||||
} else {
|
||||
let placeholder = if cx.env.surface() == SurfaceKind::Sunken { style.placeholder_on_sunken } else { style.placeholder };
|
||||
ui.draw().fill(&PaintShape::Rect(picture, flat), placeholder);
|
||||
}
|
||||
if let Some(paint) = self.first.take() {
|
||||
let _ = ui.child("picture", picture, RowThumb::new(paint));
|
||||
}
|
||||
let face_ink = match self.hue {
|
||||
Some(hue) => ui.with_style(cx.resolved.variant, |scx| scx.ink_of(hue, Rgba::from(placeholder.egui()))),
|
||||
None => cx.resolve(&style.face.color),
|
||||
};
|
||||
{
|
||||
let draw = ui.draw();
|
||||
let face = self.icon.take().or_else(|| self.folder.then(|| IconSpec::svg(IconId::new("folder"))));
|
||||
if let Some(face) = face {
|
||||
let icon = Rect::from_center_size(picture.center(), Vec2::splat(style.face.side));
|
||||
draw.icon(icon, &face.color(cx.resolve(&style.face.color)));
|
||||
draw.icon(icon, &face.color(face_ink));
|
||||
}
|
||||
if self.dimmed || self.rejected || self.hidden {
|
||||
draw.fill(&PaintShape::Rect(picture, flat), style.dim);
|
||||
@@ -895,8 +961,8 @@ impl Component for Tile<'_> {
|
||||
self.paint_band(ui, cx, &placed);
|
||||
self.paint_bar(ui, cx, &placed);
|
||||
self.paint_pills(ui, cx, &placed);
|
||||
if let (Some((icon, command)), Some(_)) = (&self.corner, placed.corner) {
|
||||
ui.face(CORNER, IconButton::command(icon.clone(), command.clone()));
|
||||
for (at, ((icon, command), _)) in self.actions.iter().zip(&placed.actions).enumerate() {
|
||||
ui.face(ACTION.at(at as u64), IconButton::command(icon.clone(), command.clone()));
|
||||
}
|
||||
if let (Some(state), Some((_, plate))) = (self.check, placed.check) {
|
||||
ui.draw().fill(&PaintShape::Rect(plate, style.plate_radius), style.plate);
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
//! The tile grid's layout: justified rows fill the width with whole cards (picture and what the tile adds around it).
|
||||
//! The tile grid's layout: justified rows fill the width with whole cards (picture and what the tile adds around it);
|
||||
//! a bound zoom that keeps the tile under the pointer in place; a drag whose tiles leave; insert gaps by display
|
||||
//! position.
|
||||
|
||||
use craft_ui::tile_grid::{Around, ArrangeSpacing, TileGroup, Tiling, arrange};
|
||||
use craft_behavior::keyed;
|
||||
use craft_ui::contract::{Bind, CollectionEvent, ReorderRule, ShowCollection as _};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::testing::{Fixture, pointer};
|
||||
use craft_ui::tile_grid::{Around, ArrangeSpacing, GridEvent, GridZoom, Tile, TileGrid, TileGroup, TileZoom, Tiling, ZoomStep, arrange};
|
||||
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
const WIDTH: f32 = 400.0;
|
||||
const ROW: f32 = 100.0;
|
||||
@@ -41,3 +51,163 @@ fn a_leading_group_header_sits_at_the_top_edge_and_ungrouped_tiles_keep_the_inse
|
||||
let loose = arrange::<usize>(&aspects, &[], WIDTH, Tiling::justified(ROW), spacing(), Around::default());
|
||||
assert!((loose.rows[0].top - INSET).abs() < EPS, "tiles that open the grid keep the inset above them");
|
||||
}
|
||||
|
||||
/// Tiles of the shown grids: enough rows to scroll several views.
|
||||
const TILES: usize = 120;
|
||||
|
||||
/// What a grid showed in its latest pass: each tile's rect, the grid's rect, and what it reported in every pass.
|
||||
struct Shown {
|
||||
tiles: HashMap<usize, Rect>,
|
||||
view: Rect,
|
||||
grid: Vec<GridEvent<usize>>,
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
/// Nothing shown yet, shared between a fixture's frames and the trial.
|
||||
fn shared() -> Rc<RefCell<Self>> {
|
||||
Rc::new(RefCell::new(Shown { tiles: HashMap::new(), view: Rect::NOTHING, grid: Vec::new() }))
|
||||
}
|
||||
|
||||
/// The tile whose centre is nearest `at`, and its rect.
|
||||
fn nearest(&self, at: Pos2) -> (usize, Rect) {
|
||||
let nearest = self.tiles.iter().min_by(|a, b| a.1.center().distance(at).total_cmp(&b.1.center().distance(at)));
|
||||
nearest.map(|(key, rect)| (*key, *rect)).expect("the grid shows tiles")
|
||||
}
|
||||
|
||||
/// The rect tile `key` has now.
|
||||
fn tile(&self, key: usize) -> Rect {
|
||||
self.tiles.get(&key).copied().expect("the tile stays in view")
|
||||
}
|
||||
}
|
||||
|
||||
/// A Ctrl/Cmd+wheel zoom and a Cmd/Ctrl+= step reflow the grid into another column count, and the tile under the
|
||||
/// pointer keeps its top through both.
|
||||
#[craft_ui::testing::trial]
|
||||
fn a_wheel_zoom_keeps_the_tile_under_the_pointer_in_place() {
|
||||
let zoom = Rc::new(Cell::new(TileZoom::Ladder.default_value()));
|
||||
let shown = Shown::shared();
|
||||
let (held_zoom, held) = (zoom.clone(), shown.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let keys: Vec<usize> = (0..TILES).collect();
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let mut value = held_zoom.get();
|
||||
held.borrow_mut().tiles.clear();
|
||||
let grid = TileGrid::new("Library").zoom(GridZoom::Bound(Bind::bound(&mut value), TileZoom::Ladder));
|
||||
let out = grid.show_items(ui, &source, &mut |key, icx| {
|
||||
held.borrow_mut().tiles.insert(*key, icx.rect);
|
||||
Tile::new(format!("Tile {key}"))
|
||||
});
|
||||
held_zoom.set(value);
|
||||
held.borrow_mut().view = out.response.response.rect;
|
||||
});
|
||||
fixture.room(Vec2::new(600.0, 400.0));
|
||||
fixture.settle();
|
||||
let view = shown.borrow().view;
|
||||
// A scrolled grid, so the kept tile has room to move either way.
|
||||
fixture.frame(vec![pointer::moved(view.center())]);
|
||||
fixture.frame(vec![pointer::wheel_lines(-2.0)]).settle();
|
||||
|
||||
let (key, before) = shown.borrow().nearest(view.center());
|
||||
fixture.frame(vec![pointer::moved(before.center())]);
|
||||
let start = zoom.get();
|
||||
fixture.frame(vec![pointer::zoom_wheel(120.0)]).settle();
|
||||
assert!(zoom.get() != start, "the wheel zoom moved the bound value from {start}");
|
||||
let after = shown.borrow().tile(key);
|
||||
assert!((after.top() - before.top()).abs() <= 1.0, "the tile under the pointer keeps its top: {before:?} to {after:?}");
|
||||
|
||||
let (key, _) = shown.borrow().nearest(view.center());
|
||||
let lead = shown.borrow().tile(key);
|
||||
fixture.click_at(lead.center()).settle();
|
||||
let before = shown.borrow().tile(key);
|
||||
let start = zoom.get();
|
||||
fixture.key(Key::Equals, Modifiers::COMMAND).settle();
|
||||
// Keeping the tile in place reruns the key's pass inside its frame; the rerun takes no input, so one step.
|
||||
assert_eq!(zoom.get(), TileZoom::Ladder.step(start, ZoomStep::In), "Cmd/Ctrl+= raised the bound value one step from {start}");
|
||||
let after = shown.borrow().tile(key);
|
||||
assert!((after.top() - before.top()).abs() <= 1.0, "the lead tile under the pointer keeps its top: {before:?} to {after:?}");
|
||||
}
|
||||
|
||||
/// A drag whose tiles leave the grid's source while it is held ends with no reorder; the same drag with its tiles
|
||||
/// still there reorders.
|
||||
#[craft_ui::testing::trial]
|
||||
fn a_drag_whose_tiles_leave_ends_without_a_reorder() {
|
||||
let keys = Rc::new(RefCell::new((0..6_usize).collect::<Vec<_>>()));
|
||||
let reorders = Rc::new(Cell::new(0_usize));
|
||||
let (held_keys, held_reorders) = (keys.clone(), reorders.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let keys = held_keys.borrow().clone();
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let grid = TileGrid::new("Library").reorder(ReorderRule::new());
|
||||
let out = grid.show_items(ui, &source, &mut |key, _| Tile::new(format!("Tile {key}")));
|
||||
let moved = out.response.events.iter().filter(|event| matches!(event, CollectionEvent::Reorder(_))).count();
|
||||
held_reorders.set(held_reorders.get() + moved);
|
||||
});
|
||||
fixture.room(Vec2::new(600.0, 400.0));
|
||||
fixture.settle();
|
||||
let rect = |fixture: &Fixture, key: usize| fixture.by_label(&format!("Tile {key}")).expect("the tile has a node").rect;
|
||||
let (from, onto) = (rect(&fixture, 1), rect(&fixture, 3));
|
||||
let by = onto.center() + Vec2::new(onto.width() / 4.0, 0.0) - from.center();
|
||||
fixture.drag_at(from.center(), by).settle();
|
||||
assert!(reorders.get() > 0, "a drag of a tile onto a later place reorders");
|
||||
|
||||
fixture.drag_at_pausing(from.center(), by, |fixture| {
|
||||
keys.borrow_mut().retain(|key| *key != 1);
|
||||
fixture.idle(2);
|
||||
reorders.set(0);
|
||||
});
|
||||
fixture.settle();
|
||||
assert_eq!(reorders.get(), 0, "a drag whose tile left the source ends without a reorder");
|
||||
}
|
||||
|
||||
/// With rows scrolled out of view, an insert gap is named by and reports the display position of the tile it
|
||||
/// precedes, sits on that tile's start edge, and no gap shows for a position out of view or past the tiles in view.
|
||||
#[craft_ui::testing::trial]
|
||||
fn insert_gaps_keep_document_positions_when_rows_are_virtualised() {
|
||||
let shown = Shown::shared();
|
||||
let held = shown.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let keys: Vec<usize> = (0..TILES).collect();
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let name = |at: usize| Label::from(format!("Insert before {}", at + 1));
|
||||
held.borrow_mut().tiles.clear();
|
||||
let grid = TileGrid::new("Library").insert_gaps(&name);
|
||||
let out = grid.show_items(ui, &source, &mut |key, icx| {
|
||||
held.borrow_mut().tiles.insert(*key, icx.rect);
|
||||
Tile::new(format!("Tile {key}"))
|
||||
});
|
||||
let mut seen = held.borrow_mut();
|
||||
seen.view = out.response.response.rect;
|
||||
seen.grid.extend(out.events);
|
||||
});
|
||||
fixture.room(Vec2::new(600.0, 300.0));
|
||||
fixture.settle();
|
||||
let view = shown.borrow().view;
|
||||
fixture.frame(vec![pointer::moved(view.center())]);
|
||||
for _ in 0..4 {
|
||||
fixture.frame(vec![pointer::wheel_lines(-3.0)]).idle(1);
|
||||
}
|
||||
fixture.settle();
|
||||
|
||||
let first = {
|
||||
let shown = shown.borrow();
|
||||
let inside = shown.tiles.iter().filter(|(_, rect)| rect.top() >= view.top() && rect.bottom() <= view.bottom());
|
||||
inside.map(|(key, _)| *key).min().expect("whole tiles show in the view")
|
||||
};
|
||||
assert!(first > 0, "the first rows scrolled out of view");
|
||||
assert!(fixture.by_label("Insert before 1").is_none(), "no gap shows before a tile out of view");
|
||||
assert!(fixture.by_label(&format!("Insert before {}", TILES + 1)).is_none(), "no end gap shows while the last tile is out of view");
|
||||
let gap = fixture.by_label(&format!("Insert before {}", first + 1)).expect("the first whole tile in view has a gap before it");
|
||||
let tile = shown.borrow().tile(first);
|
||||
let edge = gap.rect.center();
|
||||
assert!(
|
||||
(edge.x - tile.left()).abs() < tile.width() / 2.0 && tile.y_range().contains(edge.y),
|
||||
"the gap sits on the tile's start edge: {:?} beside {tile:?}",
|
||||
gap.rect
|
||||
);
|
||||
|
||||
shown.borrow_mut().grid.clear();
|
||||
fixture.click(&gap).settle();
|
||||
let inserts: Vec<usize> =
|
||||
shown.borrow().grid.iter().filter_map(|event| if let GridEvent::Insert { at, .. } = event { Some(*at) } else { None }).collect();
|
||||
assert_eq!(inserts, [first], "the gap reports the display position it inserts before, not a row index");
|
||||
}
|
||||
|
||||
@@ -1,30 +1,34 @@
|
||||
//! The tile grid's own keys and gestures: Bridge's rating and zoom keys, and the slow click that renames.
|
||||
|
||||
use craft_behavior::{EditEvent, keyed};
|
||||
use craft_ui::contract::{CollectionEvent, ShowCollection as _};
|
||||
use craft_ui::contract::{Bind, CollectionEvent, ShowCollection as _};
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use craft_ui::tile_grid::{GridEvent, RatingKeys, Tile, TileGrid, ZoomStep};
|
||||
use craft_ui::tile_grid::{GridEvent, GridZoom, RatingKeys, Tile, TileGrid, TileZoom};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
const NAMES: [&str; 4] = ["Tile 1", "Tile 2", "Tile 3", "Tile 4"];
|
||||
|
||||
/// What the grid reported, kept across frames.
|
||||
/// What the grid reported, kept across frames, and the zoom value a bound grid writes.
|
||||
#[derive(Default)]
|
||||
struct Seen {
|
||||
grid: Vec<GridEvent<usize>>,
|
||||
collection: Vec<CollectionEvent<usize, craft_ui::tile_grid::TilePartEvent>>,
|
||||
zoom: f64,
|
||||
}
|
||||
|
||||
fn rig(make: fn() -> TileGrid<'static, usize>) -> (Fixture, Rc<RefCell<Seen>>) {
|
||||
let seen = Rc::new(RefCell::new(Seen::default()));
|
||||
/// A four-tile grid `make` builds over the zoom value the rig keeps, which starts at the ladder's default.
|
||||
fn rig(make: for<'z> fn(&'z mut f64) -> TileGrid<'z, usize>) -> (Fixture, Rc<RefCell<Seen>>) {
|
||||
let seen = Rc::new(RefCell::new(Seen { zoom: TileZoom::Ladder.default_value(), ..Seen::default() }));
|
||||
let held = seen.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let keys = [0_usize, 1, 2, 3];
|
||||
let source = keyed(&keys, |key: &usize| *key);
|
||||
let out = make().show_items(ui, &source, &mut |key, _| Tile::new(NAMES[*key]));
|
||||
let mut zoom = held.borrow().zoom;
|
||||
let out = make(&mut zoom).show_items(ui, &source, &mut |key, _| Tile::new(NAMES[*key]));
|
||||
let mut seen = held.borrow_mut();
|
||||
seen.zoom = zoom;
|
||||
seen.grid.extend(out.events);
|
||||
seen.collection.extend(out.response.events);
|
||||
});
|
||||
@@ -33,42 +37,56 @@ fn rig(make: fn() -> TileGrid<'static, usize>) -> (Fixture, Rc<RefCell<Seen>>) {
|
||||
(fixture, seen)
|
||||
}
|
||||
|
||||
/// With Bridge's keys, Cmd/Ctrl with a digit rates the selected tile and with 0 clears it; Cmd/Ctrl with `=` and `-`
|
||||
/// step the zoom. Without the rating keys, Cmd/Ctrl+0 resets the zoom.
|
||||
/// The ladder zoom bound to `zoom`.
|
||||
fn bound(zoom: &mut f64) -> GridZoom<'_> {
|
||||
GridZoom::Bound(Bind::bound(zoom), TileZoom::Ladder)
|
||||
}
|
||||
|
||||
/// With Bridge's keys, Cmd/Ctrl with a digit rates the selected tile and with 0 clears it, leaving the zoom alone;
|
||||
/// Cmd/Ctrl with `=` raises the bound zoom and with `-` lowers it. Without the rating keys, Cmd/Ctrl+0 returns the
|
||||
/// zoom to its default.
|
||||
#[trial]
|
||||
fn command_digits_rate_and_command_equals_and_minus_zoom() {
|
||||
let (mut fixture, seen) = rig(|| TileGrid::new("Library").rating_keys(RatingKeys::CommandDigits).zooms());
|
||||
let (mut fixture, seen) = rig(|zoom| TileGrid::new("Library").rating_keys(RatingKeys::CommandDigits).zoom(bound(zoom)));
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(2);
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).idle(2);
|
||||
seen.borrow_mut().grid.clear();
|
||||
for key in [Key::Num3, Key::Num0, Key::Equals, Key::Minus] {
|
||||
let start = seen.borrow().zoom;
|
||||
for key in [Key::Num3, Key::Num0] {
|
||||
fixture.key(key, Modifiers::COMMAND).idle(1);
|
||||
}
|
||||
let reported: Vec<String> = std::mem::take(&mut seen.borrow_mut().grid)
|
||||
.into_iter()
|
||||
.map(|event| match event {
|
||||
GridEvent::Rate { keys, rating, .. } => format!("rate {keys:?} {rating}"),
|
||||
GridEvent::Zoom(step) => format!("zoom {step:?}"),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(reported, ["rate [0] 3", "rate [0] 0", "zoom In", "zoom Out"], "the selected tile is rated, then cleared; the zoom steps in and out");
|
||||
assert_eq!(reported, ["rate [0] 3", "rate [0] 0"], "the selected tile is rated, then cleared");
|
||||
assert_eq!(seen.borrow().zoom, start, "Cmd/Ctrl+0 is a rating key here and leaves the zoom");
|
||||
fixture.key(Key::Equals, Modifiers::COMMAND).idle(1);
|
||||
let raised = seen.borrow().zoom;
|
||||
assert!(raised > start, "Cmd/Ctrl+= raises the zoom: {start} to {raised}");
|
||||
fixture.key(Key::Minus, Modifiers::COMMAND).idle(1);
|
||||
let lowered = seen.borrow().zoom;
|
||||
assert!(lowered < raised, "Cmd/Ctrl+- lowers it: {raised} to {lowered}");
|
||||
assert!(seen.borrow().grid.is_empty(), "a zoom step is no grid event: {:?}", seen.borrow().grid);
|
||||
|
||||
let (mut fixture, seen) = rig(|| TileGrid::new("Library").zooms());
|
||||
let (mut fixture, seen) = rig(|zoom| TileGrid::new("Library").zoom(bound(zoom)));
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(2);
|
||||
fixture.key(Key::Equals, Modifiers::COMMAND).idle(1);
|
||||
fixture.key(Key::Equals, Modifiers::COMMAND).idle(1);
|
||||
assert!(seen.borrow().zoom > TileZoom::Ladder.default_value(), "two steps in leave the default");
|
||||
fixture.key(Key::Num0, Modifiers::COMMAND).idle(1);
|
||||
assert!(
|
||||
matches!(seen.borrow().grid.as_slice(), [GridEvent::Zoom(ZoomStep::Reset)]),
|
||||
"without rating keys Cmd/Ctrl+0 resets the zoom: {:?}",
|
||||
seen.borrow().grid
|
||||
);
|
||||
assert_eq!(seen.borrow().zoom, TileZoom::Ladder.default_value(), "without rating keys Cmd/Ctrl+0 returns the zoom to its default");
|
||||
assert!(seen.borrow().grid.is_empty(), "and rates nothing: {:?}", seen.borrow().grid);
|
||||
}
|
||||
|
||||
/// A click on the caption of the only selected tile opens its rename once the double-click interval passes; a double
|
||||
/// click there activates the tile and opens no rename.
|
||||
#[trial]
|
||||
fn a_slow_click_on_the_caption_renames_and_a_double_click_activates() {
|
||||
let (mut fixture, seen) = rig(|| TileGrid::new("Library").rename(true));
|
||||
let (mut fixture, seen) = rig(|_| TileGrid::new("Library").rename(true));
|
||||
let tile = fixture.by_label("Tile 2").expect("the tile has a node");
|
||||
// The caption band runs under the picture, inside the card's bottom inset.
|
||||
let caption = tile.rect.center_bottom() - Vec2::new(0.0, 10.0);
|
||||
@@ -82,7 +100,7 @@ fn a_slow_click_on_the_caption_renames_and_a_double_click_activates() {
|
||||
fixture.advance(1.0).idle(2);
|
||||
assert_eq!(renames(&seen), 1, "a slow second click on the caption renames the tile");
|
||||
|
||||
let (mut fixture, seen) = rig(|| TileGrid::new("Library").rename(true));
|
||||
let (mut fixture, seen) = rig(|_| TileGrid::new("Library").rename(true));
|
||||
fixture.click_at(caption);
|
||||
fixture.advance(1.0).idle(1);
|
||||
fixture.click_at(caption).click_at(caption);
|
||||
@@ -94,7 +112,7 @@ fn a_slow_click_on_the_caption_renames_and_a_double_click_activates() {
|
||||
/// A double click on the grid's background reports `EmptyActivated`; a double click on a tile activates it instead.
|
||||
#[trial]
|
||||
fn a_double_click_on_the_background_activates_the_empty_space() {
|
||||
let (mut fixture, seen) = rig(|| TileGrid::new("Library"));
|
||||
let (mut fixture, seen) = rig(|_| TileGrid::new("Library"));
|
||||
let tile = fixture.by_label("Tile 2").expect("the tile has a node").rect;
|
||||
let empty_space = egui::pos2(tile.center().x, tile.max.y + 80.0);
|
||||
let count = |seen: &Rc<RefCell<Seen>>, of: fn(&CollectionEvent<usize, craft_ui::tile_grid::TilePartEvent>) -> bool| {
|
||||
|
||||
@@ -177,7 +177,7 @@ name = "TileLayout"
|
||||
old = "craft_ui::list::tiles::TileLayout"
|
||||
new = ""
|
||||
status = "replaced"
|
||||
note = "`TileGrid::justified()` for `Justified`; cards are the default with `.aspect(w / h)`. The size is `.zoom(factor)`, a multiple of the medium thumbnail side that the app's `ThumbnailSlider` binds; `Cards { caption }` is `.caption(CaptionPlace::Below)`, or `.captionless()`. `Tiling` holds the sizes in points for `arrange`."
|
||||
note = "`TileGrid::justified()` for `Justified`; cards are the default with `.aspect(w / h)`. The size is `.zoom(GridZoom::Fixed(factor))`, an f64 multiple of the medium thumbnail side the app holds, or `.zoom(GridZoom::Bound(bind, TileZoom))`, the value the app's `ThumbnailSlider` binds, which the grid steps itself with Cmd/Ctrl + / - / 0 and the zoom wheel; `Cards { caption }` is `.caption(CaptionPlace::Below)`, or `.captionless()`. `Tiling` holds the sizes in points for `arrange`."
|
||||
|
||||
[[type]]
|
||||
name = "TileArrangement"
|
||||
@@ -290,7 +290,7 @@ note = "The source goes to `show_items`; the id salt is the label's id."
|
||||
[[setter]]
|
||||
type = "TileGrid"
|
||||
old = "layout(TileLayout)"
|
||||
new = "justified() / aspect(f32) / zoom(f32) / caption(CaptionPlace) / captionless()"
|
||||
new = "justified() / aspect(f32) / zoom(GridZoom::Fixed(f64) | GridZoom::Bound(Bind<f64>, TileZoom)) / caption(CaptionPlace) / captionless()"
|
||||
note = "See `TileLayout`."
|
||||
|
||||
[[setter]]
|
||||
|
||||
Reference in New Issue
Block a user