canvas-w8: net change of 5 commits

- canvas-w8: written from its sheet
- canvas-w8: repair 1
- canvas-w8: finished by an agent
- canvas-w8: review fixes (review-1)
- canvas-w8: review fixes (review-1b)
This commit is contained in:
Martin Ball
2026-11-18 14:03:47 +00:00
parent 80d3e4d440
commit ad6575845d
7 changed files with 417 additions and 37 deletions
@@ -7,7 +7,7 @@ use super::CanvasControlWords;
use crate::bars::{Bar, BarKind};
use crate::buttons::IconButton;
use crate::canvas::canvas_space;
use crate::contract::overlay::{Anchor, Place, PlacementChange, PlacementKind};
use crate::contract::overlay::{Anchor, Dismiss, Outside, Place, PlacementChange, PlacementKind};
use crate::contract::{
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Inner, Mount, NoValue, Outcome, Overlay, Pad,
PopupKind, Props as _, Role, Show as _, ShowContainer as _, Sizing, Trigger,
@@ -16,6 +16,7 @@ use crate::display::Icon;
use crate::menu::{Menu, MenuItem};
use crate::primitives::IconSpec;
use crate::runtime::env::{Env, Label};
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::kurbo::Point;
use craft_behavior::overlay::{Align, Side};
@@ -113,7 +114,7 @@ pub struct TaskBarOutput {
pub hide: bool,
/// The bar's rect on screen.
pub rect: Rect,
/// The bar was closed by an outside press.
/// The bar closed: an outside press, Escape or its anchor going. The caller stops showing it.
pub closed: bool,
}
@@ -149,6 +150,8 @@ 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 has a More menu: a selection bar has none.
offered: bool,
placed: bool,
pick: Option<MenuPick>,
}
@@ -156,7 +159,7 @@ struct MoreMenu {
impl MoreMenu {
/// Shows the button and its menu here unless this run of the body showed them already.
fn place(&mut self, ui: &mut Ui) {
if std::mem::replace(&mut self.placed, true) {
if !self.offered || std::mem::replace(&mut self.placed, true) {
return;
}
let words = Arc::clone(&self.words);
@@ -187,14 +190,23 @@ impl<'a> TaskBar<'a> {
/// A bar named `label` anchored above or at `side` of a selection whose bounds are `anchor` (document points),
/// flipped and clamped to fit.
pub fn selection(label: impl Into<Label>, anchor: &'a [Point]) -> Self {
let _ = (label.into(), anchor);
todo!("cv.K13")
TaskBar {
label: label.into(),
anchor,
place: Bind::given(Mixed::Same(TaskBarPlace::default())),
kind: TaskBarKind::Selection,
side: None,
dismiss: TaskBarDismiss::Close,
}
}
/// 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, kind, side, dismiss } = self;
let _ = (kind, side, dismiss); // P3(canvas-w8): cv.K13
let side = side.unwrap_or(match kind {
TaskBarKind::Task => Side::Below,
TaskBarKind::Selection => Side::Above,
});
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.
@@ -209,9 +221,13 @@ impl<'a> TaskBar<'a> {
Some(Mixed::Same(held)) => held,
_ => TaskBarPlace::default(),
};
let hang = shows.then(|| hang_rect(bounds, env.tokens.space.gap.section));
let layer = TaskBarLayer::new(label, words.task_bar_move.clone(), layer_overlay(&held, hang, area), shows);
let mut menu = MoreMenu { words: Arc::clone(&words), placed: false, pick: None };
let hang = shows.then(|| hang_rect(bounds, env.tokens.space.gap.section, side));
let overlay = match kind {
TaskBarKind::Task => layer_overlay(&held, hang, area, side),
TaskBarKind::Selection => selection_overlay(hang, area, dismiss, side),
};
let layer = TaskBarLayer::new(label, words.task_bar_move.clone(), overlay, shows, kind);
let mut menu = MoreMenu { words: Arc::clone(&words), offered: kind == TaskBarKind::Task, placed: false, pick: None };
let mut shown = layer.show(ui, |ui, _| {
Bar::new(Label::Empty, BarKind::Tool).show(ui, |ui, _| {
menu.placed = false;
@@ -222,7 +238,7 @@ impl<'a> TaskBar<'a> {
});
let rect = shown.output.response.rect;
let pick = menu.pick;
if shows {
if shows && kind == TaskBarKind::Task {
let moved = shown.output.moved.filter(|moved| moved.min != rect.min);
let next = settled(held, rect, area, moved, pick);
if next != held {
@@ -235,7 +251,12 @@ impl<'a> TaskBar<'a> {
let _ = shown.settle(|cx, _| place.reborrow().write(cx, &event));
}
}
let output = TaskBarOutput { response: shown.output.response, hide: pick == Some(MenuPick::Hide), rect, closed: false };
let output = TaskBarOutput {
response: shown.output.response,
hide: pick == Some(MenuPick::Hide),
rect,
closed: shown.output.closed.is_some(),
};
match shown.inner {
Some(bar) => Inner { output, inner: bar.inner, settle: bar.settle },
None => Inner { output, inner: None, settle: None },
@@ -243,21 +264,40 @@ 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))
/// The rect the bar hangs from: the anchor's screen `bounds` grown by `gap` on the bar's `side`. A side along the
/// reading direction grows both ends, so the gap is kept in either direction. The overlay host keeps the layer inside
/// `Overlay::bounds`.
fn hang_rect(bounds: Rect, gap: f32, side: Side) -> Rect {
match side {
Side::Above => Rect::from_min_max(Pos2::new(bounds.min.x, bounds.min.y - gap), bounds.max),
Side::Below => Rect::from_min_max(bounds.min, Pos2::new(bounds.max.x, bounds.max.y + gap)),
_ => bounds.expand2(egui::vec2(gap, 0.0)),
}
}
/// 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 {
/// The layer of a selection bar: hung on `side` of `hang`, flipped and kept inside `area`, never moved by the user.
/// `dismiss` says what an outside press does to it.
fn selection_overlay(hang: Option<Rect>, area: Rect, dismiss: TaskBarDismiss, side: Side) -> Overlay {
let outside = match dismiss {
TaskBarDismiss::Close => Outside::Close,
TaskBarDismiss::Keep => Outside::Keep,
};
let overlay = Overlay::floating().modeless().body_scroll(false).dismiss(Dismiss::new().outside(outside));
match hang {
Some(hang) => overlay.bounds(area).place(Place::anchored(Anchor::Rect(hang), side, Align::Center)),
None => overlay,
}
}
/// The layer the bar shows in: hung on `side` of `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, side: Side) -> 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)),
None => overlay.place(Place::anchored(Anchor::Rect(hang), side, Align::Center)),
}
}
@@ -291,11 +331,12 @@ pub struct TaskBarLayerStyle {
metrics: Metrics,
}
/// What the task bar's layer reports: its response and the last move of this pass.
/// What the task bar's layer reports: its response, the last move of this pass and why it closed.
#[derive(Debug)]
struct TaskBarLayerOutput {
response: Response,
moved: Option<Rect>,
closed: Option<CloseReason>,
}
impl Outcome for TaskBarLayerOutput {
@@ -319,17 +360,22 @@ struct TaskBarLayer {
/// Open while the bar shows; the caller shows the bar again each pass it wants it.
open: Bind<'static, bool>,
moved: Option<Rect>,
/// Why the layer closed, once it has.
closed: Option<CloseReason>,
}
impl TaskBarLayer {
fn new(label: Label, grip: Label, overlay: Overlay, open: bool) -> Self {
let props = ContainerProps::new()
.mount(Mount::Layer(overlay))
.surface(SurfaceKind::Floating)
.pad(Pad::None)
.sizing(Sizing::Content)
.header(HeaderRegion::new().band(DragBand::Move).inline(true));
TaskBarLayer { common: Common::new(), props, grip, open: Bind::given(open), moved: None }.label(label).id_salt("task-bar")
/// A layer for a bar of `kind`: only the task bar has the grip header that moves it.
fn new(label: Label, grip: Label, overlay: Overlay, open: bool, kind: TaskBarKind) -> Self {
let mut props = ContainerProps::new().mount(Mount::Layer(overlay)).surface(SurfaceKind::Floating).pad(Pad::None).sizing(Sizing::Content);
let salt = match kind {
TaskBarKind::Task => {
props = props.header(HeaderRegion::new().band(DragBand::Move).inline(true));
"task-bar"
}
TaskBarKind::Selection => "selection-bar",
};
TaskBarLayer { common: Common::new(), props, grip, open: Bind::given(open), moved: None, closed: None }.label(label).id_salt(salt)
}
}
@@ -349,7 +395,7 @@ impl Component for TaskBarLayer {
}
fn finish(self, cx: Cx<'_, Self>) -> TaskBarLayerOutput {
TaskBarLayerOutput { response: cx.response.clone(), moved: self.moved }
TaskBarLayerOutput { response: cx.response.clone(), moved: self.moved, closed: self.closed }
}
}
@@ -363,6 +409,10 @@ impl Container for TaskBarLayer {
let _ = Icon::new(IconSpec::svg(IconId::new("grip"))).label(self.grip.clone()).show(ui);
}
fn closed(&mut self, why: CloseReason) {
self.closed.get_or_insert(why);
}
fn placement_changed(&mut self, change: &PlacementChange) {
if change.kind == PlacementKind::Move {
self.moved = Some(change.rect);
@@ -1,12 +1,13 @@
//! Stories of `TaskBar`.
use super::{TaskBar, TaskBarPlace};
use super::{TaskBar, TaskBarDismiss, 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 craft_behavior::IconId;
use craft_behavior::kurbo::{Point, Vec2};
use craft_behavior::overlay::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
@@ -17,6 +18,49 @@ fn turned_frame() -> [Point; 4] {
[(-220.0, -130.0), (220.0, -130.0), (220.0, 130.0), (-220.0, 130.0)].map(|(x, y)| centre + Vec2::new(x * cos - y * sin, x * sin + y * cos))
}
/// A strip of document at its top edge, where a bar above it has no room.
fn top_strip() -> [Point; 4] {
[(120.0, 0.0), (520.0, 0.0), (520.0, 30.0), (120.0, 30.0)].map(|(x, y)| Point::new(x, y))
}
/// The members of a selection bar.
fn formatting(ui: &mut Ui) {
for (icon, name) in [("rotate_ccw", "Rotate left"), ("rotate_cw", "Rotate right")] {
let _ = IconButton::new(IconId::new(icon)).label(name).show(ui);
}
let _ = Button::new("Done").show(ui);
}
/// A selection bar over a selection: above it, centred.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn selection_bar_over_a_selection(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let corners = turned_frame();
on_canvas(ui, |ui, area, _| TaskBar::selection("Selection", &corners).show(ui, area, |ui, _| formatting(ui)).output)
}
/// A selection bar flips below its selection when there is no room above it.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn selection_bar_flipped_near_the_top_edge(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let strip = top_strip();
on_canvas(ui, |ui, area, _| TaskBar::selection("Selection", &strip).show(ui, area, |ui, _| formatting(ui)).output)
}
/// A selection bar on the other side of its selection: after it in reading order.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn selection_bar_on_the_other_side(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let corners = turned_frame();
on_canvas(ui, |ui, area, _| TaskBar::selection("Selection", &corners).side(Side::End).show(ui, area, |ui, _| formatting(ui)).output)
}
/// A selection bar that survives presses outside it while its graphic is selected.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn selection_bar_kept_while_selected(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let corners = turned_frame();
on_canvas(ui, |ui, area, _| {
TaskBar::selection("Selection", &corners).dismiss(TaskBarDismiss::Keep).show(ui, area, |ui, _| formatting(ui)).output
})
}
/// The Crop tool's bar: three buttons, the More menu, then Cancel and Done after it.
#[story(TaskBar<'static>, covers = [], drive = Drive::Never)]
fn crop_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
@@ -3,7 +3,7 @@
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
use craft_ui::buttons::Button;
use craft_ui::canvas_controls::{TaskBar, TaskBarPlace};
use craft_ui::canvas_controls::{TaskBar, TaskBarDismiss, TaskBarPlace};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::testing::canvas_story::on_canvas;
use craft_ui::testing::{Fixture, trial};
@@ -58,6 +58,67 @@ fn seen(scene: &Rc<RefCell<Scene>>) -> Scene {
scene.borrow().clone()
}
/// What the selection bar trials' canvas shows and what the bar reported.
#[derive(Clone)]
struct Pick {
/// The anchor in document points; empty once the bar closed, so the caller stops showing it.
anchor: Vec<Point>,
/// The anchor sits at the top edge of the canvas area instead of in its middle.
at_top: bool,
dismiss: TaskBarDismiss,
bounds: Rect,
area: Rect,
rect: Rect,
/// The bar reported a close in some pass.
closed: bool,
}
/// A canvas that shows a selection bar over the pick's anchor, with one button.
fn pick_fixture(pick: &Rc<RefCell<Pick>>) -> Fixture {
let shared = Rc::clone(pick);
let mut fixture = Fixture::new(move |ui| {
let _ = on_canvas(ui, |ui, area, view| {
let mut held = shared.borrow_mut();
let pick = &mut *held;
if pick.at_top && !pick.closed {
let origin = view.to_screen(Point::ZERO);
let scale = f64::from(view.to_screen(Point::new(1.0, 0.0)).x - origin.x);
let y = f64::from(area.min.y + 2.0 - origin.y) / scale;
pick.anchor = [(120.0, y), (520.0, y), (520.0, y + 30.0), (120.0, y + 30.0)].map(|(x, y)| Point::new(x, y)).to_vec();
}
pick.bounds = Rect::from_points(&pick.anchor.iter().map(|point| view.to_screen(*point)).collect::<Vec<_>>());
pick.area = area;
let shown = TaskBar::selection("Selection", &pick.anchor).dismiss(pick.dismiss).show(ui, area, |ui, _| {
let _ = Button::new("Bold").show(ui);
});
pick.rect = shown.output.rect;
if shown.output.closed {
pick.closed = true;
pick.anchor.clear();
}
shown.output
});
});
fixture.room(Vec2::new(1120.0, 720.0));
fixture
}
fn picked(pick: &Rc<RefCell<Pick>>) -> Pick {
pick.borrow().clone()
}
fn new_pick(dismiss: TaskBarDismiss, at_top: bool) -> Rc<RefCell<Pick>> {
Rc::new(RefCell::new(Pick {
anchor: frame(DocVec::ZERO),
at_top,
dismiss,
bounds: Rect::NOTHING,
area: Rect::NOTHING,
rect: Rect::NOTHING,
closed: false,
}))
}
fn centred_under_anchor(scene: &Scene) -> bool {
(scene.rect.center().x - scene.bounds.center().x).abs() < SLACK && scene.rect.top() > scene.bounds.bottom()
}
@@ -74,6 +135,51 @@ fn pick(fixture: &mut Fixture, row: &str) {
fixture.click(&row).settle();
}
#[trial]
fn a_selection_bar_hangs_above_its_anchor_flips_below_without_room_and_cannot_be_moved() {
let pick = new_pick(TaskBarDismiss::Close, false);
let mut fixture = pick_fixture(&pick);
fixture.settle();
let above = picked(&pick);
assert!(above.rect.is_positive(), "the bar shows: {:?}", above.rect);
assert!(above.rect.bottom() <= above.bounds.top() + SLACK, "above the anchor {:?}: {:?}", above.bounds, above.rect);
assert!((above.rect.center().x - above.bounds.center().x).abs() < SLACK, "centred on the anchor");
// A press and drag on the bar's own edge, away from its button, moves nothing: it has no move band.
fixture.drag_at(above.rect.min + Vec2::new(1.0, 1.0), Vec2::new(-100.0, 60.0)).settle();
let dragged = picked(&pick);
assert!((dragged.rect.min - above.rect.min).length() < SLACK, "a drag on the bar leaves it: {:?} then {:?}", above.rect, dragged.rect);
pick.borrow_mut().at_top = true;
fixture.settle();
let flipped = picked(&pick);
assert!(flipped.rect.top() >= flipped.bounds.bottom() - SLACK, "below the anchor {:?} with no room above: {:?}", flipped.bounds, flipped.rect);
assert!(flipped.area.expand(SLACK).contains_rect(flipped.rect), "inside the canvas {:?}: {:?}", flipped.area, flipped.rect);
}
#[trial]
fn an_outside_press_closes_a_selection_bar_and_reports_it_unless_it_keeps() {
for dismiss in [TaskBarDismiss::Close, TaskBarDismiss::Keep] {
let pick = new_pick(dismiss, false);
let mut fixture = pick_fixture(&pick);
fixture.settle();
assert!(fixture.by_label("Bold").is_some(), "{dismiss:?}: the bar shows");
let area = picked(&pick).area;
fixture.click_at(egui::pos2(area.min.x + 10.0, area.max.y - 10.0)).settle();
let after = picked(&pick);
match dismiss {
TaskBarDismiss::Keep => {
assert!(!after.closed, "Keep reports no close");
assert!(fixture.by_label("Bold").is_some(), "Keep stays after an outside press");
}
_ => {
assert!(after.closed, "Close reports the close");
assert!(fixture.by_label("Bold").is_none(), "Close stops showing the bar");
}
}
}
}
#[trial]
fn the_task_bar_follows_its_anchor_until_moved_and_stays_inside_the_area() {
let scene = Rc::new(RefCell::new(Scene {
+88 -6
View File
@@ -2,10 +2,11 @@
use super::item::{MenuItem, MenuItemOutput};
use super::level::{LevelMemory, MenuLevel, level_env};
use crate::contract::overlay::{Anchor, Dismiss, Outside, Popup};
use super::words::MenuWords;
use crate::contract::overlay::{Anchor, Dismiss, Outside, Place, Popup};
use crate::contract::{
Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Entry, Focus as _, Gap, InMenu, LeastWidth, Mount, NoValue, Outcome,
Overlay, POPUP_PAD, Pointer as _, Props as _, Remember as _, Role, Scroll, Show as _, ShowContainer as _, TooltipSpec, Trigger,
Overlay, POPUP_PAD, Pad, Pointer as _, Props as _, Remember as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, TooltipSpec, Trigger,
};
use crate::display::Divider;
use crate::runtime::env::{Env, Label};
@@ -13,6 +14,7 @@ use crate::runtime::focus::{FocusPolicy, Initial};
use crate::runtime::frame;
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::overlay::{Align, Side};
use craft_behavior::{Arrows, Metrics, NavShape, Roving, Sense, Value};
use craft_keymap::{Chord, Key};
use egui::{Response, Ui};
@@ -169,7 +171,6 @@ pub struct Menu<'a> {
/// The Left or Right key a top-level level left unhandled.
step: Option<MenuStep>,
/// The bar shown above the menu in its own modeless layer.
#[allow(dead_code)] // P3(canvas-w8): cv.K40
companion: Option<&'a mut dyn FnMut(&mut Ui)>,
}
@@ -177,9 +178,9 @@ impl<'a> Menu<'a> {
/// A modeless bar layer above the menu, in its press family; it closes with the menu, and Escape closes the top
/// layer first.
#[must_use]
pub fn companion(self, bar: &'a mut dyn FnMut(&mut Ui)) -> Self {
let _ = bar;
todo!("cv.K40")
pub fn companion(mut self, bar: &'a mut dyn FnMut(&mut Ui)) -> Self {
self.companion = Some(bar);
self
}
/// A menu named `label`. Its open state is the menu's slot until [`open`](Menu::open) binds it.
@@ -409,4 +410,85 @@ impl Container for Menu<'_> {
fn closed(&mut self, why: CloseReason) {
self.closed.get_or_insert(why);
}
/// The companion bar, shown as a child layer of the menu's: it is in the menu's press family and closes with the
/// menu.
fn end(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) {
let Some(bar) = self.companion.as_mut() else { return };
let label = Env::of(ui).words::<MenuWords>().bar_companion.clone();
let _ = CompanionLayer::new(label).show(ui, |ui, _| bar(ui));
}
}
/// The style of a menu's companion layer: the surface comes from the container.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[non_exhaustive]
struct CompanionLayerStyle {
#[style(metrics)]
metrics: Metrics,
}
/// What a companion layer reports.
#[derive(Debug)]
struct CompanionOutput {
response: Response,
}
impl Outcome for CompanionOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// The modeless layer a menu's companion bar shows in, above the menu's panel. It takes no focus on open and has no
/// opener of its own: it is open while the menu's body runs it.
#[derive(crate::contract::Component)]
#[component(container, unregistered)]
struct CompanionLayer {
#[common]
common: Common,
#[container]
props: ContainerProps,
open: Bind<'static, bool>,
}
impl CompanionLayer {
fn new(label: Label) -> Self {
let overlay = Overlay::floating()
.modeless()
.body_scroll(false)
.focus(FocusPolicy::TAB_LAYER)
.dismiss(Dismiss::new().outside(Outside::Keep))
.place(Place::anchored(Anchor::Parent, Side::Above, Align::Center));
let props = ContainerProps::new().mount(Mount::Layer(overlay)).surface(SurfaceKind::Floating).pad(Pad::None).sizing(Sizing::Content);
CompanionLayer { common: Common::new(), props, open: Bind::given(true) }.label(label).id_salt("menu-companion")
}
}
impl Component for CompanionLayer {
const ROLE: Role = Role::GROUP;
const PARTS: bool = false;
const STOPS: bool = false;
type Style = CompanionLayerStyle;
type Output = CompanionOutput;
fn style(_: &StyleCx<'_>, _: CompanionLayerStyleKey) -> CompanionLayerStyle {
CompanionLayerStyle::default()
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn finish(self, cx: Cx<'_, Self>) -> CompanionOutput {
CompanionOutput { response: cx.response.clone() }
}
}
impl Container for CompanionLayer {
fn open(&mut self) -> Option<BindMut<'_, bool>> {
Some(self.open.reborrow())
}
}
+1
View File
@@ -5,6 +5,7 @@ craft_ui::words! {
pub struct MenuWords {
bar_more: "menu.barMore" = "…";
bar_all: "menu.barAll" = "Menu";
bar_companion: "menu.barCompanion" = "Menu bar";
bar_search: "menu.barSearch" = "Search menus";
bar_no_matches: "menu.barNoMatches" = "No matching commands";
edit: "menu.edit" = "Edit";
@@ -0,0 +1,93 @@
//! A menu's companion bar: a layer above the menu in its press family.
use craft_ui::buttons::Button;
use craft_ui::contract::{Role, Show as _, ShowContainer as _, Trigger};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Key, Modifiers, Pos2, Ui, Vec2};
use std::cell::Cell;
use std::rc::Rc;
/// A page with a target to right-click, a context menu with a companion bar holding a Size button that opens a list,
/// and a page button far from both. `page` counts the page button's clicks.
fn fixture(page: &Rc<Cell<u32>>) -> Fixture {
let page = Rc::clone(page);
let mut fixture = Fixture::new(move |ui| {
ui.add_space(120.0);
let target = Button::new("Target").show(ui);
ui.add_space(300.0);
if Button::new("Page").show(ui).clicks > 0 {
page.set(page.get() + 1);
}
let mut bar = |ui: &mut Ui| {
let size = Button::new("Size").show(ui);
Menu::new("Size list").opened_by(&size, Trigger::Click).show(ui, |ui, _| {
MenuItem::new("Twelve").show(ui);
});
};
Menu::context("Target menu", &target).companion(&mut bar).show(ui, |ui, _| {
MenuItem::new("Copy").show(ui);
});
});
fixture.room(Vec2::new(800.0, 640.0));
fixture
}
/// Right-clicks at `at`: move, secondary press, secondary release.
fn right_click(fixture: &mut Fixture, at: Pos2) {
fixture.frame(vec![pointer::moved(at)]);
fixture.frame(vec![pointer::secondary(at, true)]);
fixture.frame(vec![pointer::secondary(at, false)]);
fixture.settle();
}
/// Opens the context menu on the target and the Size list from the bar.
fn open_all(fixture: &mut Fixture) {
fixture.settle();
let target = fixture.by_label("Target").expect("the target has a node").center();
right_click(fixture, target);
assert!(fixture.by_label("Copy").is_some(), "the right-click opens the menu");
assert!(fixture.by_label("Size").is_some(), "the menu shows its companion bar");
}
#[trial]
fn a_press_on_the_companion_bar_or_its_popup_does_not_close_the_menu_and_the_bar_closes_with_the_menu() {
let page = Rc::new(Cell::new(0));
let mut fixture = fixture(&page);
open_all(&mut fixture);
let size = fixture.by_label("Size").expect("the bar's button");
fixture.click(&size).settle();
assert!(fixture.by_label("Twelve").is_some(), "the bar's button opens its list");
assert!(fixture.by_label("Copy").is_some(), "a press on the bar leaves the menu open");
let twelve = fixture.by_label("Twelve").expect("the list's row");
let list = fixture.by_role(Role::MENU).into_iter().find(|menu| menu.rect.contains(twelve.center())).expect("the list's panel");
fixture.click_at(list.rect.min + Vec2::new(1.0, 1.0)).settle();
assert!(fixture.by_label("Copy").is_some(), "a press on the bar's popup leaves the menu open");
assert_eq!(page.get(), 0, "no press reached the page");
let at = fixture.by_label("Page").expect("the page button").center();
fixture.click_at(at).settle();
assert!(fixture.by_label("Copy").is_none(), "a press outside closes the menu");
assert!(fixture.by_label("Size").is_none(), "the bar closes with the menu");
assert_eq!(page.get(), 0, "the press that closed the menu did not reach the page");
}
#[trial]
fn escape_closes_the_topmost_layer_first() {
let page = Rc::new(Cell::new(0));
let mut fixture = fixture(&page);
open_all(&mut fixture);
let size = fixture.by_label("Size").expect("the bar's button");
fixture.click(&size).settle();
assert!(fixture.by_label("Twelve").is_some(), "the list is open");
fixture.key(Key::Escape, Modifiers::NONE).settle();
assert!(fixture.by_label("Twelve").is_none(), "Escape closes the bar's list first");
assert!(fixture.by_label("Copy").is_some() && fixture.by_label("Size").is_some(), "the menu and its bar stay after the first Escape");
fixture.key(Key::Escape, Modifiers::NONE).settle();
assert!(fixture.by_label("Copy").is_none(), "the next Escape closes the menu");
assert!(fixture.by_label("Size").is_none(), "the bar goes with the menu");
}
+4
View File
@@ -4,6 +4,8 @@ mod bar;
mod closed;
mod companion;
mod native;
mod openers;
@@ -14,6 +16,8 @@ mod pick_focus;
mod rows;
mod search;
mod submenus;
use craft_behavior::IconId;