Merge branch 'sync/next2' into sync/delta11

This commit is contained in:
bflatastic
2026-11-23 17:13:44 +07:00
16 changed files with 272 additions and 62 deletions
+2 -3
View File
@@ -23,9 +23,8 @@ use egui::Pos2;
/// The rotation step of the Rotate View commands, in degrees.
const ROTATE_STEP_DEG: f64 = 15.0;
/// The room Fit Artboard on Screen leaves around the board, in points: at the sides, and above and below (the board's
/// name sits above it).
const ARTBOARD_MARGIN: Vec2 = Vec2::new(30.0, 40.0);
/// The room Fit Artboard on Screen leaves around the board on each side, in points.
const ARTBOARD_MARGIN: Vec2 = Vec2::new(30.0, 30.0);
/// The room Fit Layers on Screen leaves around the layers' bounds, in points.
const LAYERS_MARGIN: Vec2 = Vec2::new(20.0, 20.0);
+1 -1
View File
@@ -16,7 +16,7 @@ mod props;
mod toggles;
mod ui;
pub use container_open::Popup;
pub use container_open::{Popup, opened_from};
pub(crate) use container_open::{opener_open, set_opener_open};
pub use host::paint_frame_layers;
pub(crate) use host::{Layer, forget_layer, host, host_window};
@@ -61,8 +61,11 @@ pub(crate) fn opener_open(stage: &mut MemoryStage, first: &Opener) -> bool {
open
}
/// Whether the container hung from the opener `opener` (the id of its response) is open, as its slot holds it.
pub(crate) fn opened_from(ctx: &egui::Context, opener: Id) -> bool {
/// Whether the container hung from the opener `opener` (the id of its response, [`Overlay::opened_by`]) is open, as
/// its slot holds it: an opener reports its expanded state by it.
///
/// [`Overlay::opened_by`]: super::Overlay::opened_by
pub fn opened_from(ctx: &egui::Context, opener: Id) -> bool {
MemoryStage::peek_session::<OpenerOpen>(ctx, sub(opener, "opens")).open
}
+7 -2
View File
@@ -587,16 +587,21 @@ impl Fixture {
}
/// The node named `label`: the interactive node whose name resolves to it (its own, or the node that labels it
/// through `labelled_by`), else the first node that carries the text.
/// through `labelled_by`) and that labels no other node, so a field's control comes before its caption link;
/// else the first node that carries the text.
pub fn by_label(&self, label: &str) -> Option<Target> {
let tree = &self.tree;
let reported: HashSet<NodeKey> = tree.keys().into_iter().collect();
let labels: HashSet<NodeKey> = reported.iter().flat_map(|key| tree.labelled_by_key(*key)).collect();
let ordered = self.in_tree_order(&reported);
let node = ordered
.iter()
.copied()
.find(|key| {
super::access::name(tree, *key) == Some(label) && tree.role_of(*key) != Some(Role::LABEL) && super::access::is_interactive(tree, *key)
super::access::name(tree, *key) == Some(label)
&& tree.role_of(*key) != Some(Role::LABEL)
&& !labels.contains(key)
&& super::access::is_interactive(tree, *key)
})
.or_else(|| ordered.iter().copied().find(|key| tree.name_of(*key) == Some(label)))?;
self.target(node)
+5 -5
View File
@@ -1,6 +1,6 @@
//! `Flyout`: the panel an icon of an iconic column opens beside the column.
use crate::contract::overlay::{Anchor, Dismiss, FloatPlace, Place, PlacementChange, ResizeEdges};
use crate::contract::overlay::{Anchor, Dismiss, FloatPlace, Outside, Place, PlacementChange, ResizeEdges};
use crate::contract::{
BodyCx, Common, Component, Container, ContainerProps, Cx, Mount, NoValue, Outcome, Overlay, OverlayUi, Pad, PopupHandle, Role, SizeLimits, Sizing,
};
@@ -48,8 +48,8 @@ impl Outcome for FlyoutOutput {
}
}
/// A popup beside an iconic column, on the side of the canvas, whose top left the caller places. Escape and a press
/// outside close it; with Auto-Collapse Iconic Panels the focus leaving it closes it too. Its body is measured at the
/// A popup beside an iconic column, on the side of the canvas, whose top left the caller places. Escape closes it; with
/// Auto-Collapse Iconic Panels a press outside it and the focus leaving it close it too. Its body is measured at the
/// flyout's width first: the flyout is as tall as the body measures within the room below its top, and at least its
/// `size`'s height, and the body then shows in the rect that takes.
///
@@ -77,7 +77,7 @@ pub struct Flyout {
impl Flyout {
/// A flyout at least `size` that opens on the side `opens` of its column, in reading order (`Side::Start` or
/// `Side::End`), closing when the focus leaves it if `auto_collapse`.
/// `Side::End`), closing on a press outside it and when the focus leaves it if `auto_collapse`.
pub fn new(opens: Side, size: Vec2, auto_collapse: bool) -> Self {
let props = ContainerProps::new().surface(SurfaceKind::Popup).pad(Pad::None).sizing(Sizing::Content);
Flyout { common: Common::new(), props, opens, size, auto_collapse, within: Rect::EVERYTHING, least: Vec2::ZERO, placed: None }
@@ -96,7 +96,7 @@ impl Flyout {
.placed_at(top_left)
.size_limits(SizeLimits::at_least(least))
.resize_edges(free.union(ResizeEdges::TOP).union(ResizeEdges::BOTTOM))
.dismiss(Dismiss::new().focus_left(self.auto_collapse))
.dismiss(Dismiss::new().outside(if self.auto_collapse { Outside::Close } else { Outside::Keep }).focus_left(self.auto_collapse))
.body_scroll(false);
if bounded { overlay.bounds(self.within) } else { overlay }
}
+2 -3
View File
@@ -153,9 +153,8 @@ pub struct IconicColumnStyle {
/// icon, cut with an ellipsis to the cell; a click or drag on the name acts as one on the icon. A click or Enter on an icon
/// opens the flyout of its panel beside the column, switches it to that panel or closes it; one flyout is open at a
/// time. A drag of an icon starts a move of its panel, a drag of the grip on top of a group a move of the group, a
/// drag of the bar beside its button a move of the column; each starts through the drag session, and a press outside
/// the flyout closes it. Escape and a press
/// outside close the flyout; with `auto_collapse` the focus leaving it does too.
/// drag of the bar beside its button a move of the column; each starts through the drag session. Escape closes the
/// flyout; with `auto_collapse` a press outside it and the focus leaving it do too.
///
/// The open flyout is the bound `Option<P>` of [`new`](IconicColumn::new), owned by the host like the layout: a click
/// on an icon, Escape and auto-collapse write it, and the host opens a panel (the Window menu) by writing it. The
@@ -140,6 +140,11 @@ struct Flyouts {
impl Flyouts {
/// A column of `groups` on the right window edge when `right`, else the left one; its flyouts stay in `within`.
fn new(groups: &[&[u8]], right: bool, within: Rect) -> Self {
Self::with(groups, right, within, false)
}
/// [`Flyouts::new`] with Auto-Collapse Iconic Panels on when `auto_collapse`.
fn with(groups: &[&[u8]], right: bool, within: Rect, auto_collapse: bool) -> Self {
let mut column = Column::new(groups.iter().map(|panels| Group::new(panels.to_vec(), 0)).collect());
column.iconic = true;
let edge = if right { DockEdge::End } else { DockEdge::Start };
@@ -159,6 +164,7 @@ impl Flyouts {
.edge(edge)
.opens(if right { Side::Start } else { Side::End })
.within(within)
.auto_collapse(auto_collapse)
.show_flyouts_at(ui, place, |group, at, ui, _| {
let GroupAt::Show(rect) = at else { return None };
let panel = *group.active_panel()?;
@@ -220,6 +226,18 @@ impl Flyouts {
}
}
/// A press outside the open flyout leaves it open; with Auto-Collapse Iconic Panels on it closes it.
#[trial]
fn a_press_outside_closes_the_flyout_only_with_auto_collapse() {
for auto_collapse in [false, true] {
let mut d = Flyouts::with(&[&[1, 2]], false, screen(), auto_collapse);
d.open("Brushes");
let away = d.rect().right_center() + Vec2::new(100.0, 0.0);
d.fixture.click_at(away).settle();
assert_eq!(d.shown.get().is_none(), auto_collapse, "auto-collapse {auto_collapse}: a press outside closes the flyout only with it on");
}
}
/// The top edge and the free top corner grow the flyout upward on either window edge: the bottom and the column-side
/// edge stay, the column-side edge has no grip, and the new top is kept as an offset from the icons, so it survives
/// another group's flyout and reopening.
+51 -17
View File
@@ -5,8 +5,8 @@ use super::flyout::{FlyoutButton, SlotEdit};
use super::words::RailWords;
use crate::buttons::IconButton;
use crate::contract::{
Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, NoValue, Outcome, Pad, Props as _, Role, Scroll, Show as _,
ShowContainer as _, Sizing, WordSetCx as _,
Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, NoValue, Outcome, Pad, Pointer as _, Props as _, Role, Scroll,
Show as _, ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::contract::{BodyCx, BodyLayout, MemoProps, MemoView, Outbox, PlainData, ThemeScope, Tracked};
use crate::display::{Elide, Shade, TargetMark, Text};
@@ -21,7 +21,9 @@ use crate::tabs::TornOff;
use craft_behavior::overlay::Side;
use craft_behavior::{IconId, Metrics, NavShape, Proposal, Roving, Sense, Value};
use craft_theme::ControlSize;
use egui::{Id, Response, Ui, Vec2};
use egui::{Id, Rect, Response, Ui, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
mod data;
mod drag;
@@ -32,6 +34,7 @@ pub(crate) mod trials;
use data::row_groups;
pub use data::{LastUsed, RailTool, SlotId, ToolSlot, ToolTips, remembered, shown_tool, visible_slots};
use drag::RailDrop;
pub(crate) use drag::SlotDrop;
pub use drag::{DropAt, ToolDrag, ToolDropped, drop_in_slot};
@@ -67,7 +70,7 @@ pub struct ToolRailOutput<T> {
pub edit_toolbar: Option<Response>,
/// The slot whose flyout is open.
pub flyout: Option<SlotId>,
/// A tool dropped on a slot while the toolbar is edited, and where it goes.
/// A tool dropped on the rail while the toolbar is edited, and where it goes.
pub dropped: Option<ToolDropped>,
/// A group torn off the rail: `keys` and `grabbed` the slot, `pointer` where it tore off.
pub torn_off: Option<TornOff<SlotId>>,
@@ -106,7 +109,9 @@ type FooterFn<'a> = Box<dyn FnMut(&mut Ui, RailFooter) + 'a>;
/// an overlay bar in the end padding that shows only under the pointer (`Scroll::overlay`), and its
/// buttons show the rail's glyphs. The rail is exactly as tall as its rows and footer at the width it gets
/// ([`measure_rail`](ToolRail::measure_rail)). The buttons are one roving group: arrow keys move between them by the
/// grid. While the toolbar is edited the buttons are dragged and take drops, and report the drop in the output.
/// grid. While the toolbar is edited the buttons are dragged and the rail takes drops, and reports the drop in the
/// output: on a button by where over it the drop falls ([`drop_in_slot`]), elsewhere on the rail as a slot of its own
/// beside the nearest button, and on a rail with no buttons as the last slot.
///
/// With `captions` the caption of the first slot of a row group that has one ([`ToolSlot::captioned`]) stands above
/// the group in the caption type, cut at the rail's width; without it a caption takes no room. The grid's width
@@ -153,6 +158,8 @@ pub struct ToolRail<'a, T: Value + MemoProps + PlainData + 'static> {
footer: Option<FooterFn<'a>>,
/// The columns the rail lays out in this pass.
columns: usize,
/// The host's index and rect of each button the grid showed in this pass.
shown: Rc<RefCell<Vec<(usize, Rect)>>>,
}
impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
@@ -185,6 +192,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
tips: None,
footer: None,
columns: 1,
shown: Rc::default(),
}
.label(label)
}
@@ -289,8 +297,8 @@ struct Draw<'a, T: PlainData> {
impl<T: Value + MemoProps + PlainData> Draw<'_, T> {
/// Shows the grid as a memoized view; what the buttons report goes into `events` (nothing on a replay). Returns the
/// Edit Toolbar button's id while the rail shows it.
fn run(&self, ui: &mut Ui, events: &mut Vec<RailEvent<T>>) -> Option<Id> {
/// Edit Toolbar button's id while the rail shows it, and the host's index and rect of each slot button.
fn run(&self, ui: &mut Ui, events: &mut Vec<RailEvent<T>>) -> (Option<Id>, Vec<(usize, Rect)>) {
let tips = self.tips.map(HostTips);
let props = GridProps {
slots: self.slots,
@@ -308,13 +316,14 @@ impl<T: Value + MemoProps + PlainData> Draw<'_, T> {
reveal: self.reveal,
sent: Outbox::new(events),
};
MemoView::new("slots", props, grid::<T>).show(ui).flatten()
MemoView::new("slots", props, grid::<T>).show(ui).unwrap_or_default()
}
}
/// The grid of buttons in rows of `columns`, each row group under its caption while the rail shows captions. The result
/// is the Edit Toolbar button's id, which the rail's output turns into its response.
fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut Ui) -> Option<Id> {
/// is the Edit Toolbar button's id, which the rail's output turns into its response, and the host's index and rect of
/// each slot button, around which the rail takes drops.
fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut Ui) -> (Option<Id>, Vec<(usize, Rect)>) {
let GridProps { slots, current, last_used, hidden, editing, columns, opens, captions, tear_off, tips, mark, reveal, .. } = *props;
let tips = tips.map(|tips| tips.0);
let visible = visible_slots(slots, hidden_in(hidden));
@@ -328,7 +337,7 @@ fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut
let end = group.last().map_or(first, |last| (last + columns).min(cells));
visible.get(first..end.min(visible.len()))?.iter().find_map(|(index, _)| slots[*index].caption.clone())
};
let mut edit_toolbar = None;
let (mut edit_toolbar, mut shown_at) = (None, Vec::with_capacity(visible.len()));
let sent = &mut props.sent;
// The grid of buttons sits at the centre of the rail's width.
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
@@ -374,6 +383,7 @@ fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut
Some(tips) => button.show_with_tip(ui, |ui| tips.show(&shown.id, ui)),
None => button.show(ui),
};
shown_at.push((*index, out.response.rect));
// The slot wears the mark; while its flyout is open the tool's row does.
if marked.is_some() && !out.opened {
TargetMark::new(out.response.rect).id_salt(("mark", slot.id)).show_mark(ui);
@@ -408,7 +418,7 @@ fn grid<T: Value + MemoProps + PlainData>(props: &mut GridProps<'_, T>, ui: &mut
}
});
});
edit_toolbar
(edit_toolbar, shown_at)
}
impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
@@ -435,8 +445,12 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
remembered(draw.slots, draw.current, draw.last_used)
});
let last = last.as_ref().clone();
let (mut events, mut edit_toolbar) = (Vec::new(), None);
let shown = self.show(ui, |ui, _| edit_toolbar = draw.run(ui, &mut events));
let (mut events, mut edit_toolbar, laid) = (Vec::new(), None, Rc::clone(&self.shown));
let shown = self.show(ui, |ui, _| {
let (edit, slots) = draw.run(ui, &mut events);
edit_toolbar = edit;
*laid.borrow_mut() = slots;
});
let (mut select, mut double_clicked, mut flyout, mut dropped, mut torn_off, mut ran) = (None, None, None, None, None, None);
for event in events {
match event {
@@ -454,7 +468,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> {
// A replayed grid sends nothing: its button is shown again, and its response is read back.
edit_toolbar: ran.or_else(|| edit_toolbar.and_then(|id| crate::contract::response_of(ui, id))),
flyout,
dropped,
dropped: dropped.or(shown.output.dropped),
torn_off,
last_used: last,
..shown.output
@@ -494,20 +508,40 @@ impl<T: Value + MemoProps + PlainData + 'static> Component for ToolRail<'_, T> {
}
}
fn finish(self, cx: Cx<'_, Self>) -> ToolRailOutput<T> {
/// While the toolbar is edited the rail takes the drops its buttons do not: a blank toolbar's, and those in the room
/// around the buttons. It registers after them, and declines over them.
fn finish(self, mut cx: Cx<'_, Self>) -> ToolRailOutput<T> {
let dropped = self.editing.then(|| self.rail_drop(cx.rect, cx.flow.is_rtl())).and_then(|target| cx.drop_target::<ToolDrag, _>(&target));
ToolRailOutput {
response: cx.response.clone(),
select: None,
double_clicked: None,
edit_toolbar: None,
flyout: None,
dropped: None,
dropped,
torn_off: None,
last_used: None,
}
}
}
impl<T: Value + MemoProps + PlainData + 'static> ToolRail<'_, T> {
/// The rail `rect` as the target of the drops around the buttons the grid showed in this pass.
fn rail_drop(&self, rect: Rect, rtl: bool) -> RailDrop {
let vertical = self.columns == 1;
let slots = self
.shown
.take()
.into_iter()
.map(|(index, rect)| {
let slot = &self.slots[index];
SlotDrop { rect, slot: slot.id, index, tools: slot.tools.len(), vertical, rtl }
})
.collect();
RailDrop { rect, slots, count: self.slots.len(), beside: Cell::new(None) }
}
}
impl<T: Value + MemoProps + PlainData + 'static> Container for ToolRail<'_, T> {
/// The host's footer.
fn footer(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) {
+39
View File
@@ -4,6 +4,7 @@ use super::data::SlotId;
use crate::contract::{DropMark, DropTarget};
use craft_behavior::DropOperation;
use egui::{Pos2, Rect};
use std::cell::Cell;
/// The payload of the drag session between the Edit Toolbar drawer and the rail. Positions, not tools: each side
/// resolves them against the slots it was given.
@@ -107,6 +108,7 @@ pub fn drop_in_slot(fraction: f32, slot: SlotId, index: usize, tools: usize) ->
}
/// A slot's button as a drop target: the drop's place comes from where over the button it falls.
#[derive(Clone, Copy)]
pub(crate) struct SlotDrop {
pub rect: Rect,
pub slot: SlotId,
@@ -143,3 +145,40 @@ impl DropTarget<ToolDrag> for SlotDrop {
}
}
}
/// The rail around its slot buttons as a drop target, for a blank toolbar and the room after the last slot. A drop off
/// the buttons makes a slot of its own beside the nearest button: before it when above it, or level with it and on its
/// leading half; else after it. On a rail with no buttons it goes after the host's `count` slots.
pub(crate) struct RailDrop {
pub rect: Rect,
pub slots: Vec<SlotDrop>,
pub count: usize,
/// The button the last accepted drop goes beside, whose edge the mark lines.
pub beside: Cell<Option<SlotDrop>>,
}
impl DropTarget<ToolDrag> for RailDrop {
type Drop = ToolDropped;
/// Over a button the button's own target takes the drop.
fn accept(&self, payload: &ToolDrag, at: Pos2, _: DropOperation) -> Option<ToolDropped> {
if self.slots.iter().any(|slot| slot.rect.contains(at)) {
return None;
}
let nearest = self.slots.iter().min_by(|a, b| a.rect.distance_sq_to_pos(at).total_cmp(&b.rect.distance_sq_to_pos(at))).copied();
self.beside.set(nearest);
let before = match nearest {
Some(slot) => {
let leading = if slot.rtl { at.x > slot.rect.center().x } else { at.x < slot.rect.center().x };
let before = at.y < slot.rect.top() || (at.y <= slot.rect.bottom() && leading);
slot.index + usize::from(!before)
}
None => self.count,
};
Some(ToolDropped { drag: *payload, at: DropAt::new_slot(before) })
}
fn mark(&self, drop: &ToolDropped) -> DropMark {
self.beside.get().map_or(DropMark::Into(self.rect), |slot| slot.mark(drop))
}
}
+25 -1
View File
@@ -4,7 +4,7 @@
use super::super::FlyoutButton;
use super::stories::tools;
use super::{LastUsed, ToolRail, ToolSlot};
use super::{DropAt, LastUsed, ToolRail, ToolSlot};
use crate::buttons::Button;
use crate::contract::Props as _;
use crate::contract::Show as _;
@@ -297,6 +297,30 @@ fn a_click_on_a_slot_selects_its_tool_once() {
assert_eq!(seen.borrow().selected, [1], "the click selected the brush once");
}
/// While the toolbar is edited a drop off the buttons lands on the rail: on a blank toolbar as its first slot, and under
/// the last button after the last slot.
#[trial]
fn an_edited_rail_takes_a_drop_off_its_buttons_beside_the_nearest_one() {
let dropped = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&dropped);
let (slots, blank, last) = (Tracked::new(slots()), Tracked::new(Vec::new()), Tracked::new(LastUsed::default()));
let mut fixture = Fixture::new(move |ui| {
Stack::new().show(ui, |ui, _| {
for (label, slots, edit) in [("Tools", &slots, "Edit Tools"), ("Blank", &blank, "Edit Blank")] {
let out = ToolRail::new(label, slots, &0, &last).edit_toolbar(edit).editing().show_column(ui, |_, _| {});
seen.borrow_mut().extend(out.dropped.map(|drop| (label, drop.at)));
}
});
});
fixture.room(Vec2::new(200.0, 800.0)).settle();
let pencil = rect(&fixture, "Pencil").center();
fixture.drag_at(pencil, rect(&fixture, "Blank").center() - pencil).settle();
assert_eq!(dropped.borrow().as_slice(), [("Blank", DropAt::new_slot(0))], "a drop on a blank toolbar makes its first slot");
dropped.borrow_mut().clear();
fixture.drag_at(pencil, rect(&fixture, "Edit Tools").center() - pencil).settle();
assert_eq!(dropped.borrow().as_slice(), [("Tools", DropAt::new_slot(LABELS.len()))], "under the last button it goes after the last slot");
}
fn near(a: f32, b: f32) -> bool {
(a - b).abs() < 1.0
}
+1 -1
View File
@@ -130,7 +130,7 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> {
/// The panel whose frame shows alone.
#[prop]
maximized: Option<P>,
/// Auto-Collapse Iconic Panels: a flyout closes when the focus leaves it.
/// Auto-Collapse Iconic Panels: a flyout closes on a press outside it and when the focus leaves it.
#[prop(flag)]
auto_collapse: bool,
/// The workspace is locked: nothing moves, floats or closes.
+24 -18
View File
@@ -266,6 +266,8 @@ struct NativeDock {
palette: Option<ViewportId>,
/// The tree the palette window's pass produced in the last frame.
palette_tree: Option<AccessTree>,
/// Whether Auto-Collapse Iconic Panels is on in the frames of a collapsed palette.
auto_collapse: bool,
}
impl NativeDock {
@@ -287,7 +289,7 @@ impl NativeDock {
windows.child_info(info(true, FLOAT_AT));
let workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![2], 0)), vec![palette])));
let specs = Tracked::new(Specs { rights: Permissions::ALL, least: false, stepped });
let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None, palette: None, palette_tree: None };
let mut dock = NativeDock { windows, workspace, stepped, specs, builder: None, palette: None, palette_tree: None, auto_collapse: false };
for _ in 0..3 {
dock.frame(vec![]);
}
@@ -1034,10 +1036,10 @@ fn collapsed_palette() -> (NativeDock, Rect) {
/// One frame of `dock` with `panels`, `root` events for the main window and `child` events for the palette's window,
/// whose OS window follows its commands at `at`: the frame's output.
fn collapsed_frame(dock: &mut NativeDock, panels: &mut dyn DockPanels<u32>, at: &mut Rect, root: Vec<Event>, child: Vec<Event>) -> Out {
let workspace = &mut dock.workspace;
let specs = &dock.specs;
let (workspace, specs, auto_collapse) = (&mut dock.workspace, &dock.specs, dock.auto_collapse);
let out = dock.windows.frame(root, child, |ui| {
let _ = DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default()).show(ui);
let area = DockArea::new("Native dock", Bind::bound(workspace), specs, &mut *panels, DockConfig::default());
let _ = if auto_collapse { area.auto_collapse() } else { area }.show(ui);
});
let palette = dock.palette;
let commands: Vec<ViewportCommand> =
@@ -1222,22 +1224,26 @@ fn a_tooltip_from_a_native_palette_opens_in_a_popup_os_window() {
assert!(rect.width() > at.width() && rect.height() < rect.width(), "the tooltip's text runs on one line, wider than the strip: {rect:?}");
}
/// A press in the main window closes the flyout a collapsed native palette opened in a popup window.
/// With Auto-Collapse Iconic Panels on, a press in the main window closes the flyout a collapsed native palette opened
/// in a popup window; with it off the flyout stays open.
#[trial]
fn a_press_in_the_main_window_closes_a_native_palettes_flyout() {
let (mut dock, mut at) = collapsed_palette();
let mut probe = BodyProbe::default();
let popup = open_flyout(&mut dock, &mut probe, &mut at);
let over = OVER_GROUP - MAIN_AT.min.to_vec2();
for root in [vec![moved(over)], vec![press(over)], vec![release(over)]] {
collapsed_frame(&mut dock, &mut probe, &mut at, root, vec![]);
fn a_press_in_the_main_window_closes_a_native_palettes_flyout_with_auto_collapse() {
for auto_collapse in [true, false] {
let (mut dock, mut at) = collapsed_palette();
dock.auto_collapse = auto_collapse;
let mut probe = BodyProbe::default();
let popup = open_flyout(&mut dock, &mut probe, &mut at);
let over = OVER_GROUP - MAIN_AT.min.to_vec2();
for root in [vec![moved(over)], vec![press(over)], vec![release(over)]] {
collapsed_frame(&mut dock, &mut probe, &mut at, root, vec![]);
}
// The flyout fades out, then its window closes.
let closed = (0..60).any(|_| {
let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]);
!popups(&dock, &out).contains(&popup)
});
assert_eq!(closed, auto_collapse, "auto-collapse {auto_collapse}: the flyout's window closed only with it on");
}
// The flyout fades out, then its window closes.
let closed = (0..60).any(|_| {
let out = collapsed_frame(&mut dock, &mut probe, &mut at, vec![], vec![]);
!popups(&dock, &out).contains(&popup)
});
assert!(closed, "the flyout's window closed");
}
/// Palettes no smaller than `PALETTE_LEAST`.
+29 -5
View File
@@ -6,6 +6,7 @@ use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, PopupKi
use crate::controls::disclosure::DisclosureGlyph;
use crate::primitives::{IconSpec, PaintShape, StrokeWidth};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook};
use craft_behavior::{Metrics, Sense};
use craft_i18n::Direction;
@@ -65,7 +66,9 @@ pub enum PopupMark {
/// A square button showing only an icon. Its label is its accessible name; a tooltip is the caller's. A selected
/// button (`selected(true)`) shows the on look: the host owns the state and a click is reported in the response.
/// [`ButtonOutput::held`] reports the press from its start to its end.
/// [`ButtonOutput::held`] reports the press from its start to its end. A button whose menu picks one of its rows (an
/// Align To button) gives the picked row as its [`choice`](Self::choice): it then reads as a combo box named by its
/// label, with the choice as its value.
#[derive(crate::contract::Component, crate::contract::Props)]
pub struct IconButton<'a> {
#[common]
@@ -82,15 +85,27 @@ pub struct IconButton<'a> {
/// that opens a menu have one.
#[prop]
popup_mark: PopupMark,
/// Whether the popup the button opens is open, as the host knows it.
/// Whether the popup the button opens is open, as the host knows it. A button with a [`choice`](Self::choice)
/// reports, without it, whether the container hung from it is open.
#[prop(into)]
expanded: Option<bool>,
/// The row the menu it opens has picked, for a button that picks one of its menu's rows.
#[prop(into)]
choice: Option<Label>,
}
impl<'a> IconButton<'a> {
/// An icon button showing `icon`; `label` it with the accessible name.
pub fn new(icon: impl Into<IconSpec<'a>>) -> Self {
IconButton { common: Common::new(), icon: icon.into(), focusable: true, popup: None, popup_mark: PopupMark::None, expanded: None }
IconButton {
common: Common::new(),
icon: icon.into(),
focusable: true,
popup: None,
popup_mark: PopupMark::None,
expanded: None,
choice: None,
}
}
/// An icon button bound to `command`: its label, enabled state and activation follow the command.
@@ -101,6 +116,7 @@ impl<'a> IconButton<'a> {
impl Component for IconButton<'_> {
const ROLE: Role = Role::BUTTON;
const ALT_ROLES: &'static [Role] = &[Role::COMBO_BOX];
const PARTS: bool = false;
const SHOWS_LABEL: bool = false;
const OVERLAYS: bool = false;
@@ -176,15 +192,23 @@ impl Component for IconButton<'_> {
}
}
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
if let Some(kind) = self.popup {
access.has_popup(kind);
}
if let Some(open) = self.expanded {
if self.choice.is_some() {
access.role(Role::COMBO_BOX);
}
let shown = || self.choice.is_some().then(|| crate::contract::overlay::opened_from(&cx.ctx, cx.response.id));
if let Some(open) = self.expanded.or_else(shown) {
access.expanded(open);
}
}
fn value_text(&self, cx: &Cx<'_, Self>) -> Option<String> {
self.choice.as_ref().map(|choice| cx.env.resolve(choice).as_str().to_owned())
}
fn finish(self, cx: Cx<'_, Self>) -> ButtonOutput {
ButtonOutput::of(&cx, self.activated(&cx))
}
+25 -3
View File
@@ -1,11 +1,11 @@
//! Stories of the buttons.
use super::{Arrangement, Button, ButtonChord, ControlPlace, GroupLevel, IconButton, Link, SplitButton, SplitMenu, ToggleButton};
use crate::contract::{BodyCx, Entry, LeastWidth, Props as _, Show as _, ShowContainer as _, Sizing, Validity};
use super::{Arrangement, Button, ButtonChord, ControlPlace, GroupLevel, IconButton, Link, PopupMark, SplitButton, SplitMenu, ToggleButton};
use crate::contract::{BodyCx, Entry, LeastWidth, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, Validity};
use crate::display::{Picture, Shade, Text};
use crate::layout_components::{Grid, Row, Stack};
use crate::list::ThumbAspect;
use crate::menu::MenuItem;
use crate::menu::{Menu, MenuItem};
use crate::primitives::{AppIcons, HAlign, IconMark, IconSpec, register_app_icons};
use crate::runtime::commands::EditCommands;
use crate::runtime::env::{Message, with_env};
@@ -79,6 +79,28 @@ fn icon_button(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
IconButton::new(IconId::new("settings")).label("Settings").show(ui).into()
}
/// A menu button that picks one of its menu's rows, as an Align To button does: it reads as a combo box named by its
/// label, with the picked row as its value, and the picked row carries the check mark.
#[story(IconButton<'static>, covers = [], title = "Choice")]
fn icon_button_choice(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
const CHOICES: [&str; 3] = ["Align to Selection", "Align to Key Object", "Align to Artboard"];
let picked = *data.value("picked", 0_usize);
let button = IconButton::new(IconId::new("align_edge_left"))
.label("Align To")
.popup(PopupKind::Menu)
.popup_mark(PopupMark::Menu)
.choice(CHOICES[picked])
.show(ui);
Menu::new("Align To").opened_by(&button.response, Trigger::Press).show(ui, |ui, _| {
for (at, choice) in CHOICES.into_iter().enumerate() {
if MenuItem::new(choice).check(at == picked).id_salt(at).show(ui).ran {
*data.value("picked", 0_usize) = at;
}
}
});
button.into()
}
/// A tool strip: the first tool selected, as the gallery card shows it.
#[story(IconButton<'static>, covers = [], drive = Drive::Never)]
fn icon_button_selected(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+26 -1
View File
@@ -8,9 +8,10 @@ use craft_theme::ControlSize;
use craft_theme::Variant;
use craft_ui::buttons::{Arrangement, Button, ButtonChord, ControlPlace, GroupLevel, IconButton, SplitButton, SplitMenu, ToggleButton};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Role, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, CommandSet, Entry, Hover, PopupKind, Props as _, Role, Show as _, ShowContainer as _, Trigger};
use craft_ui::display::Picture;
use craft_ui::list::ThumbAspect;
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::pickers::ComboBox;
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandRef, CommandState, Scope};
@@ -816,3 +817,27 @@ fn an_icon_only_toggle_in_a_field_without_label_text_keeps_its_name() {
let toggle = fixture.by_label("Convert Cyan to process").expect("the toggle keeps its name");
assert!(fixture.by_role(Role::BUTTON).iter().any(|button| button.node == toggle.node), "the named node is the toggle button");
}
/// A menu button given the row its menu picked reads as a combo box named by its label, with that row as its value; a
/// menu button without one stays a button with no value.
#[trial]
fn a_menu_button_with_a_choice_reads_as_a_combo_box_valued_by_it() {
let mut fixture = Fixture::new(|ui| {
let align = IconButton::new(IconId::new("align_edge_left")).label("Align To").popup(PopupKind::Menu).choice("Align to Artboard").show(ui);
Menu::new("Align To").opened_by(&align.response, Trigger::Press).show(ui, |ui, _| {
MenuItem::new("Align to Artboard").check(true).show(ui);
});
IconButton::new(IconId::new("more")).label("More").popup(PopupKind::Menu).show(ui);
});
fixture.settle();
let align = fixture.by_label("Align To").expect("the choice button is in the access tree");
let more = fixture.by_label("More").expect("the plain menu button is in the access tree");
let tree = fixture.tree();
assert_eq!(tree.role_of(align.node), Some(Role::COMBO_BOX), "a button with a choice is a combo box");
assert_eq!(tree.value_of(align.node), Some("Align to Artboard"), "its value is the choice");
assert_eq!(tree.expanded_of(align.node), Some(false), "its menu is closed");
assert_eq!(tree.role_of(more.node), Some(Role::BUTTON), "a menu button without a choice stays a button");
assert_eq!(tree.value_of(more.node), None, "and has no value");
fixture.click_at(align.center()).settle();
assert_eq!(fixture.tree().expanded_of(align.node), Some(true), "it reports its menu open");
}
+12
View File
@@ -67,3 +67,15 @@ fn a_link_label_reports_its_click_to_the_host_and_still_scrubs() {
fixture.drag_at(link.label_at(), Vec2::new(DRAG, 0.0));
assert!(link.value.get() > START, "a drag on a link label scrubs: {}", link.value.get());
}
/// `Fixture::by_label` gives the control a link label names, not the link that carries the same name.
#[trial]
fn by_label_gives_the_control_a_link_label_names() {
let row = Row::new();
let shown = row.clone();
let mut fixture = Fixture::new(move |ui| shown.show(ui, "link", SideLabel::new().link(), ROW_A));
fixture.settle();
let dial = row.seen.borrow().id.expect("the dial ran");
let control = fixture.node_of(dial).expect("the dial is in the access tree").node;
assert_eq!(fixture.by_label("Opacity").map(|found| found.node), Some(control), "the label's name finds its control");
}