canvas-w8: net change of 1 commits

- canvas-w8: written from its sheet
This commit is contained in:
bflatastic
2026-11-21 21:26:28 +07:00
parent 6de10ac297
commit 5fecd6dbd6
10 changed files with 516 additions and 111 deletions
+26 -3
View File
@@ -220,7 +220,8 @@ fn room(anchor: Rect, bounds: Rect, side: Side, rtl: bool, gap: f32) -> f32 {
/// Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to
/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Beside the anchor, a request that
/// flips across lines up with the anchor's other end when it runs past the bounds from the aligned end and fits from the
/// other. The rect is always finite and inside the bounds.
/// other. The rect is then shifted by the request's `offset` and clamped again, unless the shifted rect would cover
/// `clear`, in which case the unshifted one stays. The rect is always finite and inside the bounds.
pub fn place(request: &PlaceRequest) -> Placement {
let anchor = clean(request.anchor);
let bounds = clean(request.bounds);
@@ -265,7 +266,11 @@ pub fn place(request: &PlaceRequest) -> Placement {
(Side::Start, true) | (Side::End, false) => Pos2::new(anchor.right() + gap, across_y),
};
let max_min = Pos2::new((bounds.right() - size.x).max(bounds.left()), (bounds.bottom() - size.y).max(bounds.top()));
let min = Pos2::new(min.x.clamp(bounds.left(), max_min.x), min.y.clamp(bounds.top(), max_min.y));
let keep = |min: Pos2| Pos2::new(min.x.clamp(bounds.left(), max_min.x), min.y.clamp(bounds.top(), max_min.y));
let min = keep(min);
let shifted = keep(min + Vec2::new(finite(request.offset.x), finite(request.offset.y)));
let covers = request.clear.map(clean).is_some_and(|clear| clear.intersects(Rect::from_min_size(shifted, size)));
let min = if covers { min } else { shifted };
Placement { rect: Rect::from_min_size(min, size), side }
}
@@ -301,6 +306,22 @@ mod tests {
assert_eq!(place(&request.side(Side::End)).rect.width(), 120.0, "beside it: its own width");
}
#[test]
fn an_offset_overlay_moves_unless_it_would_cover_its_clear_rect() {
let request = PlaceRequest::new(rect(100.0, 100.0, 200.0, 24.0), Vec2::new(100.0, 40.0), BOUNDS);
let home = place(&request).rect;
assert_eq!(home.min, Pos2::new(100.0, 124.0), "below the anchor, aligned to its start");
let by = Vec2::new(50.0, 30.0);
let moved = request.offset(by);
assert_eq!(place(&moved).rect.min, home.min + by, "shifted by the offset");
let point = Rect::from_min_max(Pos2::new(160.0, 170.0), Pos2::new(160.0, 170.0));
assert_eq!(place(&moved.clear(Some(point))).rect, home, "the shifted rect would cover the point: the unshifted one stays");
let aside = rect(600.0, 500.0, 10.0, 10.0);
assert_eq!(place(&moved.clear(Some(aside))).rect.min, home.min + by, "a clear rect off to the side changes nothing");
let far = place(&request.offset(Vec2::new(10_000.0, 0.0))).rect;
assert_eq!(far.right(), BOUNDS.right(), "the shifted rect is clamped inside the bounds");
}
#[test]
fn rect_is_finite_and_inside_the_bounds_for_any_request() {
let sides = [Side::Below, Side::Above, Side::Start, Side::End];
@@ -316,7 +337,9 @@ mod tests {
.side(side)
.align(align)
.rtl(i % 2 == 0)
.gap(if i == 1 { 4.0 } else { 0.0 });
.gap(if i == 1 { 4.0 } else { 0.0 })
.offset(Vec2::new(w, y))
.clear(Some(rect(h, x, w.abs(), y.abs())));
let placed = place(&request).rect;
assert!(placed.min.is_finite() && placed.max.is_finite(), "{request:?}");
assert!(BOUNDS.contains_rect(placed), "{request:?} gave {placed:?}");
+150 -67
View File
@@ -1,4 +1,4 @@
//! `TaskBar`: the contextual task bar over a canvas, hung below its anchor until the user moves it.
//! `TaskBar`: the contextual task bar over a canvas, hung beside its anchor until the user moves it.
#[cfg(feature = "testing")]
mod stories;
@@ -12,26 +12,28 @@ use crate::contract::{
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Inner, Mount, NoValue, Outcome, Overlay, Pad, PopupKind,
Props as _, Role, Show as _, ShowContainer as _, Sizing, Trigger,
};
use crate::display::Icon;
use crate::menu::{Menu, MenuItem, PanelRow};
use crate::display::{Divider, Icon};
use crate::menu::{Menu, MenuItem, PanelMenu, PanelRow};
use crate::primitives::IconSpec;
use crate::runtime::env::{Env, Label};
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::kurbo::Point;
use craft_behavior::overlay::{Align, Side};
use craft_behavior::overlay::{Align, PlaceRequest, Side};
use craft_behavior::{EditEvent, IconId, Metrics, Mixed, Sense};
use egui::{Pos2, Rect, Response, Ui};
use egui::{Pos2, Rect, Response, Ui, Vec2};
use std::sync::Arc;
/// Where the task bar sits: pinned or following its anchor, and where the user moved it. The one owner of the bar's
/// place; the serde shape is PhotoCraft's, so saved preferences load unchanged, and a non-finite `at` counts as unset.
/// place; the serde shape is PhotoCraft's, so saved preferences load unchanged, and a non-finite `at` or `offset`
/// counts as unset.
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct TaskBarPlace {
/// The bar keeps its place instead of following the anchor.
#[serde(default)]
pub pinned: bool,
/// The bar's top left corner relative to the area's, once moved; `None` while it follows the anchor.
/// The bar's top left corner relative to the area's while it is pinned; an unpinned place that holds it turns it
/// into `offset` at once.
#[serde(default)]
pub at: Option<[f32; 2]>,
/// Where an unpinned bar sits relative to its anchor, once moved; the bar follows the anchor with this offset.
@@ -51,19 +53,28 @@ impl TaskBarPlace {
let [x, y] = self.at.filter(|at| at.iter().all(|v| v.is_finite()))?;
Some(Pos2::new(area.min.x + x, area.min.y + y))
}
/// How far the bar sits from its unmoved place; `None` while it sits there. A non-finite `offset` counts as unset.
fn offset_in(&self) -> Option<Vec2> {
let [x, y] = self.offset.filter(|offset| offset.iter().all(|v| v.is_finite()))?;
Some(Vec2::new(x, y))
}
}
/// The contextual task bar: a movable modeless layer hung below the screen bounds of `anchor` while its place is
/// unset, with a body of members and a More menu (Hide, Reset, Pin). One place, pin and Hide setting for Crop and
/// The contextual task bar: a movable modeless layer hung on a side of the screen bounds of `anchor`, with a body of
/// members and a More menu (Hide, Pin, Reset, then the host's rows). One place, pin and Hide setting for Crop and
/// Frame.
///
/// - Place: centred under the anchor's bounds on screen, a section gap below them, following the anchor each pass.
/// Dragged by its grip (any free point of the bar), it stays where it is dropped and keeps its left edge while the
/// anchor moves or the bar grows; a press with no drag changes nothing. Pinned, it stays where it shows.
/// - Place: on `side` of the anchor's bounds on screen (below, centred, by default), a section gap away, following the
/// anchor each pass; it flips to the other side when there is no room. Dragged by its grip (any free point of the
/// bar), it keeps its offset from that place while the anchor moves or the bar grows; a press with no drag changes
/// nothing. A moved bar whose offset place would cover the `keep_clear` point shows at its unmoved place and keeps
/// its offset. Pinned, it stays where it shows.
/// - Area: the bar shows inside `area` (the canvas rect): a move stays inside it, and a stored place outside it comes
/// back inside, its left and top edges winning where the bar does not fit.
/// back inside, its left and top edges winning where the bar does not fit. Its members continue on a new line when
/// the area is too narrow for them.
/// - Menu: Hide bar reports `hide`; Reset bar position clears the place, so the bar follows its anchor again; Pin bar
/// position keeps it where it shows.
/// position keeps it where it shows and, picked again, lets it follow its anchor from where it shows.
/// - Nothing shows outside a canvas, or while the anchor's bounds or `area` is not finite or `area` has no size.
/// - `place` is the caller's value (`Bind::bound`): the bar reads it before it shows and writes the pass's change
/// after.
@@ -73,6 +84,10 @@ pub struct TaskBar<'a> {
label: Label,
anchor: &'a [Point],
place: Bind<'a, TaskBarPlace>,
rows: Vec<PanelRow>,
side: Side,
align: Align,
keep_clear: Option<Point>,
}
/// What the task bar reports.
@@ -119,6 +134,10 @@ enum MenuPick {
/// The More button and its menu, placed once per run of the bar's body.
struct MoreMenu {
words: Arc<CanvasControlWords>,
/// Whether the bar is pinned: the Pin row shows a check mark.
pinned: bool,
/// The host's rows, after the bar's own.
rows: Vec<PanelRow>,
placed: bool,
pick: Option<MenuPick>,
}
@@ -133,74 +152,97 @@ impl MoreMenu {
let more = IconButton::new(IconId::new("more")).popup(PopupKind::Menu).label(words.task_bar_more.clone()).show(ui);
let mut pick = None;
let rows = [
(MenuPick::Hide, "eye_off", &words.task_bar_hide),
(MenuPick::Reset, "reset", &words.task_bar_reset),
(MenuPick::Pin, "pin", &words.task_bar_pin),
(MenuPick::Hide, "eye_off", &words.task_bar_hide, false),
(MenuPick::Pin, "pin", &words.task_bar_pin, self.pinned),
(MenuPick::Reset, "reset", &words.task_bar_reset, false),
];
let host = &self.rows;
let _ = Menu::new(words.task_bar_more.clone()).opened_by(&more, Trigger::Click).show(ui, |ui, _| {
for (row, icon, name) in rows {
if MenuItem::new(name.clone()).icon(IconSpec::svg(IconId::new(icon))).show(ui).ran {
for (row, icon, name, checked) in rows {
if MenuItem::new(name.clone()).icon(IconSpec::svg(IconId::new(icon))).check(checked).show(ui).ran {
pick = Some(row);
}
}
if !host.is_empty() {
Divider::horizontal().show(ui);
let _ = PanelMenu::new(host.clone(), Vec::new()).show(ui);
}
});
self.pick = pick.or(self.pick);
}
}
/// Whether the More menu offers `row`: a dock row (`PanelRow::Item`), which only a dock reads, does not belong in it.
fn offered(row: &PanelRow) -> bool {
match row {
PanelRow::Item(_) => false,
PanelRow::Submenu(_, rows) => rows.iter().all(offered),
_ => true,
}
}
impl<'a> TaskBar<'a> {
/// A bar named `label` hung below the screen bounds of `anchor` (document points) until `place` moves it.
pub fn new(label: impl Into<Label>, anchor: &'a [Point], place: Bind<'a, TaskBarPlace>) -> Self {
TaskBar { label: label.into(), anchor, place }
TaskBar { label: label.into(), anchor, place, rows: Vec::new(), side: Side::Below, align: Align::Center, keep_clear: None }
}
/// Adds `rows` to the More menu after Hide, Pin and Reset and a divider: command rows take their label, chord, check
/// and enabled state from the command, and submenus show as in panel menus.
/// and enabled state from the command, and submenus show as in panel menus. A dock row (`PanelRow::Item`) is not
/// offered.
#[must_use]
pub fn more_rows(self, rows: Vec<PanelRow>) -> Self {
let _ = rows;
todo!("cv.F34")
pub fn more_rows(mut self, rows: Vec<PanelRow>) -> Self {
debug_assert!(rows.iter().all(offered), "the task bar's More menu offers no dock rows");
self.rows = rows;
self
}
/// Hangs the bar on `side` of the anchor's screen bounds, aligned by `align`, in place of below and centred.
#[must_use]
pub fn side(self, side: Side, align: Align) -> Self {
let _ = (side, align);
todo!("cv.F36")
pub fn side(mut self, side: Side, align: Align) -> Self {
self.side = side;
self.align = align;
self
}
/// A moved bar whose offset place would cover `point` (a document point, like the anchor) shows at its unmoved
/// place and keeps its offset.
#[must_use]
pub fn keep_clear(self, point: Point) -> Self {
let _ = point;
todo!("cv.F36")
pub fn keep_clear(mut self, point: Point) -> Self {
self.keep_clear = Some(point);
self
}
/// Shows the bar inside `area`; `body` fills its members.
pub fn show<R>(self, ui: &mut Ui, area: Rect, mut body: impl FnMut(&mut Ui, &mut TaskBarCx<'_>) -> R) -> Inner<TaskBarOutput, R> {
let TaskBar { label, anchor, mut place } = self;
let TaskBar { label, anchor, mut place, rows, side, align, keep_clear } = self;
let env = Env::of(ui);
let words = env.words::<CanvasControlWords>();
// The anchor maps through this pass's view, so the bar follows a scroll or zoom in the same pass.
let bounds = canvas_space(&env.view()).map_or(Rect::NOTHING, |space| {
anchor.iter().fold(Rect::NOTHING, |mut bounds, point| {
bounds.extend_with(space.view.to_screen(*point));
bounds
})
let space = canvas_space(&env.view());
let to_screen = |point: Point| space.as_ref().map(|space| space.view.to_screen(point));
let bounds = anchor.iter().filter_map(|point| to_screen(*point)).fold(Rect::NOTHING, |mut bounds, at| {
bounds.extend_with(at);
bounds
});
let shows = bounds.is_finite() && area.is_finite() && area.is_positive();
let held = match place.reborrow().get() {
Some(Mixed::Same(held)) => held,
_ => TaskBarPlace::default(),
};
let hang = shows.then(|| hang_rect(bounds, env.tokens.space.gap.section));
let layer = TaskBarLayer::new(label, layer_overlay(&held, hang, area), shows);
let mut menu = MoreMenu { words: Arc::clone(&words), placed: false, pick: None };
let rtl = env.direction.is_rtl();
let hang = shows.then(|| Hang {
rect: hang_for(bounds, side, rtl, env.tokens.space.gap.section),
side,
align,
clear: keep_clear.and_then(to_screen).map(|at| Rect::from_min_max(at, at)),
});
let layer = TaskBarLayer::new(label, layer_overlay(&held, hang.as_ref(), area), shows);
let mut menu = MoreMenu { words: Arc::clone(&words), pinned: held.pinned, rows, placed: false, pick: None };
let grip = words.task_bar_move.clone();
let mut shown = layer.show(ui, |ui, _| {
// The bar is the one surface: the grip is its first member, on the members' line inside its padding.
Bar::new(Label::Empty, BarKind::Tool).surface(SurfaceKind::Floating).show(ui, |ui, _| {
Bar::new(Label::Empty, BarKind::Tool).surface(SurfaceKind::Floating).wrap().show(ui, |ui, _| {
let _ = Icon::new(IconSpec::svg(IconId::new("grip"))).label(grip.clone()).show(ui);
menu.placed = false;
let inner = body(ui, &mut TaskBarCx { menu: &mut menu });
@@ -210,9 +252,9 @@ impl<'a> TaskBar<'a> {
});
let rect = shown.output.response.rect;
let pick = menu.pick;
if shows {
if let Some(hang) = &hang {
let moved = shown.output.moved.filter(|moved| moved.min != rect.min);
let next = settled(held, rect, area, moved, pick);
let next = settled(held, rect, area, moved, pick, hang.unmoved(rect.size(), area, rtl));
if next != held {
let word = match pick {
Some(MenuPick::Reset) => &words.task_bar_reset,
@@ -231,42 +273,83 @@ impl<'a> TaskBar<'a> {
}
}
/// The rect the bar hangs below: the anchor's screen `bounds` grown by `gap` at the bottom. The overlay host keeps the
/// layer inside `Overlay::bounds`.
fn hang_rect(bounds: Rect, gap: f32) -> Rect {
Rect::from_min_max(bounds.min, Pos2::new(bounds.max.x, bounds.max.y + gap))
/// What the bar hangs from, in screen space.
struct Hang {
/// The anchor's bounds grown by the section gap on the hanging side. The overlay host keeps the layer inside
/// `Overlay::bounds`.
rect: Rect,
side: Side,
align: Align,
/// A rect the bar keeps clear of while it is offset.
clear: Option<Rect>,
}
/// The layer the bar shows in: hung below `hang` while `held` has no place, at its place once it has one. A move stays
/// inside `area`. A bar that does not show (`hang` is `None`) gets a closed layer with no place.
fn layer_overlay(held: &TaskBarPlace, hang: Option<Rect>, area: Rect) -> Overlay {
impl Hang {
/// Where a bar of `size` hangs inside `area` before any offset: the place the overlay host computes for the
/// anchored layer, taken from the one placement rule.
fn unmoved(&self, size: Vec2, area: Rect, rtl: bool) -> Rect {
let request = PlaceRequest::new(self.rect, size, area).side(self.side).align(self.align).rtl(rtl).flips_across(true);
craft_behavior::overlay::place(&request).rect
}
}
/// The rect the bar hangs from: the anchor's screen `bounds` grown by `gap` on `side`.
fn hang_for(bounds: Rect, side: Side, rtl: bool, gap: f32) -> Rect {
let mut rect = bounds;
match (side, rtl) {
(Side::Below, _) => rect.max.y += gap,
(Side::Above, _) => rect.min.y -= gap,
(Side::Start, false) | (Side::End, true) => rect.min.x -= gap,
_ => rect.max.x += gap,
}
rect
}
/// The layer the bar shows in: at its place while `held` has one, else hung from `hang` with its offset, keeping clear
/// of `hang.clear`. A move stays inside `area`. A bar that does not show (`hang` is `None`) gets a closed layer with no
/// place.
fn layer_overlay(held: &TaskBarPlace, hang: Option<&Hang>, area: Rect) -> Overlay {
let overlay = Overlay::floating().modeless().movable(true).body_scroll(false);
let Some(hang) = hang else { return overlay };
let overlay = overlay.bounds(area);
match held.placed_in(area) {
Some(at) => overlay.placed_at(at),
None => overlay.place(Place::anchored(Anchor::Rect(hang), Side::Below, Align::Center)),
if let Some(at) = held.placed_in(area) {
return overlay.placed_at(at);
}
let hung = Place::anchored(Anchor::Rect(hang.rect), hang.side, hang.align).flipping_across().offset(held.offset_in().unwrap_or(Vec2::ZERO));
overlay.place(match hang.clear {
Some(clear) => hung.clear_of(clear),
None => hung,
})
}
/// The place after a pass that showed the bar at `shown`. A move (`moved`, a rect other than `shown`) keeps the bar
/// where it was dropped; Reset clears the place; Pin, and a pinned bar with no place, keep the bar at `shown`. A
/// non-finite place is cleared. With no move and no pick, the place stays unchanged; the overlay host keeps the layer
/// inside the area.
fn settled(held: TaskBarPlace, shown: Rect, area: Rect, moved: Option<Rect>, pick: Option<MenuPick>) -> TaskBarPlace {
let offset = |rect: Rect| -> [f32; 2] { (rect.min - area.min).into() };
let placed = held.placed_in(area).is_some();
let mut next = TaskBarPlace { at: held.at.filter(|_| placed), ..held };
if let Some(moved) = moved {
next.at = Some(offset(moved));
/// The place after a pass that showed the bar at `shown`, whose unmoved place is `unmoved`. A move (`moved`, a rect
/// other than `shown`) of an unpinned bar adds its distance to the offset, of a pinned bar sets `at`; Reset gives the
/// default place; Pin pins the bar where it shows, and picked while pinned unpins it, the bar keeping where it shows.
/// An unpinned place that holds `at` turns it into the offset that keeps the bar where it shows. With no move and no
/// pick the place stays unchanged; the overlay host keeps the layer inside the area.
fn settled(held: TaskBarPlace, shown: Rect, area: Rect, moved: Option<Rect>, pick: Option<MenuPick>, unmoved: Rect) -> TaskBarPlace {
if pick == Some(MenuPick::Reset) {
return TaskBarPlace::default();
}
match pick {
Some(MenuPick::Reset) => next = TaskBarPlace::default(),
Some(MenuPick::Pin) => next = TaskBarPlace { pinned: true, at: Some(offset(shown)), offset: None },
Some(MenuPick::Hide) | None => {}
let at = |rect: Rect| -> [f32; 2] { (rect.min - area.min).into() };
let placed = held.placed_in(area).is_some();
let mut next = TaskBarPlace { pinned: held.pinned, at: held.at.filter(|_| placed), offset: held.offset_in().map(<[f32; 2]>::from) };
if pick == Some(MenuPick::Pin) {
next = TaskBarPlace { pinned: !held.pinned, at: Some(at(shown)), offset: None };
}
if next.pinned && next.at.is_none() {
next.at = Some(offset(shown));
next.at = Some(at(shown));
}
if !next.pinned && next.at.is_some() {
next.at = None;
next.offset = Some((shown.min - unmoved.min).into());
}
if let Some(moved) = moved {
if next.pinned {
next.at = Some(at(moved));
} else {
next.offset = Some((next.offset.map_or(Vec2::ZERO, Vec2::from) + (moved.min - shown.min)).into());
}
}
next
}
@@ -4,9 +4,12 @@ use super::{TaskBar, TaskBarPlace};
use crate::buttons::{Button, IconButton};
use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas};
use crate::contract::{Bind, Props as _, Show as _};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use crate::menu::PanelRow;
use crate::runtime::commands::{CommandRef, EditCommands};
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use craft_behavior::IconId;
use craft_behavior::kurbo::{Point, Vec2};
use craft_behavior::overlay::{Align, Side};
use egui::Ui;
/// The corners of a crop frame turned by a few degrees about the document's middle: the Crop tool hangs its bar from
@@ -36,12 +39,74 @@ fn crop_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
})
}
/// The Crop bar's frame `corners` with a Done button, the bar set up by `configure`, in a story area as wide as `width`
/// when it is given.
fn configured(
ui: &mut Ui,
data: &mut StoryData,
corners: &[Point],
width: Option<f32>,
configure: impl for<'a> Fn(TaskBar<'a>) -> TaskBar<'a>,
) -> StoryOutput {
on_canvas(ui, |ui, area, _| {
let place = data.value("place", TaskBarPlace::default());
let mut area = area;
if let Some(width) = width {
area.set_width(width);
}
configure(TaskBar::new("Crop", corners, Bind::bound(place)))
.show(ui, area, |ui, _| {
for name in ["Rotate", "Flip", "Overlay", "Done"] {
let _ = Button::new(name).show(ui);
}
})
.output
})
}
fn open_more(fixture: &mut Fixture) {
let more = fixture.by_label("More options").expect("the bar has its More button");
fixture.click(&more).settle();
}
/// The More menu open with the host's rows after its own: two command rows and a submenu.
#[story(TaskBar<'static>, covers = [], drive = Drive::Custom(open_more))]
fn host_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = vec![
PanelRow::Command(CommandRef::from(EditCommands::Undo)),
PanelRow::Command(CommandRef::from(EditCommands::Redo)),
PanelRow::Submenu("Arrange".into(), vec![PanelRow::Command(CommandRef::from(EditCommands::Cut))]),
];
configured(ui, data, &turned_frame(), None, |bar| bar.more_rows(rows.clone()))
}
/// A bar beside the frame's right end, near the canvas's right edge so it flips to the other side, keeping clear of a
/// point.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn beside_a_point(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let corners = turned_frame().map(|corner| corner + Vec2::new(300.0, 0.0));
let point = corners[0];
configured(ui, data, &corners, None, |bar| bar.side(Side::End, Align::Start).keep_clear(point))
}
/// A bar resting above the frame.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn resting_above(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
configured(ui, data, &turned_frame(), None, |bar| bar.side(Side::Above, Align::Center))
}
/// A bar in a narrow area: its members continue on a new line.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn wrapped(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
configured(ui, data, &turned_frame(), Some(200.0), |bar| bar)
}
/// A bar the user moved and pinned: it keeps its place near the canvas's top left while the frame stays where it is.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn placed_and_pinned(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let corners = turned_frame();
on_canvas(ui, |ui, area, _| {
let place = data.value("place", TaskBarPlace { pinned: true, at: Some([24.0, 24.0]), offset: None });
let place = data.value("place", TaskBarPlace::new(true, Some([24.0, 24.0])));
TaskBar::new("Crop", &corners, Bind::bound(place))
.show(ui, area, |ui, _| {
let _ = Button::new("Done").show(ui);
@@ -1,14 +1,17 @@
//! The contextual task bar (N6): hung centred under its anchor's screen bounds, following the anchor until the grip
//! moves it, reset and pinned from its More menu, and kept inside the canvas area whatever place it is given.
//! The contextual task bar (N6): hung centred under its anchor's screen bounds, following the anchor with the offset
//! the grip gave it, reset and pinned from its More menu, and kept inside the canvas area whatever place it is given.
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
use craft_behavior::overlay::{Align, Side};
use craft_ui::buttons::Button;
use craft_ui::canvas_controls::{TaskBar, TaskBarPlace};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::menu::PanelRow;
use craft_ui::runtime::commands::{CommandRef, EditCommands};
use craft_ui::testing::canvas_story::on_canvas;
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Vec2};
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const SLACK: f32 = 1.5;
@@ -27,14 +30,26 @@ struct Scene {
rect: Rect,
}
/// A scene with the frame at its start and no place.
fn scene() -> Rc<RefCell<Scene>> {
Rc::new(RefCell::new(Scene {
anchor: frame(DocVec::ZERO),
place: TaskBarPlace::default(),
bounds: Rect::NOTHING,
area: Rect::NOTHING,
rect: Rect::NOTHING,
}))
}
/// A frame of the story document, moved by `by` document points. It lies high on the story canvas (360 points tall),
/// so the bar hangs below it after every move and drop the trial makes.
fn frame(by: DocVec) -> Vec<Point> {
[(120.0, 40.0), (520.0, 40.0), (520.0, 200.0), (120.0, 200.0)].into_iter().map(|(x, y)| Point::new(x, y) + by).collect()
}
/// A canvas that shows the bar for the scene's anchor and place, with the More menu before a Done button.
fn fixture(scene: &Rc<RefCell<Scene>>) -> Fixture {
/// A canvas that shows the bar for the scene's anchor and place, set up by `configure`, with the More menu before a
/// Done button.
fn fixture_with(scene: &Rc<RefCell<Scene>>, configure: impl for<'a> Fn(TaskBar<'a>) -> TaskBar<'a> + 'static) -> Fixture {
let shared = Rc::clone(scene);
let mut fixture = Fixture::new(move |ui| {
let _ = on_canvas(ui, |ui, area, view| {
@@ -42,7 +57,7 @@ fn fixture(scene: &Rc<RefCell<Scene>>) -> Fixture {
let scene = &mut *held;
scene.bounds = Rect::from_points(&scene.anchor.iter().map(|point| view.to_screen(*point)).collect::<Vec<_>>());
scene.area = area;
let shown = TaskBar::new("Crop", &scene.anchor, Bind::bound(&mut scene.place)).show(ui, area, |ui, cx| {
let shown = configure(TaskBar::new("Crop", &scene.anchor, Bind::bound(&mut scene.place))).show(ui, area, |ui, cx| {
cx.more_menu(ui);
let _ = Button::new("Done").show(ui);
});
@@ -54,6 +69,10 @@ fn fixture(scene: &Rc<RefCell<Scene>>) -> Fixture {
fixture
}
fn fixture(scene: &Rc<RefCell<Scene>>) -> Fixture {
fixture_with(scene, |bar| bar)
}
fn seen(scene: &Rc<RefCell<Scene>>) -> Scene {
scene.borrow().clone()
}
@@ -76,13 +95,7 @@ fn pick(fixture: &mut Fixture, row: &str) {
#[trial]
fn the_task_bar_follows_its_anchor_until_moved_and_stays_inside_the_area() {
let scene = Rc::new(RefCell::new(Scene {
anchor: frame(DocVec::ZERO),
place: TaskBarPlace::default(),
bounds: Rect::NOTHING,
area: Rect::NOTHING,
rect: Rect::NOTHING,
}));
let scene = scene();
let mut fixture = fixture(&scene);
fixture.settle();
let first = seen(&scene);
@@ -104,13 +117,20 @@ fn the_task_bar_follows_its_anchor_until_moved_and_stays_inside_the_area() {
let by = Vec2::new(-120.0, 60.0);
fixture.drag(&grip, by).settle();
let dropped = seen(&scene);
assert!(dropped.place.at.is_some(), "the drag gave the bar a place");
assert!((dropped.rect.min - (followed.rect.min + by)).length() < 2.0 * SLACK, "the bar stays where it was dropped: {:?}", dropped.rect);
assert!(dropped.place.offset.is_some() && dropped.place.at.is_none(), "the drag gave the bar an offset: {:?}", dropped.place);
assert!((dropped.rect.min - (followed.rect.min + by)).length() < 2.0 * SLACK, "the bar sits where it was dropped: {:?}", dropped.rect);
scene.borrow_mut().anchor = frame(DocVec::new(90.0, 10.0));
fixture.settle();
let kept = seen(&scene);
assert!((kept.rect.min - dropped.rect.min).length() < SLACK, "a moved bar keeps its left edge while the anchor moves: {:?}", kept.rect);
let shift = kept.bounds.min - dropped.bounds.min;
assert!(shift.length() > SLACK, "the anchor moved on screen");
assert!(
(kept.rect.min - dropped.rect.min - shift).length() < SLACK,
"a moved bar follows its anchor with its offset: anchor shifted {shift:?}, bar {:?} to {:?}",
dropped.rect,
kept.rect
);
pick(&mut fixture, "Reset bar position");
let reset = seen(&scene);
@@ -119,10 +139,21 @@ fn the_task_bar_follows_its_anchor_until_moved_and_stays_inside_the_area() {
pick(&mut fixture, "Pin bar position");
let pinned = seen(&scene);
assert!(pinned.place.pinned && pinned.place.at.is_some(), "Pin keeps the place: {:?}", pinned.place);
assert!(pinned.place.pinned && pinned.place.at.is_some() && pinned.place.offset.is_none(), "Pin keeps the place: {:?}", pinned.place);
scene.borrow_mut().anchor = frame(DocVec::new(-60.0, -40.0));
fixture.settle();
assert!((seen(&scene).rect.min - pinned.rect.min).length() < SLACK, "a pinned bar stays while the anchor moves");
let held = seen(&scene);
assert!((held.rect.min - pinned.rect.min).length() < SLACK, "a pinned bar stays while the anchor moves");
pick(&mut fixture, "Pin bar position");
let unpinned = seen(&scene);
assert!(!unpinned.place.pinned && unpinned.place.at.is_none() && unpinned.place.offset.is_some(), "Pin again unpins: {:?}", unpinned.place);
assert!((unpinned.rect.min - held.rect.min).length() < SLACK, "the bar jumped when it was unpinned: {:?}", unpinned.rect);
scene.borrow_mut().anchor = frame(DocVec::new(-20.0, -40.0));
fixture.settle();
let after = seen(&scene);
let shift = after.bounds.min - unpinned.bounds.min;
assert!((after.rect.min - unpinned.rect.min - shift).length() < SLACK, "an unpinned bar follows its anchor again");
scene.borrow_mut().place = TaskBarPlace::new(false, Some([f32::NAN, 0.0]));
fixture.settle();
@@ -135,17 +166,79 @@ fn the_task_bar_follows_its_anchor_until_moved_and_stays_inside_the_area() {
assert!(inside_area(&far), "a place far outside comes back inside {:?}: {:?}", far.area, far.rect);
}
/// The More menu lists Hide, Pin and Reset, then the host's rows in the order given; a submenu opens.
#[trial]
fn the_more_menu_lists_the_hosts_rows_after_its_own_and_runs_them() {
let scene = scene();
let mut fixture = fixture_with(&scene, |bar| {
bar.more_rows(vec![
PanelRow::Command(CommandRef::from(EditCommands::Undo)),
PanelRow::Submenu("Arrange".into(), vec![PanelRow::Command(CommandRef::from(EditCommands::Cut))]),
])
});
fixture.settle();
let more = fixture.by_label("More options").expect("the bar has its More button");
fixture.click(&more).settle();
let tops: Vec<f32> = ["Hide bar", "Pin bar position", "Reset bar position", "Undo", "Arrange"]
.into_iter()
.map(|label| fixture.by_label(label).unwrap_or_else(|| panic!("the More menu lists {label}")).rect.top())
.collect();
assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "the rows are not in order, the bar's own first: {tops:?}");
assert!(fixture.by_label("Cut").is_none(), "the submenu is closed");
let arrange = fixture.by_label("Arrange").expect("the submenu row");
fixture.click(&arrange).settle();
assert!(fixture.by_label("Cut").is_some(), "the submenu opens");
}
/// Beside the anchor near the canvas's right edge the bar flips to the anchor's other side, and a moved bar whose
/// offset place would cover the kept-clear point shows at its unmoved place with its offset kept.
#[trial]
fn a_bar_beside_a_point_flips_and_keeps_clear_of_it() {
let scene = scene();
let clear = Rc::new(Cell::new(None));
let kept = Rc::clone(&clear);
let mut fixture = fixture_with(&scene, move |bar| {
let bar = bar.side(Side::End, Align::Start);
match kept.get() {
Some(point) => bar.keep_clear(point),
None => bar,
}
});
fixture.settle();
let origin = seen(&scene);
// How far a document point moves on screen, to put the anchor at the canvas's right edge.
scene.borrow_mut().anchor = frame(DocVec::new(100.0, 0.0));
fixture.settle();
let probed = seen(&scene);
let scale = f64::from(probed.bounds.min.x - origin.bounds.min.x) / 100.0;
let far = 100.0 + f64::from(probed.area.max.x - probed.bounds.max.x - 8.0) / scale;
scene.borrow_mut().anchor = frame(DocVec::new(far, 0.0));
fixture.settle();
let flipped = seen(&scene);
assert!(flipped.rect.right() <= flipped.bounds.left() + SLACK, "the bar flipped to the left of the anchor {:?}: {:?}", flipped.bounds, flipped.rect);
// A point a little to the bar's right: a bar moved by 60 points would cover it.
let at = egui::pos2(flipped.rect.max.x + 20.0, flipped.rect.center().y);
let corner = frame(DocVec::new(far, 0.0))[0];
clear.set(Some(corner + DocVec::new(f64::from(at.x - flipped.bounds.min.x) / scale, f64::from(at.y - flipped.bounds.min.y) / scale)));
fixture.settle();
assert!((seen(&scene).rect.min - flipped.rect.min).length() < SLACK, "the bar stays at its unmoved place until moved");
let grip = fixture.by_label("Move bar").expect("the grip is named");
fixture.drag(&grip, Vec2::new(60.0, 0.0)).settle();
let dropped = seen(&scene);
let offset = dropped.place.offset.expect("the drag gave the bar an offset");
assert!((offset[0] - 60.0).abs() < 2.0 * SLACK && offset[1].abs() < 2.0 * SLACK, "the offset is the drag: {offset:?}");
assert!((dropped.rect.min - flipped.rect.min).length() < SLACK, "the bar covers the point at its offset place: {:?}", dropped.rect);
fixture.settle();
assert_eq!(seen(&scene).place.offset, dropped.place.offset, "the offset is kept on the next pass");
}
/// The grip is one of the bar's members: it sits on the members' line, centred with them, inside the bar's padding,
/// and a drag on it still moves the bar.
#[trial]
fn the_grip_sits_on_the_members_line() {
let scene = Rc::new(RefCell::new(Scene {
anchor: frame(DocVec::ZERO),
place: TaskBarPlace::default(),
bounds: Rect::NOTHING,
area: Rect::NOTHING,
rect: Rect::NOTHING,
}));
let scene = scene();
let mut fixture = fixture(&scene);
fixture.settle();
let bar = seen(&scene).rect;
@@ -80,15 +80,19 @@ impl Place {
}
/// The place shifted by `by` from where it would sit; no change off `Anchored`.
pub fn offset(self, by: egui::Vec2) -> Self {
let _ = by;
todo!("cv.F38")
pub fn offset(mut self, by: egui::Vec2) -> Self {
if let Place::Anchored { offset, .. } = &mut self {
*offset = by;
}
self
}
/// The place keeping clear of `rect`; no change off `Anchored`.
pub fn clear_of(self, rect: egui::Rect) -> Self {
let _ = rect;
todo!("cv.F38")
pub fn clear_of(mut self, rect: egui::Rect) -> Self {
if let Place::Anchored { clear, .. } = &mut self {
*clear = Some(rect);
}
self
}
}
@@ -220,7 +220,7 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option<egui::Vec
let rtl = layer.env.direction.is_rtl();
let cap = cap(layer.overlay, bounds, anchor);
match &layer.overlay.place {
Place::Anchored { side, align, flips_across, .. } => {
Place::Anchored { side, align, flips_across, offset, clear, .. } => {
let kept = layer_bounds(layer, bounds);
let Some(size) = size else {
let room = content_room(layer.overlay, bounds, kept, anchor, rtl);
@@ -234,7 +234,9 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option<egui::Vec
.align(*align)
.rtl(rtl)
.min_width(layer.overlay.min_width)
.flips_across(*flips_across);
.flips_across(*flips_across)
.offset(*offset)
.clear(*clear);
let placed = craft_behavior::overlay::place(&request);
// The room is what the side the layer took leaves for a body as large as the cap.
let room = craft_behavior::overlay::place(&request.kept(Some(placed.side)).size(cap)).rect.size();
@@ -198,8 +198,14 @@ impl Overlay {
mapped.placed = mapped.placed.map(|rect| to_screen * rect);
mapped.placed_at = mapped.placed_at.map(|pos| to_screen * pos);
mapped.bounds = mapped.bounds.map(|rect| to_screen * rect);
if let Place::Float(FloatPlace { pos: Some(pos) }) = &mut mapped.place {
*pos = to_screen * *pos;
match &mut mapped.place {
Place::Float(FloatPlace { pos: Some(pos) }) => *pos = to_screen * *pos,
// An offset is a vector: it scales with the layer's space and does not translate.
Place::Anchored { offset, clear, .. } => {
*offset = to_screen.scaling * *offset;
*clear = clear.map(|rect| to_screen * rect);
}
_ => {}
}
Cow::Owned(mapped)
}
+5 -3
View File
@@ -88,7 +88,7 @@ impl Outcome for BarOutput {
/// left-to-right. A select in a bar fits its widest entry, up to a field length. A rule between groups of members is a
/// `Divider::vertical()`; it shows only with the member after it. A bar with `commit_cancel` ends with a
/// cancel and a commit button in its end region, outside the scroll, `space.gap.stack` from the body and on the
/// members' line; they run `BarCommands`.
/// members' line; they run `BarCommands`. A bar made [`wrap`](Bar::wrap) continues on a new line instead of scrolling.
#[derive(crate::contract::Component)]
#[component(container)]
pub struct Bar<'a> {
@@ -148,8 +148,10 @@ impl<'a> Bar<'a> {
/// Lays out the members as a row that wraps instead of scrolling under an overlay bar: no horizontal scroll, no row
/// cap; a member wider than the bar narrows and elides by the shared rules.
#[must_use]
pub fn wrap(self) -> Self {
todo!("cv.F37")
pub fn wrap(mut self) -> Self {
self.props.layout = self.props.layout.clone().wrap(true);
self.props.scroll = None;
self
}
/// Makes each member its own Tab stop, in reading order, as media controls are; the arrows no longer move between
+44 -1
View File
@@ -1,12 +1,13 @@
//! Stories of the bars.
use super::{Bar, BarHome, BarItem, BarItems, BarKind, BarTool, ItemDisplay, StatusItem, StatusMessage, StatusProgress, StatusReadout, StatusValues};
use crate::buttons::Link;
use crate::buttons::{Button, Link};
use crate::choice::{Checkbox, Segmented};
use crate::contract::{Bind, Entry, Props as _};
use crate::contract::{Show as _, ShowContainer as _};
use crate::display::{Divider, Shade, Text};
use crate::form::Field;
use crate::layout_components::Row;
use crate::menu::{Menu, MenuItem};
use crate::pickers::Select;
use crate::runtime::commands::EditCommands;
@@ -22,6 +23,8 @@ const NARROW: f32 = 80.0;
/// The widths of the old status bar stories.
const STATUS_WIDTH: f32 = 640.0;
const STATUS_NARROW: f32 = 480.0;
/// A width that holds two or three of the tool buttons of a row and not all of them.
const TOOLS_NARROW: f32 = 220.0;
/// The document the status readout zooms, in document units.
const DOCUMENT: Size = Size::new(2000.0, 1500.0);
@@ -44,6 +47,46 @@ fn bar(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
.into()
}
/// A bar made to wrap: its members continue on a new line in a narrow stage instead of scrolling.
#[story(Bar<'static>, covers = [], drive = Drive::Never)]
fn bar_wrapping(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
crate::testing::memory::scoped(ui, |ui| {
ui.set_max_width(TOOLS_NARROW);
Bar::new("Tools", BarKind::Tool)
.wrap()
.show(ui, |ui, _| {
for name in ["Undo", "Redo", "Cut", "Copy", "Paste", "Delete"] {
Button::new(name).show(ui);
}
})
.output
})
.into()
}
/// A bar whose members sit in ranked rows in a narrow stage: the row of the lowest rank leaves first, the unranked row
/// stays.
#[story(Bar<'static>, covers = [], drive = Drive::Never)]
fn ranked_row_in_a_narrow_bar(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
crate::testing::memory::scoped(ui, |ui| {
ui.set_max_width(TOOLS_NARROW);
Bar::new("Tools", BarKind::Tool)
.show(ui, |ui, _| {
Row::new().fit_rank(1).show(ui, |ui, _| {
Button::new("Low").show(ui);
});
Row::new().fit_rank(2).show(ui, |ui, _| {
Button::new("Mid").show(ui);
});
Row::new().show(ui, |ui, _| {
Button::new("Keep").show(ui);
});
})
.output
})
.into()
}
/// The brush tool's bar: Home and the tool, the brush cells, a rule, the sampling group and its hint, then commit
/// and cancel.
#[story(Bar<'static>, covers = [], drive = Drive::Never)]
+84
View File
@@ -291,6 +291,90 @@ fn filling_bar_members_keep_their_natural_width_and_the_bar_scrolls() {
assert!(button_whole.contains(&true), "the bar does not scroll to show its last member whole: {button_whole:?}");
}
/// The rects of `count` buttons in a tool bar `width` wide that wraps or scrolls.
fn tools(width: f32, wrap: bool, count: usize) -> Vec<Rect> {
let seen = Rc::new(std::cell::RefCell::new(Vec::new()));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let bar = Bar::new("Tools", BarKind::Tool);
let bar = if wrap { bar.wrap() } else { bar };
bar.show(ui, |ui, _| {
*out.borrow_mut() = (0..count).map(|at| Button::new(format!("Tool {at}")).show(ui).rect).collect();
});
});
fixture.room(Vec2::new(width, 300.0)).settle();
seen.borrow().clone()
}
/// The rect of a select with a long entry in a tool bar `width` wide that wraps.
fn wide_member(width: f32) -> Rect {
let seen = Rc::new(Cell::new(Rect::NOTHING));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let entries = [Entry::new(0u8, "Current and Below, No Adjustments"), Entry::new(1, "All Layers")];
Bar::new("Tools", BarKind::Tool).wrap().show(ui, |ui, _| {
out.set(Select::new("Sample", Bind::given(0u8), &entries).sizing(Sizing::Content).show(ui).response.rect);
});
});
fixture.room(Vec2::new(width, 300.0)).settle();
seen.get()
}
#[trial]
fn a_wrapping_bar_continues_on_a_new_line() {
let plain = tools(200.0, false, 6);
assert!(plain.last().is_some_and(|last| last.max.x > 200.0), "six tools fit a 200-point bar that scrolls: {plain:?}");
let wrapped = tools(200.0, true, 6);
assert_eq!(wrapped.len(), 6, "every member shows");
for rect in &wrapped {
assert!(rect.min.x >= -SLACK && rect.max.x <= 200.0 + SLACK, "{rect:?} lies past the bar's edge");
}
let first_line = wrapped[0].center().y;
assert!(wrapped.iter().any(|rect| rect.center().y > first_line + SLACK), "no member continued on a new line: {wrapped:?}");
for pair in wrapped.windows(2) {
let (before, after) = (pair[0], pair[1]);
let same_line = (before.center().y - after.center().y).abs() < SLACK;
assert!(
(same_line && before.max.x <= after.min.x + SLACK) || after.center().y > before.center().y + SLACK,
"{after:?} is out of reading order after {before:?}"
);
}
let select = wide_member(120.0);
assert!(select.max.x <= 120.0 + SLACK, "a member wider than the bar kept its width: {select:?}");
}
/// What a bar of three rows, ranked 1 and 2 and unranked, `width` wide shows: whether each of their buttons is there.
fn ranked(width: f32) -> [bool; 3] {
let mut fixture = Fixture::new(|ui| {
Bar::new("Tools", BarKind::Tool).show(ui, |ui, _| {
Row::new().fit_rank(1).show(ui, |ui, _| {
Button::new("Low").show(ui);
});
Row::new().fit_rank(2).show(ui, |ui, _| {
Button::new("Mid").show(ui);
});
Row::new().show(ui, |ui, _| {
Button::new("Keep").show(ui);
});
});
});
fixture.room(Vec2::new(width, 80.0)).settle();
["Low", "Mid", "Keep"].map(|label| fixture.by_label(label).is_some())
}
#[trial]
fn ranked_rows_leave_a_narrow_bar_by_rank_and_take_their_rule() {
let widths: Vec<f32> = (60..=600).step_by(20).map(|width| width as f32).collect();
let shown: Vec<[bool; 3]> = widths.iter().map(|width| ranked(*width)).collect();
assert_eq!(shown[shown.len() - 1], [true; 3], "a wide bar shows every row");
assert!(!shown[0][0], "the lowest rank is still there in the narrowest bar");
for (width, [low, mid, keep]) in widths.iter().zip(&shown) {
assert!(*keep, "the unranked row left a bar {width} wide");
assert!(!(*low && !*mid), "the higher rank left before the lower at {width}");
}
assert!(shown.iter().any(|[low, mid, _]| !low && *mid), "the lowest rank never left alone: {shown:?}");
}
/// The texts a status bar `width` wide paints, each with whether it was cut: the readout of the document sizes, a long
/// message and the render-path link in its trailing group.
fn readout_texts(width: f32) -> Vec<(String, bool)> {