From 7102556d5ccb433534714a18e17e8ecc2bc3cf32 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 15:46:44 +0100 Subject: [PATCH 01/27] ui-contract press winners: a window's move band takes no drag from under a control over it, so a press-drag on a title bar's Home, menu title or caption button no longer moves the window and a double click on it no longer maximizes it; the free band still moves and zooms the window. Title bar trial under a press on a control over the band --- crates/ui-contract/src/runtime/pointer.rs | 14 +++-- crates/ui-shell/tests/it/shell/title_bar.rs | 66 +++++++++++++++++++++ 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 5c3f115005..b87caa5713 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -846,8 +846,9 @@ pub(crate) fn made_by_component(ctx: &Context, viewport: ViewportId, id: Id) -> /// their winning shapes' place in the pass's paint order, top first. The top one takes every kind of press its shape /// senses. Under a top shape that only drags (a window's resize grip), the click goes to the first root below whose /// shape clicks; under one that only clicks (a button), the drag goes to the first root below whose shape drags, when -/// that root takes no click anywhere. Under a top shape that clicks and passes its drag (`Sense::PASSES_DRAG`), the -/// drag goes to the next shape under it that drags: its own root's, else the first root's below. +/// that root takes no click anywhere and that shape is no move band (`MOVE_BAND`). Under a top shape that clicks and +/// passes its drag (`Sense::PASSES_DRAG`), the drag goes to the next shape under it that drags: its own root's, else the +/// first root's below. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(crate) struct PressWinners { pub click: Option<(Winner, Id)>, @@ -1123,12 +1124,15 @@ fn winners_of(mut ranked: Vec) -> PressWinners { } } // Under a top shape that only clicks, the first root below whose shape drags takes the drag, unless the - // root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it. Under a top - // shape that passes its drag, the next shape that drags takes it, in the same root or one below. + // root takes clicks anywhere: a drag-only root (a scroll view) is dragged from a button in it. A move band + // is not: a press on a control over the band (a title bar's Home, a menu title, a caption button) never + // moves the window, and its double click never zooms it. Under a top shape that passes its drag, the next + // shape that drags takes it, in the same root or one below, a move band too. (true, false) => { let passes = winners.click.is_some_and(|(top, _)| top.sense.contains(craft_behavior::Sense::PASSES_DRAG)); let root_target = winners.click.is_some_and(|(top, owner)| top.drag_to_root && root != owner); - if drags && !root_target && (passes || !(clicks || root_clicks)) { + let band = winner.part.is_some_and(|part| part.key == crate::contract::MOVE_BAND); + if drags && !root_target && (passes || !(clicks || root_clicks || band)) { winners.drag = Some((winner, root)); } break; diff --git a/crates/ui-shell/tests/it/shell/title_bar.rs b/crates/ui-shell/tests/it/shell/title_bar.rs index a44a27375e..b77a166ae0 100644 --- a/crates/ui-shell/tests/it/shell/title_bar.rs +++ b/crates/ui-shell/tests/it/shell/title_bar.rs @@ -94,6 +94,72 @@ fn a_title_bar_in_an_embedded_shell_acts_on_no_window() { assert!(!commands.is_empty(), "the window's bar acts on the window"); } +/// The window commands a title bar with a Home button in its leading content sends for each step list of `gestures`, +/// in order, given the Home button's centre and a free point of the band. +fn home_bar_sent(gestures: impl Fn(Pos2, Pos2) -> Vec>>) -> Vec> { + use craft_ui::buttons::Button; + use craft_ui::contract::Show as _; + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout }); + let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None }; + let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).frame(Decision { frame, overridden: None, desktop })); + let bar = Cell::new(Rect::NOTHING); + let frame = |events: Vec| { + windows.frame(events, vec![], |ui| { + let shown = TitleBar::new().show_titled( + ui, + Title::new("Landscape.psd"), + |ui, _| { + Button::new("Home").show(ui); + }, + |_, _| {}, + ); + bar.set(shown.response.rect); + }) + }; + frame(vec![]); + let settled = frame(vec![]); + let tree = &settled.trees.iter().rev().find(|(viewport, _)| *viewport == ViewportId::ROOT).expect("the root pass ran").1; + let home = tree + .with_role(Role::BUTTON) + .into_iter() + .find(|key| tree.name_of(*key) == Some("Home")) + .and_then(|key| tree.bounds_of(key)) + .expect("the bar shows its Home button") + .center(); + // The title is no control: the band lies under it. + let band = bar.get().center(); + gestures(home, band) + .into_iter() + .map(|steps| { + steps + .into_iter() + .flat_map(|events| frame(events).commands) + .map(|(_, command)| command) + .filter(|command| matches!(command, ViewportCommand::StartDrag | ViewportCommand::Maximized(_) | ViewportCommand::OuterPosition(_))) + .collect() + }) + .collect() +} + +/// A press on a control over the band is the control's: a press-drag that starts on the bar's Home button neither +/// moves the window nor drags, and a double click on it does not maximize the window. The band used to take the drag +/// under the button, as a drag-only root under a button in it does, so the drag moved the window and the double click +/// zoomed it. The free band still moves the window, and its double click still maximizes it. +#[trial] +fn a_press_on_a_control_over_the_band_never_moves_or_zooms_the_window() { + let sent = home_bar_sent(|home, band| { + let drag = |at: Pos2| vec![vec![moved(at)], vec![press(at)], vec![moved(at + vec2(40.0, 0.0))], vec![release(at + vec2(40.0, 0.0))], vec![]]; + let double = |at: Pos2| vec![vec![moved(at)], vec![press(at)], vec![release(at)], vec![press(at)], vec![release(at)], vec![]]; + vec![drag(home), double(home), drag(band), double(band)] + }); + let [home_drag, home_double, band_drag, band_double] = &sent[..] else { panic!("four gestures ran: {sent:?}") }; + assert!(home_drag.is_empty(), "a drag from Home does not move the window: {home_drag:?}"); + assert!(home_double.is_empty(), "a double click on Home does not maximize the window: {home_double:?}"); + assert!(band_drag.contains(&ViewportCommand::StartDrag), "a drag of the free band moves the window: {band_drag:?}"); + assert!(band_double.contains(&ViewportCommand::Maximized(true)), "a double click on the free band maximizes the window: {band_double:?}"); +} + /// The shell sends the window title once after a change and not again while the viewport reports it; an embedded shell /// sends none. #[trial] From 0be3d77cdfa819ff6b3a240ed43a6d2a9ee93eb6 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 16:47:26 +0100 Subject: [PATCH 02/27] ui-panels docking: a panel's flyout can be as tall as its body (PanelSpec::flyout_height) An iconic column's flyout took at least the DockHeights default of each of its group's panels, so a panel given a tall docked height also opened a tall flyout over a short body. FlyoutHeight::Docked, the default, keeps that; FlyoutHeight::Content opens the flyout as tall as its body measures, while the panel's DockHeights still size its group docked in a column. Trial a_content_tall_flyout_ignores_the_docked_height_that_its_docked_group_keeps. --- crates/ui-panels/src/docking/iconic.rs | 19 +++-- crates/ui-panels/src/docking/iconic/trials.rs | 78 ++++++++++++++++++- crates/ui-panels/src/docking/mod.rs | 2 +- crates/ui-panels/src/docking/spec.rs | 28 ++++++- docs/ui-docking.md | 3 +- 5 files changed, 117 insertions(+), 13 deletions(-) diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 42e0c7f4d2..a476b960aa 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -6,7 +6,7 @@ use super::dock_column::{ register_edges, show_bar, }; use super::group::GripMarks; -use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag}; +use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, FlyoutHeight, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag}; use crate::buttons::IconButton; use crate::contract::overlay::Anchor; use crate::contract::{ @@ -181,10 +181,12 @@ pub struct IconicColumnStyle { /// column registers its drop spots with the dock `dock` as an expanded column does: its edges, the seams between its /// icon groups, the top and bottom of the stack and each icon group's cells, which join its tabs. The flyout shows /// its group through the `view` of [`show_flyouts`](IconicColumn::show_flyouts), with the opened panel active, as tall as the view measures the -/// group within the room and at least the height of its panels' default heights; a group the user sized keeps that -/// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`. -/// The user resizes it by its top and bottom edges and the edge away from the column; each step comes back in -/// [`IconicColumnOutput::flyout`], which the host keeps in the group (`flyout_width`, `height`, `flyout_offset`). +/// group within the room and at least the default height ([`DockHeights`](super::DockHeights)) of each of its panels +/// whose [`FlyoutHeight`] is `Docked`, the default: a panel whose flyout is `Content` tall leaves its docked heights to +/// its group docked in a column. A group the user sized keeps that size. The flyout's top is level with its group's +/// icons, shifted by the group's `flyout_offset`, inside `within`. The user resizes it by its top and bottom edges and +/// the edge away from the column; each step comes back in [`IconicColumnOutput::flyout`], which the host keeps in the +/// group (`flyout_width`, `height`, `flyout_offset`). /// /// In a floating window ([`ColumnBar::Window`]) the window's title row is the column's bar and the window's sides set /// its width: the column shows its icons under it, with no divider on its inner edge, and registers no edge bands. @@ -418,12 +420,15 @@ impl<'a, P: Value + Hash + Debug + 'static> IconicColumn<'a, P> { Plan { bar, cells, names, grips, groups, body } } - /// The height of the flyout of `group`: the group's own height, else what its panels ask for, else the least. + /// The height of the flyout of `group`: the group's own height, else the docked default heights of its panels + /// whose flyout takes them ([`FlyoutHeight::Docked`]), else the least. fn flyout_height(&self, group: &Group

, sizes: &DockSizes) -> f32 { let content = group .panels .iter() - .filter_map(|panel| (self.spec)(panel).heights.filter(|heights| heights.valid())) + .map(|panel| (self.spec)(panel)) + .filter(|spec| spec.flyout_height == FlyoutHeight::Docked) + .filter_map(|spec| spec.heights.filter(|heights| heights.valid())) .map(|heights| heights.default + sizes.strip) .fold(sizes.strip + sizes.least, f32::max); group.height.filter(|height| height.is_finite() && *height > 0.0).unwrap_or(content).max(sizes.strip + sizes.least) diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index 1b1f02a339..18cec2e784 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -1,5 +1,5 @@ //! Trials of `IconicColumn`: the letter of a panel without an icon, the names a wide column shows, the grips of its -//! groups, the resizes of its flyouts, and a flyout that a command leaves open. +//! groups, the heights and resizes of its flyouts, and a flyout that a command leaves open. #![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] use super::GRIP; @@ -8,7 +8,8 @@ use crate::contract::overlay::{self, OpenFilter}; use crate::contract::{Bind, Show as _, ShowContainer as _}; use crate::docking::group::GRIP_ABOVE; use crate::docking::{ - DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutResize, GroupAt, GroupDrag, GroupGrip, IconicColumn, PanelKey, PanelSpec, + DockColumn, DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutHeight, FlyoutResize, GroupAt, GroupDrag, GroupGrip, IconicColumn, + PanelKey, PanelSpec, }; use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, Scope}; use crate::runtime::drag; @@ -420,6 +421,79 @@ fn a_flyout_with_an_offset_in_a_short_viewport_stays_inside_and_resizes_its_widt } } +/// The body height a panel asks for docked in a column, well above what its one-line body measures. +const DOCKED: f32 = 260.0; + +/// A panel with a one-line body that asks for [`DOCKED`] in a dock column, its flyout `height` tall; the other panel +/// asks for no height. +fn docked_tall(height: FlyoutHeight) -> impl Fn(&u8) -> PanelSpec { + move |panel| match panel { + 0 => PanelSpec::new("Swatches").heights(DockHeights::new(DOCKED)).flyout_height(height), + _ => PanelSpec::new("Brushes"), + } +} + +/// What a group with a one-line body measures in the trials: its strip, the body's padding and a line, four strips. +fn one_line(sizes: &DockSizes) -> f32 { + sizes.strip * 4.0 +} + +/// The height of the flyout of the [`docked_tall`] panel at `height`, whose group measures [`one_line`], and the dock +/// sizes it showed in. +fn flyout_height_of(height: FlyoutHeight) -> (f32, DockSizes) { + let shown = Rc::new(Cell::new(None)); + let (seen, open) = (Rc::clone(&shown), Cell::new(None)); + let spec = docked_tall(height); + let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)); + let mut fixture = Fixture::new(move |ui| { + let column = Column::new(vec![Group::new(vec![0], 0)]); + let measured = one_line(&StyleCx::with_root(ui.ctx(), DockSizes::style)); + let mut now = open.get(); + IconicColumn::new("Panels", global("iconic column", "flyout height"), &column, Bind::bound(&mut now), &spec) + .within(screen()) + .show_flyouts_at(ui, place, |_, at, _, _| match at { + GroupAt::Measure(_) => Some(measured), + GroupAt::Show(rect) => { + seen.set(Some(rect)); + None + } + }); + open.set(now); + }); + fixture.room(SCREEN).settle(); + let icon = fixture.by_label("Swatches").expect("the Swatches icon").rect.center(); + fixture.click_at(icon).settle(); + (shown.get().expect("the flyout is open").height(), StyleCx::with_root(fixture.ctx(), DockSizes::style)) +} + +/// A panel that asks for a tall docked height opens a flyout at least that tall by default; with +/// `FlyoutHeight::Content` its flyout is as tall as its one-line body measures, while docked in a column its group +/// keeps the docked height. +#[trial] +fn a_content_tall_flyout_ignores_the_docked_height_that_its_docked_group_keeps() { + let (by_default, sizes) = flyout_height_of(FlyoutHeight::Docked); + let (docked, measured) = (DOCKED + sizes.strip, one_line(&sizes)); + assert!(measured < docked && measured > sizes.strip + sizes.least, "the body measures between the least and the docked height"); + assert!(near(by_default, docked), "by default the flyout takes the docked height: {by_default} for {docked}"); + let (content, _) = flyout_height_of(FlyoutHeight::Content); + assert!(near(content, measured), "a content-tall flyout is as tall as its body measures: {content} for {measured}"); + + let rects = Rc::new(RefCell::new(Vec::new())); + let seen = Rc::clone(&rects); + let spec = docked_tall(FlyoutHeight::Content); + let mut fixture = Fixture::new(move |ui| { + let column = Column::new(vec![Group::new(vec![0], 0), Group::new(vec![1], 0)]); + let mut shown = Vec::new(); + DockColumn::new("Panels", global("dock column", "flyout height"), &column, &spec).show_groups(ui, |group, rect, _, _| { + shown.push((group.panels.first().copied(), rect)); + }); + *seen.borrow_mut() = shown; + }); + fixture.room(SCREEN).settle(); + let group = rects.borrow().iter().find(|(panel, _)| *panel == Some(0)).map(|(_, rect)| *rect).expect("the docked group shows"); + assert!(near(group.height(), docked), "docked in a column the group keeps its docked height: {group:?} for {docked}"); +} + /// Each icon group's grip strip has its own room at the group's top: across the group, below the bar or the group /// before it and above the group's first icon, overlapping no icon. A drag that starts on a grip moves its whole /// group, as a drag on an icon moves its panel. diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 37ceceb30e..5689a56718 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -43,7 +43,7 @@ pub use panels::{DockPanels, PanelSpecs, SpecSource, request_actions}; pub use panels::{close_requests, open_requests}; pub use placed::{Placing, placed_rect, with_area_rules}; pub use root::{DockRoot, DockRootOutput, DockRootStyle}; -pub use spec::{DockGrid, DockHeights, PanelSpec}; +pub use spec::{DockGrid, DockHeights, FlyoutHeight, PanelSpec}; pub use splitter::{Splitter, SplitterStyle}; pub use targets::{DockSizes, DockSpot, DockTargets, GroupDrag, ZoneRule}; pub use words::DockWords; diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index 2fed17f8f8..d90b7a58fb 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -51,6 +51,19 @@ impl DockHeights { } } +/// How tall the flyout of a panel in a column collapsed to icons opens while the user has not resized its group. Either +/// way the flyout is at least as tall as its body measures, within the room below its top. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum FlyoutHeight { + /// At least the panel's [`DockHeights::default`], the height its group takes docked in a column. + #[default] + Docked, + /// As tall as the body measures, at least the dock's least group height: the panel's [`DockHeights`] size its + /// group docked in a column only. + Content, +} + /// How a panel that lays its content in a grid of equal columns (a toolbar) sizes its dock column. The column is a /// whole number of content columns wide, its steps ([`Column::steps`](craft_behavior::dock::Column::steps)), and as /// tall as the content measures at that width: docked from the top of the dock, floating under the title row. A drag @@ -162,9 +175,12 @@ pub struct PanelSpec { pub icon: Option>, /// Body size limits. pub limits: SizeLimits, - /// How the panel's group sizes itself in a dock column until the user resizes it. `None` shares the column's - /// free height with the column's last open group, which fills it, and with the other groups that have none. + /// How the panel's group sizes itself in a dock column until the user resizes it, and under + /// [`FlyoutHeight::Docked`] the least height of its flyout. `None` shares the column's free height with the + /// column's last open group, which fills it, and with the other groups that have none. pub heights: Option, + /// How tall the panel's flyout opens: at least its docked default height, or as tall as its body measures. + pub flyout_height: FlyoutHeight, /// The size the panel floats at: its width and the most height it takes. `None`: the size of the group it floats /// out of, else `FloatSpace`'s default size. pub float_size: Option, @@ -201,6 +217,7 @@ impl PanelSpec { icon: None, limits: SizeLimits::default(), heights: None, + flyout_height: FlyoutHeight::Docked, float_size: None, allow_native: true, window_kind: WindowKind::Tool, @@ -262,6 +279,13 @@ impl PanelSpec { self } + /// How tall the panel's flyout opens. + #[must_use] + pub fn flyout_height(mut self, height: FlyoutHeight) -> Self { + self.flyout_height = height; + self + } + /// The size the panel floats at. #[must_use] pub fn float_size(mut self, size: Vec2) -> Self { diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 081948655d..1afbd4a8f2 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -56,7 +56,7 @@ The host keeps its panels' specs in a plain-data model that implements `PanelSpe | Method | Does | | --- | --- | -| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, float size, `allow_native`, `window_kind`, `canvas`, `grid`. | +| `spec` | The panel's `PanelSpec`: label, icon, `SizeLimits`, `DockHeights`, `FlyoutHeight`, float size, `allow_native`, `window_kind`, `canvas`, `grid`. | | `permissions` | The panel's `Permissions` (default `ALL`). | The area reads them only when the model's revision, the workspace's revision or the lock changes (`runtime::derived`), and keeps what it read otherwise, so an idle pass reads no spec. A host changes a label or a limit by editing the model. A spec reads no style: a tool rail's grid is `DockGrid::rail(cells)`, which the dock sizes from its own tokens. @@ -120,6 +120,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A drag ends without a change when another arrangement replaces the workspace it started on: it records the workspace's generation, which `Workspace::replace` and the `WorkspaceSet` switch and reset change. The dock's own edits keep the generation, so they keep the drag. Every write moves the workspace's revision (`Workspace::revision`), which keys what the area derives. - A floating window's id comes from a counter its layout owns (`Layout::fresh_window_id`). It starts above every id the layout is built or loaded with and only grows while the layout lives; `Workspace::replace` gives the incoming windows ids the replaced layout never gave out, and a dock area keeps the windows its actions add above every id it has shown, so a workspace an undo brings back draws no id twice (`Workspace::raise_window_floor`). An OS window never passes to another window. - A dock column's last open group fills the column: it takes the height the other groups leave and asks for its `DockHeights::fill`. The other groups keep the height the user gave them, or take their `DockHeights::default`, which shrinks towards `compact` before the filling group gets less than its fill. Groups that ask for no heights share the free height with the filling group. +- A flyout is as tall as its group measures, within the room below its top, and at least the `DockHeights::default` of each of its panels whose `PanelSpec::flyout_height` is `FlyoutHeight::Docked`, the default. A panel with `FlyoutHeight::Content` opens a flyout as tall as its body measures, while its `DockHeights` still size its group docked in a column. A group the user sized keeps that height. - Split handles are Tab stops, and the arrow keys move them. A divider drag is one gesture in `DockAreaOutput::edit`. - A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s. From d468b0f790e8d366583a6875b5412e7ce19e0b8a Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 16:51:32 +0100 Subject: [PATCH 03/27] tabs: panel tabs can shrink to a readable prefix ending in an ellipsis Panel tabs shrink to their title's first three letters and clip the label at the tab's edge, so a narrow dock column reads "Colo", "Swa", "Gra". Add PanelTabShrink, a strip's choice (TabStrip::panel_shrink) that a dock makes for its groups (DockConfig::tab_shrink). Under PanelTabShrink::Ellipsis a panel tab shrinks no further than its label's readable least (TextRun::READABLE_CHARACTERS and an ellipsis), a cut label ends in an ellipsis, and the tabs that do not fit at that width go to the strip's overflow menu. The default, FirstLetters, keeps today's behaviour. Trial: panel_tabs_shrinking_to_an_ellipsis_keep_a_readable_prefix_and_overflow_the_rest. --- crates/ui-panels/src/docking/config.rs | 14 ++- crates/ui-panels/src/docking/group.rs | 9 +- crates/ui-patterns/src/patterns/dock/area.rs | 1 + crates/ui-widgets/src/tabs/mod.rs | 2 +- crates/ui-widgets/src/tabs/rules.rs | 22 +++++ crates/ui-widgets/src/tabs/strip.rs | 16 ++-- crates/ui-widgets/src/tabs/tab.rs | 26 ++++-- crates/ui-widgets/tests/it/tabs.rs | 92 +++++++++++++++++++- docs/ui-docking.md | 1 + 9 files changed, 168 insertions(+), 15 deletions(-) diff --git a/crates/ui-panels/src/docking/config.rs b/crates/ui-panels/src/docking/config.rs index d3b885867a..f43f20d895 100644 --- a/crates/ui-panels/src/docking/config.rs +++ b/crates/ui-panels/src/docking/config.rs @@ -3,7 +3,7 @@ use super::IconicMode; use super::targets::ZoneRule; -use crate::tabs::PanelTabLook; +use crate::tabs::{PanelTabLook, PanelTabShrink}; use craft_behavior::{DockSide, IconId}; /// A set of the sides of the layout's outer edge or of a group. @@ -101,6 +101,10 @@ pub struct DockConfig { /// The look of the groups' panel tabs: the shown tab on the panel surface ([`PanelTabLook::Plain`]), or on a /// filled rounded pill ([`PanelTabLook::Pill`]). pub tab_look: PanelTabLook, + /// How far the groups' panel tabs shrink before they overflow: to their first letters, clipped + /// ([`PanelTabShrink::FirstLetters`]), or to a readable prefix ending in "…" ([`PanelTabShrink::Ellipsis`]), the + /// tabs that do not fit at that width going to the strip's overflow menu. + pub tab_shrink: PanelTabShrink, /// A floating window opens in an OS window of its own where the window host opens OS windows and reports where /// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and /// with this off, it shows in the app window. @@ -136,6 +140,7 @@ impl Default for DockConfig { titled_headers: false, wheel_selects_tabs: false, tab_look: PanelTabLook::Plain, + tab_shrink: PanelTabShrink::FirstLetters, native_windows: true, group_order_items: false, panel_menu_always: false, @@ -265,6 +270,13 @@ impl DockConfig { self } + /// How far the groups' panel tabs shrink ([`tab_shrink`](Self::tab_shrink)). + #[must_use] + pub fn tab_shrink(mut self, shrink: PanelTabShrink) -> Self { + self.tab_shrink = shrink; + self + } + /// Close buttons on tabs on or off. #[must_use] pub fn tab_close_buttons(mut self, on: bool) -> Self { diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 16184feac5..d6eda81619 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -21,7 +21,7 @@ use crate::runtime::focus::{self, FocusTarget}; use crate::runtime::memory::sub; use crate::sections::FooterBar; use crate::style::{ComponentStyle, Corners, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind, TypeRole}; -use crate::tabs::{PanelTabLook, Tab, TabKind, TabStrip, TornOff}; +use crate::tabs::{PanelTabLook, PanelTabShrink, Tab, TabKind, TabStrip, TornOff}; use craft_behavior::{CursorIcon, CursorPriority, DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; use craft_theme::{ControlSize, GripMark, GripShape, Tokens}; use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; @@ -350,6 +350,9 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { /// The look of the tabs ([`DockConfig::tab_look`](super::DockConfig::tab_look)). #[prop] tab_look: PanelTabLook, + /// How far the tabs shrink ([`DockConfig::tab_shrink`](super::DockConfig::tab_shrink)). + #[prop] + tab_shrink: PanelTabShrink, /// The header shows the shown panel's title (with its count) and a close button in place of the tab strip, as a /// single titled panel does: the panels are shown from a rail, not by tabs. #[prop(flag)] @@ -406,6 +409,7 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< closable: false, wheel_selects_tabs: false, tab_look: PanelTabLook::Plain, + tab_shrink: PanelTabShrink::FirstLetters, titled: false, dock: None, zones: ZoneRule::Fraction, @@ -671,6 +675,7 @@ impl Container for closable: self.closable, wheel_selects: self.wheel_selects_tabs, look: self.tab_look, + shrink: self.tab_shrink, dock: self.dock, sent: Outbox::new(&mut sent), }; @@ -746,6 +751,7 @@ struct TabRow<'a, P> { closable: bool, wheel_selects: bool, look: PanelTabLook, + shrink: PanelTabShrink, dock: Option, sent: Outbox<'a, TabEvent>, } @@ -775,6 +781,7 @@ fn tab_row(row: &mu let mut strip = TabStrip::new(name) .kind(kind) .panel_look(row.look) + .panel_shrink(row.shrink) .shown(active) .tear_off() .natural_height(true) diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index c8f50a75ab..5914a01193 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1105,6 +1105,7 @@ impl Pass<'_, P> { .panel_menu_shown(*hosted || scene.config.panel_menu_always) .panel_menu_icon(scene.config.panel_menu_icon.clone()) .tab_look(scene.config.tab_look) + .tab_shrink(scene.config.tab_shrink) .command_states(states.clone()); if look.in_window { group = group.in_window(); diff --git a/crates/ui-widgets/src/tabs/mod.rs b/crates/ui-widgets/src/tabs/mod.rs index 4e27b1c627..02f6577f9a 100644 --- a/crates/ui-widgets/src/tabs/mod.rs +++ b/crates/ui-widgets/src/tabs/mod.rs @@ -6,7 +6,7 @@ mod words; mod rules; pub(crate) mod tab; -pub use rules::{CloseSide, DocumentTabLook, FitMode, OverflowMenu, OverflowPlace, PanelTabLook, TabKind, close_side}; +pub use rules::{CloseSide, DocumentTabLook, FitMode, OverflowMenu, OverflowPlace, PanelTabLook, PanelTabShrink, TabKind, close_side}; pub use tab::{Tab, TabOutput, TabPartEvent, TabRole, TabStyle}; pub use words::TabWords; diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 19a74b5976..3ba30b32c0 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -30,6 +30,21 @@ pub enum PanelTabLook { Pill, } +/// How far panel tabs ([`TabKind::Panel`]) shrink before they overflow, and how a label too long for its tab ends: a +/// strip's choice ([`TabStrip::panel_shrink`](super::TabStrip)), which a dock makes for its groups' tabs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] +#[non_exhaustive] +pub enum PanelTabShrink { + /// Tabs shrink to their title's first letters, the label clipped at the tab's edge with no ellipsis. + #[default] + FirstLetters, + /// Tabs shrink no further than their label's readable least, its first + /// [`TextRun::READABLE_CHARACTERS`](crate::primitives::TextRun::READABLE_CHARACTERS) characters and an ellipsis (a + /// title at most one character longer stays whole), and a cut label ends in "…"; the tabs that do not fit at that + /// width go to the overflow menu. + Ellipsis, +} + /// The kind of a strip. It sets the defaults below; the host picks one per strip. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] @@ -126,6 +141,13 @@ impl TabKind { self == Self::Panel } + /// Whether a label too long for its tab is clipped at the tab's edge under the strip's `shrink`: panel tabs that + /// shrink to their first letters ([`PanelTabShrink::FirstLetters`]); under [`PanelTabShrink::Ellipsis`] they end + /// in an ellipsis as the other kinds do. + pub fn clips_label_in(self, shrink: PanelTabShrink) -> bool { + self.clips_label() && shrink == PanelTabShrink::FirstLetters + } + /// Where the overflow button sits: at the strip's end for document and text tabs, after the last tab for panel /// tabs. pub fn overflow_place(self) -> OverflowPlace { diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index da1ab7e019..75af550fd4 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -498,9 +498,10 @@ impl TabRoles<'_, K> { /// asks for the tab's context menu. /// /// The `kind` picks the rules: document and text tabs keep whole titles and send the rest to an overflow menu of -/// every tab; panel tabs shrink before they overflow and the menu lists the hidden ones. The shown tab is always -/// visible. A tab dragged out of the strip and released where no other strip, dock or drop target takes it is -/// reported as `torn_off`. +/// every tab; panel tabs shrink before they overflow and the menu lists the hidden ones. Panel tabs shrink to their +/// first letters, clipped, or with `panel_shrink(PanelTabShrink::Ellipsis)` to a readable prefix ending in "…". The +/// shown tab is always visible. A tab dragged out of the strip and released where no other strip, dock or drop target +/// takes it is reported as `torn_off`. #[derive(crate::contract::Component, crate::contract::Props)] #[component(collection, overlay, probe(TabStrip<'static, usize>))] pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> { @@ -519,6 +520,10 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + ' /// The look of a panel strip's tabs ([`TabKind::Panel`]). #[prop] panel_look: super::PanelTabLook, + /// How far a panel strip's tabs ([`TabKind::Panel`]) shrink before they overflow: to their first letters, clipped + /// (the default), or to a readable prefix ending in an ellipsis ([`PanelTabShrink::Ellipsis`](super::PanelTabShrink)). + #[prop] + panel_shrink: super::PanelTabShrink, /// The tab the host shows. A click, Space, Enter or a drop reports the new one in the output. #[prop] shown: Option, @@ -590,6 +595,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri kind: TabKind::Document, large: false, panel_look: super::PanelTabLook::Plain, + panel_shrink: super::PanelTabShrink::FirstLetters, shown: None, tear_off: false, wheel_selects: false, @@ -1027,9 +1033,9 @@ impl Collection StripLayout::new(count, Vec2::new(width, cx.tokens.size.bar.tab), tab_gap, fitting, self.report.clone(), cx.frame_ctx().clone()) } - /// Every tab takes the strip's kind, panel look and size. + /// Every tab takes the strip's kind, panel look, panel shrink and size. fn dress<'r>(&self, tab: Self::Item<'r>, _: &RowState) -> Self::Item<'r> { - let tab = tab.kind(self.kind).panel_look(self.panel_look); + let tab = tab.kind(self.kind).panel_look(self.panel_look).panel_shrink(self.panel_shrink); if self.large { tab.large() } else { tab } } diff --git a/crates/ui-widgets/src/tabs/tab.rs b/crates/ui-widgets/src/tabs/tab.rs index 7a035282f8..e82f8aded8 100644 --- a/crates/ui-widgets/src/tabs/tab.rs +++ b/crates/ui-widgets/src/tabs/tab.rs @@ -2,10 +2,11 @@ //! //! Selection, the lead, the focus ring and the drag ghost belong to the collection that shows the tab; the tab draws //! the look the item step gives it and reports what its own parts do. The strip gives the tab a rect: the tab's -//! measure is its natural width (`Proposal::Min` the room for the first letters of its title), and a narrower rect cuts the label -//! first, then the detail, and shows the whole text as a tooltip. +//! measure is its natural width (`Proposal::Min` the room for the first letters of its title, or for a panel tab under +//! `PanelTabShrink::Ellipsis` its label's readable least), and a narrower rect cuts the label first, then the detail, +//! and shows the whole text as a tooltip. -use super::rules::{CloseSide, PanelTabLook, TabKind, close_side}; +use super::rules::{CloseSide, PanelTabLook, PanelTabShrink, TabKind, close_side}; use super::words::TabWords; use std::borrow::Cow; @@ -195,6 +196,9 @@ pub struct Tab<'a> { #[style_key] #[prop] panel_look: PanelTabLook, + /// How far a panel tab ([`TabKind::Panel`]) shrinks and how its cut label ends; the other kinds have their own. + #[prop] + panel_shrink: PanelTabShrink, /// Secondary text after the label (a colour mode, a zoom). #[prop(into)] detail: Option

::register_room(ui.ctx(), dock, cell); } let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; - // Only a docked column's icons are a rail; a floating window's open flyouts. + // Only a docked column's icons are a rail; a floating window's open flyouts, which stand above its window. let mode = if in_window { IconicMode::Flyouts } else { scene.config.iconic_mode }; + let flyout_layer = if in_window { PopupLayer::AboveWindows } else { scene.config.flyout_layer }; // The width the user gives a column by its inner edge leaves out its card's inset. let inset = card.unwrap_or(0.0); let mut icons = |cell: Rect, open: Option

, card: Option| { @@ -1353,7 +1354,8 @@ impl Pass<'_, P> { .bar(bar) .within(within) .auto_collapse(scene.auto_collapse) - .mode(mode); + .mode(mode) + .flyout_layer(flyout_layer); let shown = match card { Some(inset) => shown.card(inset), None => shown, diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index 217f91ad0c..18168744b2 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -2,6 +2,8 @@ use craft_behavior::Axis; use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at}; +use craft_ui::buttons::Button; +use craft_ui::contract::overlay::PopupLayer; use craft_ui::contract::{Bind, BodyCx, PlainData, Role, Show as _, SizeLimits, Tracked}; use craft_ui::display::Text; use craft_ui::docking::{ @@ -421,6 +423,91 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses assert!(!shown(&fixture, "Alpha body"), "and its panel no longer shows"); } +/// How tall the flyout of [`UnderWindow`]'s Alpha group measures. +const FLYOUT_HEIGHT: f32 = 300.0; + +/// Panels for a docked flyout under a floating window: Alpha's group, in the flyout, is a view that measures +/// [`FLYOUT_HEIGHT`] and records the rect it shows in; Beta, in the window, shows a button that counts its clicks. +struct UnderWindow { + flyout: Rc>>, + clicks: Rc>, +} + +impl DockPanels for UnderWindow { + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + if *panel == 11 { + self.clicks.set(self.clicks.get() + Button::new("Beta button").show(ui).clicks); + } + } + + fn group_view(&mut self, panels: &[u32], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + if !panels.contains(&10) { + return None; + } + Some(match at { + GroupAt::Measure(_) => FLYOUT_HEIGHT, + GroupAt::Show(rect) => { + self.flyout.set(Some(rect)); + rect.height() + } + }) + } +} + +/// A start dock whose column, collapsed to icons, holds Alpha, beside the canvas, and a floating window holding Beta +/// at `window`. +fn flyout_dock(window: Option) -> Arc> { + let side = Column::new(vec![Group::new(vec![10], 0)]).with_iconic(true); + let root = Node::split(Axis::X, SplitSize::Ratio(0.4), Node::dock(DockEdge::Start, vec![side]), Node::tabs(vec![1], 0)); + let windows = window.map(|at| Floating::new(100, Column::new(vec![Group::new(vec![11], 0)]), at)).into_iter().collect(); + Arc::new(Workspace::new(Layout::new(Some(root), windows))) +} + +/// What shows where a floating window lies over part of Alpha's open flyout, with docked flyouts standing at `layer`: +/// whether the layer on top there is the flyout's, whether it stands above the flyout's in egui's layer order, and how +/// many clicks a click there gave the window's button. +fn flyout_under_window(layer: PopupLayer) -> (bool, bool, u32) { + let workspace = Rc::new(RefCell::new(flyout_dock(None))); + let (flyout, clicks) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(0))); + let mut panels = UnderWindow { flyout: Rc::clone(&flyout), clicks: Rc::clone(&clicks) }; + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Sides)); + let mut fixture = Fixture::new(move |ui| { + let config = DockConfig::default().native_windows(false).flyout_layer(layer); + let shown = Bind::given(Arc::clone(&held.borrow())); + DockArea::new("Flyout dock", shown, &specs, &mut panels, config).flyout(Bind::given(Some(10))).show(ui); + }); + fixture.room(Vec2::new(900.0, 600.0)).settle(); + let open = flyout.get().expect("Alpha's flyout shows its group"); + // The window covers the flyout's end two thirds from its top and reaches past its end edge. + let window = Rect::from_min_size(open.min + Vec2::new(open.width() / 3.0, 0.0), Vec2::new(open.width() + 100.0, 220.0)); + *workspace.borrow_mut() = flyout_dock(Some(window)); + fixture.settle(); + let button = fixture.by_label("Beta button").expect("the floating window shows Beta's button").center(); + assert!(open.contains(button), "the window's button lies over the flyout: {button:?} in {open:?}"); + let alone = Pos2::new(open.left() + open.width() / 6.0, open.center().y); + let ctx = fixture.ctx().clone(); + let flyout_layer = ctx.layer_id_at(alone).expect("the flyout is on top beside the window"); + let top = ctx.layer_id_at(button).expect("a layer lies under the button"); + let place = |layer: egui::LayerId| ctx.memory(|memory| memory.layer_ids().position(|listed| listed == layer)); + let above = place(top) > place(flyout_layer); + fixture.click_at(button).settle(); + (top == flyout_layer, above, clicks.get()) +} + +/// A docked column's open flyout stands above a floating window over it, as popups do: it is drawn over the window +/// and takes the press there. With `DockConfig::flyout_layer(PopupLayer::BelowWindows)` the window stays in front: its +/// layer lies above the flyout's and the press reaches its button. +#[trial] +fn a_floating_window_stays_above_a_docked_flyout_that_stands_below_the_windows() { + let (flyout_on_top, _, clicks) = flyout_under_window(PopupLayer::AboveWindows); + assert!(flyout_on_top, "by default the flyout is on top where it overlaps the window"); + assert_eq!(clicks, 0, "and the press there does not reach the window"); + + let (flyout_on_top, window_above, clicks) = flyout_under_window(PopupLayer::BelowWindows); + assert!(!flyout_on_top && window_above, "below the windows, the window's layer lies above the flyout's"); + assert_eq!(clicks, 1, "and the press where they overlap reaches the window's button"); +} + #[derive(PlainData)] struct RailWithMenu; diff --git a/docs/contract-api.md b/docs/contract-api.md index 30983c458b..7ffd5459c3 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2403,7 +2403,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn unshown(response: Response) -> Option where Self: Sized,`. The output of a layer-like container that shows nothing this pass (closed, past its exit fade): `response` is - `fn value_text(&self) -> Option<&str>`. The shown value as the component words it to assistive technology; `None` for a component that gives none. - `fn story_facts(&self) -> crate::testing::StoryOutput`. The facts a story reports about this output: its id, click, edit kinds, collection kinds and visible range. -- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. +- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub popup_layer: PopupLayer }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. @@ -2434,6 +2434,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn min_width(mut self, min_width: MinWidth) -> Overlay`. Sets the narrowest width. - `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it. - `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]). + - `pub fn popup_layer(mut self, layer: PopupLayer) -> Overlay`. Sets where a popup stands against the floating windows ([`Overlay::popup_layer`]). - `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer. - `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]). - `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer @@ -2725,7 +2726,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `craft_ui::contract::overlay::OpenFilter`: re-export of `craft_ui::runtime::overlay::OpenFilter`. - `craft_ui::contract::overlay::Opener`: `pub struct Opener { pub id: Id, pub rect: Rect, pub layer: areas::Layer, pub trigger: Trigger, pub enabled: bool, pub anchor: Option, pub others: Vec }`. A component that opens a free-standing popup, and how. A layer with several openers keeps the first as its - `craft_ui::contract::overlay::Outside`: `pub enum Outside { Close, Keep, Absorb }`. What a press outside the layer and its anchor does. -- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. +- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub popup_layer: PopupLayer }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. @@ -2756,6 +2757,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub fn min_width(mut self, min_width: MinWidth) -> Overlay`. Sets the narrowest width. - `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it. - `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]). + - `pub fn popup_layer(mut self, layer: PopupLayer) -> Overlay`. Sets where a popup stands against the floating windows ([`Overlay::popup_layer`]). - `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer. - `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]). - `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer @@ -2797,6 +2799,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub fn changed(self, cx: &mut Cx<'_, C>) -> bool`. Whether a toggle, `open` or `close` queued in this pass leaves the popup's open state different from the - `pub fn bind_open(self, cx: &mut Cx<'_, C>, mut open: BindMut<'_, bool>) -> bool`. Binds the popup's open state to `open`: call it in `update`, after the toggles and closes the component - `pub fn is_open(self, cx: &mut Cx<'_, C>) -> bool`. Whether the popup is open in this pass: valid from step 8, with the changes queued so far applied. +- `craft_ui::contract::overlay::PopupLayer`: re-export of `craft_ui::runtime::overlay::PopupLayer`. - `craft_ui::contract::overlay::PopupRegion`: `pub struct PopupRegion(pub Option)`. The screen rect the popups opened in an env are contained in, and the popups opened from those: the menus of a menu - `pub fn new(region: Option) -> Self`. Popups contained in `region`; `None` lets them take the whole safe rect. - `craft_ui::contract::overlay::Resize`: `pub struct Resize { pub edges: ResizeEdges, pub by_caller: bool }`. How the user may resize a layer. @@ -4249,7 +4252,8 @@ The layer stack (15.2): the record of the egui layers shown, their order and the - `craft_ui::runtime::overlay::CloseReason`: `pub enum CloseReason { Requested, Escape, Outside, FocusLeft(crate::runtime::focus::FocusMove), Activated, Enter, Timeout, AnchorGone }`. Why a layer closes. - `craft_ui::runtime::overlay::LayerRole`: `pub enum LayerRole { Plain, Progress, InPlaceEditor }`. What a layer is for, beyond its rank. - `craft_ui::runtime::overlay::OpenFilter`: `pub enum OpenFilter { Any, Modal, Keys }`. What `any_open` counts. -- `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen. +- `craft_ui::runtime::overlay::PopupLayer`: `pub enum PopupLayer { AboveWindows, BelowWindows }`. Where a popup stands against the floating windows of its window. +- `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen, with a popup's - `pub const fn modal(backdrop: Backdrop) -> Rank`. A modal rank with `backdrop`. - `craft_ui::runtime::overlay::any_open`: `pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool`. Whether any layer of the running viewport that `filter` counts was shown last frame. - `craft_ui::runtime::overlay::close_popups`: `pub fn close_popups(ctx: &Context)`. Queues a close of every popup layer of the running viewport shown last frame: its menus, dropdowns and lists. The diff --git a/docs/glossary.md b/docs/glossary.md index 317b2a8587..13ddc3563b 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -216,6 +216,7 @@ One row per name in the author table (Overview) and per `pub` item a component a | `PointerButton`, `Buttons` | Pointer buttons, egui-free | craft-behavior | 8.1 | | `Politeness` | An announcement's or live region's urgency | `craft_ui::runtime::access` | 12.1 | | `PopupHandle` | A `Copy` id and name for one of a component's own popups, from `cx.popup(name)`, with `trigger`, `open`, `close` and `is_open` | `craft_ui::contract` | 15.5 | +| `PopupLayer` | Where a popup stands against the floating windows: above them, or below them for one opened outside every layer (a dock column's flyout) | `craft_ui::runtime` (layer stack) | 15.2 | | Prelude | The stable surface of a crate | each crate | 1.11 | | Press-target rule | Exactly one root starts each press: on the topmost layer under it, the root whose press-taking shape is painted on top there; none when egui's hit test names a raw egui widget | `craft_ui::primitives` (sensing core) | 8.3 | | `PressPhase`, `PressState` | A press lifecycle's phase, and its state with mods, sample and capture | craft-behavior | 8.2 | diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 081948655d..ab8b4518cb 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -105,6 +105,7 @@ The host handles these `DockEvent`s: | `panel_menu_always` | off | Every group shows its panel menu button, with the dock's own rows when the shown panel has none. Off: only a panel with rows of its own (`DockPanels::panel_rows`) gets the button. | | `panel_menu_icon` | `more` | The panel menu button's icon; `menu` gives the three-line mark. | | `native_windows` | on | Floating windows open as OS windows where the window host opens them and reports their positions (not on Wayland) and `PanelSpec::allow_native` allows. | +| `flyout_layer` | `PopupLayer::AboveWindows` | Where docked columns' flyouts stand against the floating windows. `PopupLayer::BelowWindows` keeps a floating window in front of a docked flyout it overlaps: drawn over it and taking the presses there. The flyout still closes by its rules, and menus opened from it stand above everything. A floating window's own flyouts stand above it either way. | The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords` holds the words. From 525743f8249d54f7abc23757679809e6507e4fef Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 18:07:16 +0100 Subject: [PATCH 05/27] ui-contract viewports: the window's movable flag read between passes answers for the viewport's last pass. egui counts a pass when it ends, so read after the frame the flag the pass wrote looked stale and said the window was movable everywhere, over a title bar's Home button too. Title bar trial under the movable flag over a control and over the free band, with a measuring run before the drawn run --- .../ui-contract/src/runtime/egui/viewports.rs | 10 +++- crates/ui-shell/src/shell/title_bar.rs | 3 +- crates/ui-shell/tests/it/shell/title_bar.rs | 57 +++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/viewports.rs b/crates/ui-contract/src/runtime/egui/viewports.rs index e20acbb1e8..028bb666aa 100644 --- a/crates/ui-contract/src/runtime/egui/viewports.rs +++ b/crates/ui-contract/src/runtime/egui/viewports.rs @@ -250,11 +250,15 @@ fn movable_id(viewport: ViewportId) -> egui::Id { /// Whether the OS may move the running viewport's window from where the pointer is in this pass: what the move bands /// of the pass wrote (the body step writes it for every move band of an OS window, `true` only where a press would go -/// to the band), else what the app wrote with [`write_movable`], else true. +/// to the band), else what the app wrote with [`write_movable`], else true. Read between passes (by an integration or +/// a test after the frame), it answers for the viewport's last pass: egui counts a pass when it ends, so there the +/// pass number has already moved past the pass that wrote the flag. #[doc(hidden)] pub fn movable(ctx: &Context) -> bool { - match movable_record(ctx) { - Some((pass, movable)) if pass == pass_number(ctx) => movable, + let number = pass_number(ctx); + let latest = if crate::runtime::frame::running(ctx).is_some() { Some(number) } else { number.checked_sub(1) }; + match (movable_record(ctx), latest) { + (Some((pass, movable)), Some(latest)) if pass == latest => movable, _ => true, } } diff --git a/crates/ui-shell/src/shell/title_bar.rs b/crates/ui-shell/src/shell/title_bar.rs index 9a58954a9f..06b6aedd76 100644 --- a/crates/ui-shell/src/shell/title_bar.rs +++ b/crates/ui-shell/src/shell/title_bar.rs @@ -7,7 +7,8 @@ use egui::Context; /// Whether the OS may move the running viewport's window from where the pointer is in this pass: what the move bands /// of the pass wrote (the body step writes it for every move band of an OS window, `true` only where a press would go /// to the band), else what the app wrote with [`set_window_movable`], else true. The runtime sets macOS's -/// `NSWindow.movable` from it at the end of each window's pass. +/// `NSWindow.movable` from it at the end of each window's pass. Read between passes, it answers for the window's last +/// pass. pub fn window_movable(ctx: &Context) -> bool { viewports::movable(ctx) } diff --git a/crates/ui-shell/tests/it/shell/title_bar.rs b/crates/ui-shell/tests/it/shell/title_bar.rs index b77a166ae0..a4f36936d8 100644 --- a/crates/ui-shell/tests/it/shell/title_bar.rs +++ b/crates/ui-shell/tests/it/shell/title_bar.rs @@ -160,6 +160,63 @@ fn a_press_on_a_control_over_the_band_never_moves_or_zooms_the_window() { assert!(band_double.contains(&ViewportCommand::Maximized(true)), "a double click on the free band maximizes the window: {band_double:?}"); } +/// The OS may move the window (macOS `NSWindow.movable`) only where a press would go to the bar's free band: not over +/// the bar's Home button, over the free band yes. The bar runs in a measuring run before its drawn run, as in a +/// measured container, and the flag reads the same in the pass and after it. Read after the pass, it used to say the +/// window was movable everywhere: egui had counted the pass by then, so the flag the pass wrote looked stale. +#[trial] +fn the_window_is_movable_from_the_free_band_and_not_from_a_control_over_it() { + use craft_ui::buttons::Button; + use craft_ui::contract::Show as _; + use craft_ui::runtime::measure; + use craft_ui::shell::title_bar::window_movable; + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout }); + let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None }; + let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).frame(Decision { frame, overridden: None, desktop })); + let (bar, in_pass) = (Cell::new(Rect::NOTHING), Cell::new(None)); + let show = |ui: &mut Ui| { + TitleBar::new() + .show_titled( + ui, + Title::new("Landscape.psd"), + |ui, _| { + Button::new("Home").show(ui); + }, + |_, _| {}, + ) + .response + .rect + }; + let frame = |events: Vec| { + windows.frame(events, vec![], |ui| { + let ctx = ui.ctx().clone(); + let builder = egui::UiBuilder::new().sizing_pass().invisible(); + measure::run(&ctx, || ui.scope_builder(builder, show)); + bar.set(show(ui)); + in_pass.set(Some(window_movable(&ctx))); + }) + }; + frame(vec![]); + let settled = frame(vec![]); + let tree = &settled.trees.iter().rev().find(|(viewport, _)| *viewport == ViewportId::ROOT).expect("the root pass ran").1; + let home = tree + .with_role(Role::BUTTON) + .into_iter() + .find(|key| tree.name_of(*key) == Some("Home")) + .and_then(|key| tree.bounds_of(key)) + .expect("the bar shows its Home button") + .center(); + // The title is no control: the band lies under it. + let band = bar.get().center(); + for (at, movable, what) in [(home, false, "over Home"), (band, true, "over the free band"), (home, false, "over Home again")] { + frame(vec![moved(at)]); + frame(vec![]); + assert_eq!(in_pass.get(), Some(movable), "{what}, read in the pass"); + assert_eq!(window_movable(&windows.ctx), movable, "{what}, read after the pass"); + } +} + /// The shell sends the window title once after a change and not again while the viewport reports it; an embedded shell /// sends none. #[trial] From 783d30a73e5f2bec77356fcc9efa51782380a696 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 18:08:45 +0100 Subject: [PATCH 06/27] ui-contract overlay: DragBounds::TitleVisible lets a moved dialog go past the window's edges A movable float was always kept wholly inside the window, so a dialog that previews its change in the document behind it could not be moved aside. Overlay::drag_bounds and Dialog::drag_bounds take DragBounds::Inside (the default, unchanged) or TitleVisible, which keeps only the top edge and a strip of the title band (size.bar.title tall, size.dialog.button wide) inside, as the old DesignCraft dialogs and InDesign do. A float kept that way has the room it would have inside, so it keeps its size past an edge, and a drag starts from where the layer is shown rather than from a stored position the keep rule moved. Trial: a_layer_that_keeps_its_title_strip_inside_moves_past_the_window_edges. --- crates/ui-contract/src/contract/body/hooks.rs | 2 +- .../src/contract/body/placement.rs | 18 +++---- .../ui-contract/src/contract/body/window.rs | 10 ++-- crates/ui-contract/src/contract/mount.rs | 2 +- crates/ui-contract/src/contract/overlay.rs | 2 +- .../ui-contract/src/contract/overlay/place.rs | 32 +++++++++++++ .../src/contract/overlay/placement.rs | 20 ++++---- .../ui-contract/src/contract/overlay/props.rs | 13 ++++- crates/ui-contract/tests/it/body/placement.rs | 47 ++++++++++++++++++- crates/ui-panels/src/dialog/modal.rs | 10 +++- 10 files changed, 131 insertions(+), 25 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index a92e7820ed..ccdade1412 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -195,7 +195,7 @@ impl ShapeHooks for BodyHooks<'_> { Mount::Layer(_) | Mount::Viewport { .. } => { let placement = overlay_of(props).map_or_else(Placement::default, |overlay| { let screen = crate::contract::overlay::screen_for(&ctx, env, overlay); - shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, env.tokens.space.inset.screen) + shown_placement(&ctx, id, save.as_ref(), overlay, None, screen, &env.tokens) }); // A layer the user sized takes that size, at its saved position or where its anchor places it. placement.size.is_some() diff --git a/crates/ui-contract/src/contract/body/placement.rs b/crates/ui-contract/src/contract/body/placement.rs index 311fe446b3..19decad5c0 100644 --- a/crates/ui-contract/src/contract/body/placement.rs +++ b/crates/ui-contract/src/contract/body/placement.rs @@ -5,6 +5,7 @@ use crate::contract::{ContainerProps, Mount}; use crate::runtime::egui::areas; use crate::runtime::memory::{MemoryStage, SaveKey, sub}; use crate::runtime::windows::{self}; +use crate::style::UiTokens; use egui::{Context, Id, Pos2, Rect, Ui, Vec2}; use serde::{Deserialize, Serialize}; @@ -94,9 +95,10 @@ fn placement_of(ctx: &Context, id: Id, save: Option<&SaveKey>) -> Placement { } /// The placement a layer is shown at: the caller's `placed` rect or `placed_at` position, else the saved or session placement, else for a -/// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less `screen_inset` on -/// each side, centred or at the overlay's float position. A saved size and position win over the default. A size with -/// no position places an anchored layer from its anchor at that size. +/// floating resizable layer with a default size (`Overlay::size`) that size, within the screen less the tokens' +/// `space.inset.screen` on each side, centred or at the overlay's float position and kept as `Overlay::drag_bounds` +/// says. A saved size and position win over the default. A size with no position places an anchored layer from its +/// anchor at that size. /// /// While a drag of the layer's move band runs, `moving` is the rect it puts the layer at in this pass /// (`WindowMode::running_move`): the layer shows there, within its bounds, at the size the placement gives. The @@ -108,9 +110,9 @@ pub(crate) fn shown_placement( overlay: &crate::contract::Overlay, moving: Option, screen: Rect, - screen_inset: f32, + tokens: &UiTokens, ) -> Placement { - let mut placement = resting_placement(ctx, id, save, overlay, screen, screen_inset); + let mut placement = resting_placement(ctx, id, save, overlay, screen, tokens); if let Some(moving) = moving { placement.pos = Some(super::window::kept_in(moving, overlay.bounds).min.into()); } @@ -124,7 +126,7 @@ fn resting_placement( save: Option<&SaveKey>, overlay: &crate::contract::Overlay, screen: Rect, - screen_inset: f32, + tokens: &UiTokens, ) -> Placement { if let Some(given) = Placement::given(overlay) { return given; @@ -136,14 +138,14 @@ fn resting_placement( if placement.size.is_some() { return placement; } - let room = (screen.size() - Vec2::splat(2.0 * screen_inset)).max(Vec2::ZERO); + let room = (screen.size() - Vec2::splat(2.0 * tokens.space.inset.screen)).max(Vec2::ZERO); let least = overlay.size_limits.min.min(room); let size = default.max(least).min(overlay.size_limits.max.unwrap_or(Vec2::INFINITY)).min(room); // The layer centres, and is kept, inside the screen cut to `bounds`; bounds that miss the screen leave it whole. let region = overlay.bounds.map(|bounds| screen.intersect(bounds)).filter(|region| region.is_positive()).unwrap_or(screen); // The saved position is the layer's top left; the float's is where its corner sits. let pos = placement.pos.map(Pos2::from).or_else(|| float.top_left(size)).unwrap_or_else(|| region.center() - size / 2.0); - let pos = super::window::keep_inside(Rect::from_min_size(pos, size), region).min; + let pos = overlay.drag_bounds.keep(Rect::from_min_size(pos, size), region, tokens).min; placement.pos = Some(pos.into()); placement.size = Some(size.into()); placement diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index dc5e45c133..352afa91e7 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -213,7 +213,8 @@ fn resized_edge(before: Rect, after: Rect) -> Option { } /// `rect` moved, at its size, the least distance that puts it inside `bounds`: the one keep rule for a layer's -/// bounds, whether the user moves the layer or the host places it. On an axis where it is longer than the bounds, its +/// bounds, whether the user moves the layer or the host places it, and the window's under the default +/// [`DragBounds::Inside`](crate::contract::overlay::DragBounds::Inside). On an axis where it is longer than the bounds, its /// low edge sits on theirs. pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect { let keep = |low: f32, high: f32, bounds_low: f32, bounds_high: f32| low.min(bounds_high - (high - low)).max(bounds_low) - low; @@ -484,15 +485,18 @@ impl BodyHooks<'_> { }; let mut slot = PlacementSlot::new(&mut *cx.core.memory, id, self.save.as_ref(), overlay); let current = slot.read(); + // Where the layer stands: at the placement's size, where it is shown, which the window's keep rule + // (`Overlay::drag_bounds`) may have moved from the stored position a drag past the window's edge left. + let shown = Rect::from_min_size(rect.min, current.rect_over(rect).size()); let (origin, pos, gesture) = match phase { PressPhase::Down { .. } => { - self.mode.pressed = Some(current.rect_over(rect)); + self.mode.pressed = Some(shown); return; } PressPhase::DragStart { start, pos, .. } => { // The layer host shows this pass at the step's rect already (`running_move`): the drag runs from where // the layer stood at the press. - self.mode.began = Some(self.mode.pressed.unwrap_or_else(|| current.rect_over(rect))); + self.mode.began = Some(self.mode.pressed.unwrap_or(shown)); self.mode.restore = current.clone(); self.mode.held = grip; (start.origin, Some(pos), GesturePhase::Begin) diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 8f90ce438e..cb66d8e9b8 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -243,7 +243,7 @@ impl Host for LayerHost { overlay = mapped; } let screen = overlay::screen_for(&ctx, env, &overlay); - let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, env.tokens.space.inset.screen); + let placement = shown_placement(&ctx, id, self.save.as_ref(), &overlay, self.moving, screen, &env.tokens); // An anchored resizable layer has no position to seed: its default size is held as its minimum until the // user resizes it. if overlay.fit == overlay::OverlayFit::Resizable diff --git a/crates/ui-contract/src/contract/overlay.rs b/crates/ui-contract/src/contract/overlay.rs index 5974d4d2c7..516fafe177 100644 --- a/crates/ui-contract/src/contract/overlay.rs +++ b/crates/ui-contract/src/contract/overlay.rs @@ -22,7 +22,7 @@ pub use host::paint_frame_layers; pub(crate) use host::{Layer, forget_layer, host, host_window}; pub(crate) use opener::{LayerFloor, anchor_floor}; pub use opener::{Opener, Trigger}; -pub use place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; +pub use place::{Anchor, DragBounds, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; pub use placement::{PopupRegion, layer_room}; pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_for}; pub(crate) use popups::dwell; diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index 93c7c89b0f..0bdd685be9 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -1,5 +1,6 @@ //! Where a layer sits and how it sizes: anchors, places, viewport shares, fit, resize and size limits. +use crate::style::UiTokens; use craft_behavior::overlay::{Align, Side}; use egui::{Align2, Pos2, Rect, Vec2}; @@ -60,6 +61,37 @@ impl FloatPlace { } } +/// How much of a floating layer stays inside the window when the user moves it, or when it is placed at a position: +/// the window's safe rect, cut to the overlay's [`bounds`](super::Overlay::bounds) when it sets them. Bounds of the +/// overlay's own still hold the whole layer while the user moves it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum DragBounds { + /// The whole layer: a move stops where an edge of the layer meets the window's. + #[default] + Inside, + /// A strip of its title: its top edge stays at or below the window's top, and at least `size.bar.title` of its + /// height and `size.dialog.button` of its width stay inside, so the user takes it back by its title band. The rest + /// may go past the window's edges: a dialog moved mostly aside shows what lies behind it, as InDesign's do. A layer + /// smaller than the strip on an axis stays whole inside on that axis. + TitleVisible, +} + +impl DragBounds { + /// `rect` moved, at its size, the least distance that keeps what this rule keeps of it inside `bounds`. + pub(crate) fn keep(self, rect: Rect, bounds: Rect, tokens: &UiTokens) -> Rect { + match self { + DragBounds::Inside => crate::contract::body::keep_inside(rect, bounds), + DragBounds::TitleVisible => { + let strip = Vec2::new(tokens.size.dialog.button, tokens.size.bar.title).min(rect.size()); + let x = rect.min.x.min(bounds.max.x - strip.x).max(bounds.min.x + strip.x - rect.width()); + let y = rect.min.y.min(bounds.max.y - strip.y).max(bounds.min.y); + rect.translate(Pos2::new(x, y) - rect.min) + } + } + } +} + /// Where an egui layer sits. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 4785c5fe09..dbe306e841 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -263,12 +263,14 @@ pub(super) struct Placed { } /// The pure placement of the anchored forms; the centre or the given position for floats, kept inside the safe rect -/// within the overlay's bounds (`within_bounds`) by the keep rule moves follow. An anchored layer takes its side by its -/// size: below its anchor, above when the room below is too short and the room above is larger, and keeps that side -/// while it stays open, asks for the same side, and the content fits there or that side is the larger. A layer that `covers` its anchor -/// ([`layer_covers_anchor`]) and fits neither side keeps its height within the bounds and slides over the anchor. -/// Before its size is known (a popup's first, hidden pass) it takes no side and its body is offered `content_room`, so -/// the size it measures decides the side. +/// within the overlay's bounds (`within_bounds`) by the keep rule moves follow (`Overlay::drag_bounds`). A float that +/// keeps only its title strip inside has the room it would have with the whole of it inside, so a move past an edge +/// leaves its size as it was. An anchored layer takes its side by its size: below its anchor, above when the room below +/// is too short and the room above is larger, and keeps that side while it stays open, asks for the same side, and the +/// content fits there or that side is the larger. A layer that `covers` its anchor ([`layer_covers_anchor`]) and fits +/// neither side keeps its height within the bounds and slides over the anchor. Before its size is known (a popup's +/// first, hidden pass) it takes no side and its body is offered `content_room`, so the size it measures decides the +/// side. pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Option, bounds: Rect, anchor: Rect) -> Placed { let rtl = layer.env.direction.is_rtl(); let cap = cap(layer.overlay, bounds, anchor); @@ -302,8 +304,10 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Op let kept = within_bounds(layer.overlay, bounds); let size = size.unwrap_or(egui::Vec2::ZERO); let min = float.top_left(size).unwrap_or_else(|| kept.center() - size / 2.0); - let at = crate::contract::body::keep_inside(Rect::from_min_size(min, size), kept).min; - Placed { at, side: None, asked: None, room: (kept.max - at).max(egui::Vec2::ZERO).min(cap) } + let rect = Rect::from_min_size(min, size); + let at = layer.overlay.drag_bounds.keep(rect, kept, &layer.env.tokens).min; + let inside = crate::contract::body::keep_inside(rect, kept).min; + Placed { at, side: None, asked: None, room: (kept.max - inside).max(egui::Vec2::ZERO).min(cap) } } } } diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index a01d00a92f..cb3e17f3ab 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -1,7 +1,7 @@ //! The `Overlay` data, its presets and builders, its dismissal rules and the placement changes it reports. use super::opener::{Opener, Trigger}; -use super::place::{Anchor, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; +use super::place::{Anchor, DragBounds, FloatPlace, OverlayFit, Place, Resize, ResizeEdges, SizeLimits, ViewportShare}; use crate::runtime::access::PopupKind; use crate::runtime::focus::{FocusPolicy, Initial}; use crate::runtime::motion::{MotionSpec, spec}; @@ -109,6 +109,9 @@ pub struct Overlay { pub min_width: MinWidth, /// Whether the user may move it. pub movable: bool, + /// How much of it stays inside the window when the user moves it or it floats at a position (default + /// [`DragBounds::Inside`]). + pub drag_bounds: DragBounds, /// How the user may resize it. pub resize: Resize, /// Its rank. @@ -180,6 +183,7 @@ impl Overlay { fit, min_width: MinWidth::None, movable: false, + drag_bounds: DragBounds::Inside, resize: Resize::NONE, rank, keys, @@ -461,6 +465,13 @@ impl Overlay { self } + /// Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]): + /// [`DragBounds::TitleVisible`] lets a dialog go past the window's edges with its title band left to grab. + pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay { + self.drag_bounds = bounds; + self + } + /// Sets what the layer is for ([`Overlay::role`]). pub fn role(mut self, role: LayerRole) -> Overlay { self.role = role; diff --git a/crates/ui-contract/tests/it/body/placement.rs b/crates/ui-contract/tests/it/body/placement.rs index 77d7127232..d8af700f04 100644 --- a/crates/ui-contract/tests/it/body/placement.rs +++ b/crates/ui-contract/tests/it/body/placement.rs @@ -4,7 +4,7 @@ use craft_behavior::overlay::{Align, Side}; use craft_behavior::{GesturePhase, Sense}; -use craft_ui::contract::overlay::{Anchor, FloatPlace, Place, PlacementChange, PlacementKind}; +use craft_ui::contract::overlay::{Anchor, DragBounds, FloatPlace, Place, PlacementChange, PlacementKind}; use craft_ui::contract::{ BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Mount, Overlay, Props as _, Role, Show as _, ShowContainer as _, Sizing, @@ -144,6 +144,51 @@ fn a_placed_layer_reports_its_move_and_keeps_no_placement_of_its_own() { assert!((caller.rect.get().min - commit.rect.min).abs().max_elem() > SLACK, "no placement was stored: {:?}", caller.rect.get()); } +/// A movable float dragged by its header far toward the window's bottom right corner: under the default +/// `DragBounds::Inside` it stops with the whole of it inside the window. Under `DragBounds::TitleVisible` it goes past +/// the right and bottom edges at its own size with its header still inside, and a second drag of the header moves it +/// back by the pointer's travel. +#[trial] +fn a_layer_that_keeps_its_title_strip_inside_moves_past_the_window_edges() { + for bounds in [DragBounds::Inside, DragBounds::TitleVisible] { + let (shown, log, seen) = (Cell::new(Rect::NOTHING), RefCell::new(Vec::new()), RefCell::new(Seen::default())); + let mut show = |ui: &mut Ui| { + let overlay = Overlay::floating().movable(true).drag_bounds(bounds); + let props = ContainerProps::new().mount(Mount::Layer(overlay)).sizing(Sizing::Content).header(HeaderRegion::new().band(DragBand::Move)); + let out = Pane { common: Common::new(), props, log: &log }.id_salt("aside").show(ui, |ui, _| { + Probe::new(&seen).size(BODY).show(ui); + }); + shown.set(out.output.rect); + }; + let mut frames = Frames::new(); + frames.idle(4, &mut show); + let window = frames.ctx.content_rect(); + let start = shown.get(); + assert!(start.is_positive() && window.contains_rect(start), "{bounds:?}: the layer opens inside {window:?}: {start:?}"); + // The pointer ends just inside the window's corner; the layer's own corner would end far past it. + let grab = header_of(start); + pointer::drag(&mut frames, grab, window.right_bottom() - Vec2::splat(4.0) - grab, &mut show); + frames.idle(3, &mut show); + let moved = shown.get(); + assert!((moved.size() - start.size()).abs().max_elem() < SLACK, "{bounds:?}: the layer keeps its size: {start:?} -> {moved:?}"); + if bounds == DragBounds::Inside { + assert!(window.expand(SLACK).contains_rect(moved), "{bounds:?}: the layer stays inside {window:?}: {moved:?}"); + continue; + } + assert!(moved.right() > window.right() + SLACK, "the layer goes past the right edge of {window:?}: {moved:?}"); + assert!(moved.bottom() > window.bottom() + SLACK, "the layer goes past the bottom edge of {window:?}: {moved:?}"); + // The part of the header left inside the window takes the next drag. + let title = Pos2::new((moved.left() + window.right()) / 2.0, moved.top() + 8.0); + assert!(window.contains(title) && moved.contains(title), "the header stays inside {window:?}: {moved:?}"); + let back = Vec2::new(-200.0, -200.0); + pointer::drag(&mut frames, title, back, &mut show); + frames.idle(3, &mut show); + let returned = shown.get(); + assert!((returned.min - (moved.min + back)).abs().max_elem() < SLACK, "a drag of the header moves it back: {moved:?} -> {returned:?}"); + assert!(window.contains_rect(returned), "the layer is back inside {window:?}: {returned:?}"); + } +} + /// Where the layers of the Size trial hang from: with room above it and before it. const ANCHOR: Rect = Rect { min: Pos2::new(400.0, 300.0), max: Pos2::new(430.0, 320.0) }; diff --git a/crates/ui-panels/src/dialog/modal.rs b/crates/ui-panels/src/dialog/modal.rs index 93ed9e84d8..51a4218f18 100644 --- a/crates/ui-panels/src/dialog/modal.rs +++ b/crates/ui-panels/src/dialog/modal.rs @@ -3,7 +3,7 @@ use super::frame::{self, DialogOutput, FOOTER, FooterCx, FooterFn, FooterHooks, HEADER, SIDE_BUTTONS}; use crate::contract::Remember as _; -use crate::contract::overlay::{FloatPlace, OverlayFit, Place}; +use crate::contract::overlay::{DragBounds, FloatPlace, OverlayFit, Place}; use crate::contract::{ Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, FooterPlace, FooterRegion, HeaderRegion, Mount, Overlay, Pad, Props as _, Role, SaveKey, Show as _, ShowContainer as _, @@ -196,6 +196,14 @@ impl<'a> Dialog<'a> { self.overlay(Overlay::modeless) } + /// How much of the dialog stays inside the window when the user moves it by its title band: the whole dialog + /// ([`DragBounds::Inside`], the default), or only a strip of its title ([`DragBounds::TitleVisible`]), so a dialog + /// that previews its change in the document behind it moves mostly aside and is taken back by its title. + #[must_use] + pub fn drag_bounds(self, bounds: DragBounds) -> Self { + self.overlay(|overlay| overlay.drag_bounds(bounds)) + } + /// What is drawn behind a modal dialog. #[must_use] pub fn backdrop(self, backdrop: Backdrop) -> Self { From f52799a8bf036e0238e013a726e3d2839931f904 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 01:04:10 +0100 Subject: [PATCH 07/27] tabs: ellipsis panel tabs all shrink to their least before any overflows Under PanelTabShrink::Ellipsis the shown panel tab kept its whole title, as it does under FirstLetters, and the other tabs shrank only to the widest tab's least, so a group sent a sibling to the overflow menu where every tab would fit at its readable least: DesignCraft's Stroke, Color and Swatches group hid Color while Swatches was shown, and Separations Preview hid Attributes and Preflight. Add FitMode::ShrinkToLeast and craft_behavior::fit::fit_to_least: every tab shrinks, the shown one too, the widest first, each no further than its own least, and only the tabs that do not fit at their least overflow, the last ones first. A panel strip under PanelTabShrink::Ellipsis fits this way (TabKind::fit_mode_for); FirstLetters and the other kinds are unchanged. Trial: panel_tabs_shrinking_to_an_ellipsis_all_reach_their_least_before_any_overflows. --- crates/behavior/src/fit.rs | 64 +++++++++++++++++++++++--- crates/ui-panels/src/docking/config.rs | 4 +- crates/ui-widgets/src/tabs/rules.rs | 25 ++++++++-- crates/ui-widgets/src/tabs/strip.rs | 33 +++++++++---- crates/ui-widgets/tests/it/tabs.rs | 62 +++++++++++++++++++++++++ docs/contract-api.md | 1 + docs/ui-docking.md | 2 +- 7 files changed, 169 insertions(+), 22 deletions(-) diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..3712ca15e2 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,7 @@ -//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and -//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`], +//! [`fit_to_least`] and [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); +//! [`fit_items`] shortens items that have a short form, then drops command items and titles from the end. All of them +//! read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -175,10 +176,61 @@ pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32 TabFit { shown, overflow, overflow_width } } +/// Fit tab widths into `available` points, each tab shrinking to its own `least` before any tab overflows. +/// Every tab shrinks, the selected one too: the widest tabs shrink first to a common cap, and each keeps at least +/// `min(natural, least)` of its own. Only when the tabs do not all fit at their least is an overflow button +/// `overflow_width` wide reserved; the selected tab stays, the others follow in order while their least widths fit +/// beside it, and the rest overflow, the last ones first. A selected tab whose least alone is wider than the strip +/// less the button takes the room left. A tab past the end of `least` keeps its natural width as its least. +/// +/// Dimensions are sanitized as in [`fit`], and the shown widths plus `overflow_width` never exceed the sanitized +/// available width. Work and storage are linear in the input count (with at most 32 fitting passes). +pub fn fit_to_least(natural: &[f32], least: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit { + let available = tab_extent(available); + let natural: Vec = natural.iter().map(|&w| tab_extent(w)).collect(); + let floors: Vec = natural.iter().enumerate().map(|(i, &w)| least.get(i).map_or(w, |&least| w.min(tab_extent(least)))).collect(); + let all: Vec = (0..natural.len()).collect(); + let total = |widths: &[f32]| widths.iter().map(|&w| f64::from(w)).sum::(); + if total(natural.as_slice()) <= f64::from(available) { + return TabFit { shown: all.into_iter().zip(natural).collect(), ..Default::default() }; + } + // One tab has nowhere to overflow; all available space belongs to it. + if natural.len() == 1 { + return TabFit { shown: vec![(0, available)], ..Default::default() }; + } + let floor = |i: usize| floors.get(i).copied().unwrap_or(0.0); + if total(floors.as_slice()) <= f64::from(available) { + return TabFit { shown: squeeze_floored(&natural, &all, available, 0.0, floor), ..Default::default() }; + } + let overflow_width = tab_extent(overflow_width).min(available); + let budget = available - overflow_width; + let selected = selected.min(natural.len().saturating_sub(1)); + let mut used = f64::from(floor(selected)); + let mut open = true; + let (shown, overflow): (Vec, Vec) = all.into_iter().partition(|&i| { + if i == selected { + return true; + } + open = open && used + f64::from(floor(i)) <= f64::from(budget); + if open { + used += f64::from(floor(i)); + } + open + }); + let shown = squeeze_floored(&natural, &shown, budget, 0.0, floor); + TabFit { shown, overflow, overflow_width } +} + fn squeeze(natural: &[f32], indices: &[usize], total: f32, minimum: f32) -> Vec<(usize, f32)> { + squeeze_floored(natural, indices, total, minimum, |i| natural.get(i).copied().unwrap_or(0.0).min(minimum)) +} + +/// Shrinks the tabs at `indices` into `total` to a common cap, found between `start` and the widest natural width, +/// each tab keeping at least its `floor`. +fn squeeze_floored(natural: &[f32], indices: &[usize], total: f32, start: f32, floor: impl Fn(usize) -> f32) -> Vec<(usize, f32)> { let width = |i: usize| natural.get(i).copied().unwrap_or(0.0); - let sum_at = |cap: f32| indices.iter().map(|&i| f64::from(width(i).min(cap.max(width(i).min(minimum))))).sum::(); - let (mut lo, mut hi) = (minimum, indices.iter().map(|&i| width(i)).fold(minimum, f32::max)); + let sum_at = |cap: f32| indices.iter().map(|&i| f64::from(width(i).min(cap.max(floor(i))))).sum::(); + let (mut lo, mut hi) = (start, indices.iter().map(|&i| width(i)).fold(start, f32::max)); if sum_at(hi) > f64::from(total) { for _ in 0..32 { let mid = lo + (hi - lo) * 0.5; @@ -198,7 +250,7 @@ fn squeeze(natural: &[f32], indices: &[usize], total: f32, minimum: f32) -> Vec< let natural = width(i); // Also handles a selected tab whose minimum alone exceeds the budget, and prevents // accumulated floating-point rounding from placing the overflow button past the end. - let width = natural.min(lo.max(natural.min(minimum))).min(remaining); + let width = natural.min(lo.max(floor(i))).min(remaining); remaining = (remaining - width).max(0.0); (i, width) }) diff --git a/crates/ui-panels/src/docking/config.rs b/crates/ui-panels/src/docking/config.rs index f43f20d895..685f47a3e5 100644 --- a/crates/ui-panels/src/docking/config.rs +++ b/crates/ui-panels/src/docking/config.rs @@ -102,8 +102,8 @@ pub struct DockConfig { /// filled rounded pill ([`PanelTabLook::Pill`]). pub tab_look: PanelTabLook, /// How far the groups' panel tabs shrink before they overflow: to their first letters, clipped - /// ([`PanelTabShrink::FirstLetters`]), or to a readable prefix ending in "…" ([`PanelTabShrink::Ellipsis`]), the - /// tabs that do not fit at that width going to the strip's overflow menu. + /// ([`PanelTabShrink::FirstLetters`]), or each to a readable prefix ending in "…", the shown tab too + /// ([`PanelTabShrink::Ellipsis`]), the tabs that do not fit at that width going to the strip's overflow menu. pub tab_shrink: PanelTabShrink, /// A floating window opens in an OS window of its own where the window host opens OS windows and reports where /// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 3ba30b32c0..37f66be1e6 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -1,6 +1,6 @@ //! The pure rules of a tab strip: what each kind of strip does, and which side a tab's close button is on. -use craft_behavior::fit::{TabFit, fit, fit_whole}; +use craft_behavior::fit::{TabFit, fit, fit_to_least, fit_whole}; use craft_host::target::Os; /// The look of document tabs ([`TabKind::Document`]) app-wide. An app sets it once at its root (`RootEnv::values`); @@ -40,8 +40,9 @@ pub enum PanelTabShrink { FirstLetters, /// Tabs shrink no further than their label's readable least, its first /// [`TextRun::READABLE_CHARACTERS`](crate::primitives::TextRun::READABLE_CHARACTERS) characters and an ellipsis (a - /// title at most one character longer stays whole), and a cut label ends in "…"; the tabs that do not fit at that - /// width go to the overflow menu. + /// title at most one character longer stays whole), and a cut label ends in "…". Every tab shrinks, the shown one + /// too, the widest first; only the tabs that do not fit at their least go to the overflow menu, the last ones + /// first ([`FitMode::ShrinkToLeast`]). Ellipsis, } @@ -76,16 +77,22 @@ pub enum FitMode { /// Whether the selected tab keeps its natural width. keep_selected: bool, }, + /// Every tab shrinks towards its own least width, the selected one too, the widest first; only the tabs that do + /// not fit at their least overflow, the last ones first (`fit_to_least`). Panel tabs under + /// [`PanelTabShrink::Ellipsis`]. + ShrinkToLeast, } impl FitMode { /// Fits tabs of the `natural` widths into `available`, keeping the `selected` tab. Whole widths give the tabs /// marked in `kept` the room before the other tabs (`fit_whole`); shrinking tabs have no kept tabs. `minimum` is - /// the narrowest a shrinking tab becomes and `overflow` the width of the overflow button. + /// the narrowest a shrinking tab becomes and `overflow` the width of the overflow button; [`FitMode::ShrinkToLeast`] + /// takes it as every tab's least (a strip passes each tab's own to `fit_to_least`). pub fn fit(self, natural: &[f32], selected: usize, kept: &[bool], available: f32, minimum: f32, overflow: f32) -> TabFit { match self { FitMode::Whole => fit_whole(natural, selected, kept, available, overflow), FitMode::Shrink { keep_selected } => fit(natural, selected, available, minimum, overflow, keep_selected), + FitMode::ShrinkToLeast => fit_to_least(natural, &vec![minimum; natural.len()], selected, available, overflow), } } } @@ -125,12 +132,20 @@ impl TabKind { if self.shrinks_in(look) { FitMode::Shrink { keep_selected: self.keeps_active_width() } } else { self.fit_mode() } } + /// How tab widths are fitted under the app's document tab look and the strip's panel shrink: panel tabs under + /// [`PanelTabShrink::Ellipsis`] all shrink to their own readable least, the shown tab too, before any overflows + /// ([`FitMode::ShrinkToLeast`]); every other kind and shrink is [`TabKind::fit_mode_in`]. + pub fn fit_mode_for(self, look: DocumentTabLook, shrink: PanelTabShrink) -> FitMode { + if self == Self::Panel && shrink == PanelTabShrink::Ellipsis { FitMode::ShrinkToLeast } else { self.fit_mode_in(look) } + } + /// Whether these are document tabs under [`DocumentTabLook::Shrinking`]. pub fn shrinks_in(self, look: DocumentTabLook) -> bool { self == Self::Document && look == DocumentTabLook::Shrinking } - /// Whether the shown tab keeps its whole title while the other tabs shrink: panel tabs. + /// Whether the shown tab keeps its whole title while the other tabs shrink: panel tabs that shrink to their first + /// letters (under [`PanelTabShrink::Ellipsis`] the shown tab shrinks with the others, [`TabKind::fit_mode_for`]). pub fn keeps_active_width(self) -> bool { self == Self::Panel } diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index 75af550fd4..39bd4feefb 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -29,7 +29,7 @@ use crate::primitives::{PaintShape, StrokeWidth}; use crate::runtime::commands::FireSource; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleColor, StyleCx}; -use craft_behavior::fit::{FitItem, fit_items}; +use craft_behavior::fit::{FitItem, fit_items, fit_to_least}; use craft_behavior::{ Flow, HitLevel, HitPriority, IconId, Insets, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, SelectionChange, Sense, @@ -315,8 +315,22 @@ impl StripLayout { }) .collect(); let selected = lane.iter().position(|place| matches!(*place, Lane::Tab(at) if at == *selected)).unwrap_or(usize::MAX); - let minimum = min.iter().copied().fold(0.0, f32::max); - let fit = mode.fit(&padded, selected, &held, (*width - ends_room).max(0.0) + tab_gap, minimum + tab_gap, *height); + let available = (*width - ends_room).max(0.0) + tab_gap; + let fit = if *mode == FitMode::ShrinkToLeast { + // Each tab shrinks no further than its own least; a tab fading out keeps its width. + let least: Vec = lane + .iter() + .map(|place| match *place { + Lane::Tab(at) => min.get(at).copied().unwrap_or(0.0), + Lane::Ghost(k) => ghosts.get(k).map_or(0.0, |ghost| ghost.width), + }) + .map(|width| width + tab_gap) + .collect(); + fit_to_least(&padded, &least, selected, available, *height) + } else { + let minimum = min.iter().copied().fold(0.0, f32::max); + mode.fit(&padded, selected, &held, available, minimum + tab_gap, *height) + }; *shown = vec![false; count]; *left = vec![*width; count]; *wide = vec![0.0; count]; @@ -499,9 +513,10 @@ impl TabRoles<'_, K> { /// /// The `kind` picks the rules: document and text tabs keep whole titles and send the rest to an overflow menu of /// every tab; panel tabs shrink before they overflow and the menu lists the hidden ones. Panel tabs shrink to their -/// first letters, clipped, or with `panel_shrink(PanelTabShrink::Ellipsis)` to a readable prefix ending in "…". The -/// shown tab is always visible. A tab dragged out of the strip and released where no other strip, dock or drop target -/// takes it is reported as `torn_off`. +/// first letters, clipped, beside the shown tab whole, or with `panel_shrink(PanelTabShrink::Ellipsis)` each to a +/// readable prefix ending in "…", the shown tab too, before any overflows. The shown tab is always visible. A tab +/// dragged out of the strip and released where no other strip, dock or drop target takes it is reported as +/// `torn_off`. #[derive(crate::contract::Component, crate::contract::Props)] #[component(collection, overlay, probe(TabStrip<'static, usize>))] pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> { @@ -521,7 +536,8 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + ' #[prop] panel_look: super::PanelTabLook, /// How far a panel strip's tabs ([`TabKind::Panel`]) shrink before they overflow: to their first letters, clipped - /// (the default), or to a readable prefix ending in an ellipsis ([`PanelTabShrink::Ellipsis`](super::PanelTabShrink)). + /// (the default), or each to a readable prefix ending in an ellipsis, the shown tab too + /// ([`PanelTabShrink::Ellipsis`](super::PanelTabShrink)). #[prop] panel_shrink: super::PanelTabShrink, /// The tab the host shows. A click, Space, Enter or a drop reports the new one in the output. @@ -1027,7 +1043,8 @@ impl Collection // Each end item is measured in this pass, with its label and icon only. let ends = self.trailing.iter().map(|end| end.fit_item(cx)).collect(); let look = cx.env::(); - let fitting = Fitting { selected, mode: self.kind.fit_mode_in(look), kept, ends, gap: cx.tokens.space.gap.inline, ghosts, departed }; + let mode = self.kind.fit_mode_for(look, self.panel_shrink); + let fitting = Fitting { selected, mode, kept, ends, gap: cx.tokens.space.gap.inline, ghosts, departed }; // Shrinking document tabs stand apart by the inline gap; the other kinds and looks touch. let tab_gap = if self.kind.shrinks_in(look) { cx.tokens.space.gap.inline } else { 0.0 }; StripLayout::new(count, Vec2::new(width, cx.tokens.size.bar.tab), tab_gap, fitting, self.report.clone(), cx.frame_ctx().clone()) diff --git a/crates/ui-widgets/tests/it/tabs.rs b/crates/ui-widgets/tests/it/tabs.rs index 67ca44149f..ce76d5c901 100644 --- a/crates/ui-widgets/tests/it/tabs.rs +++ b/crates/ui-widgets/tests/it/tabs.rs @@ -947,6 +947,68 @@ fn panel_tabs_shrinking_to_an_ellipsis_keep_a_readable_prefix_and_overflow_the_r assert!(labels.iter().any(|(_, clipped)| *clipped), "in {room}: the default strip clips a label at its tab's edge: {plain:?}"); } +/// A colour group of three short panels, as DesignCraft's dock lists Stroke, Color and Swatches. +const COLOUR_GROUP: [&str; 3] = ["Stroke", "Color", "Swatches"]; + +/// A panel strip `room` wide of `COLOUR_GROUP` under `PanelTabShrink::Ellipsis`, the last one, Swatches, shown. +fn colour_group(room: f32) -> Fixture { + let mut fixture = Fixture::new(move |ui| { + let source = keyed(&COLOUR_GROUP, |title: &&'static str| *title).with_text(|title| std::borrow::Cow::Borrowed(*title)); + let strip = TabStrip::new("Panels").kind(TabKind::Panel).panel_shrink(PanelTabShrink::Ellipsis).shown(COLOUR_GROUP[2]); + let _ = strip.show_items(ui, &source, &mut |key, _| Tab::new(*key)); + }); + fixture.room(egui::vec2(room, 100.0)).settle(); + fixture +} + +/// Under `PanelTabShrink::Ellipsis` every panel tab shrinks to its readable least before any tab overflows, the shown +/// tab too: in the narrowest room that shows Stroke, Color and Swatches, Swatches shown, nothing is in the overflow +/// menu, so no overflow button shows, and the shown Swatches tab reads its first characters and "…" like the others; +/// a point narrower a tab other than the shown one goes to the overflow menu. +#[trial] +fn panel_tabs_shrinking_to_an_ellipsis_all_reach_their_least_before_any_overflows() { + use craft_ui::primitives::TextRun; + let all_shown = |room: f32| shown_labels(&mut colour_group(room)).len() == COLOUR_GROUP.len(); + let (mut narrow, mut wide) = (40.0_f32, 400.0_f32); + assert!(!all_shown(narrow) && all_shown(wide), "the group overflows in {narrow} and fits whole in {wide}"); + while wide - narrow > 1.0 { + let middle = ((narrow + wide) / 2.0).floor(); + if all_shown(middle) { + wide = middle; + } else { + narrow = middle; + } + } + + let mut fixture = colour_group(wide); + assert!(fixture.by_label("More tabs").is_none(), "in {wide}, the narrowest room that shows every tab, nothing overflows"); + let shown = shown_labels(&mut fixture); + for (title, label) in &shown { + let (text, clipped) = label.as_ref().unwrap_or_else(|| panic!("in {wide}: the {title} tab paints its label")); + assert!(!clipped, "in {wide}: the {title} tab's label is not clipped at its edge: {text:?}"); + if text == title { + continue; + } + let kept = text.strip_suffix('…').unwrap_or_else(|| panic!("in {wide}: the {title} tab's cut label ends in an ellipsis: {text:?}")); + let readable: String = title.chars().take(TextRun::READABLE_CHARACTERS).collect(); + assert!( + title.starts_with(kept) && kept.starts_with(&readable), + "in {wide}: the {title} tab keeps {readable:?} before its ellipsis: {text:?}" + ); + } + let swatches = shown.iter().find_map(|(title, label)| (*title == COLOUR_GROUP[2]).then_some(label.as_ref())).flatten(); + assert!( + swatches.is_some_and(|(text, _)| text.ends_with('…')), + "in {wide}: the shown Swatches tab shrinks with the others before any tab overflows: {shown:?}" + ); + + let mut fixture = colour_group(narrow); + let fewer = shown_labels(&mut fixture); + assert!(fewer.len() < COLOUR_GROUP.len(), "in {narrow}, a point narrower, a tab overflows: {fewer:?}"); + assert!(fewer.iter().any(|(title, _)| *title == COLOUR_GROUP[2]), "in {narrow}: the shown tab stays: {fewer:?}"); + assert!(fixture.by_label("More tabs").is_some(), "in {narrow}: the overflow button shows"); +} + /// A strip places its tabs by their measure in its first frame: a panel strip too narrow for its tabs fits them by /// their measured widths and takes their measured height, in a frame that runs once and measures each tab's height /// at most twice (at its ideal width, and at the width the fit shrinks it to), and the strip and every tab have the diff --git a/docs/contract-api.md b/docs/contract-api.md index 30983c458b..3185badf2f 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -699,6 +699,7 @@ The fit rules: which tabs, bar items or titles stay in a strip and which go to a - `craft_behavior::fit::TabFit`: `pub struct TabFit { pub shown: Vec<(usize, f32)>, pub overflow: Vec, pub overflow_width: f32 }`. Tabs visible on a strip and tabs that need an overflow menu, all in original order. - `craft_behavior::fit::fit`: `pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32, keep_selected: bool) -> TabFit`. Fit tab widths into `available` points, shrinking the widest tabs first to a common cap. - `craft_behavior::fit::fit_items`: `pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit`. Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. +- `craft_behavior::fit::fit_to_least`: `pub fn fit_to_least(natural: &[f32], least: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit`. Fit tab widths into `available` points, each tab shrinking to its own `least` before any tab overflows. - `craft_behavior::fit::fit_whole`: `pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32, overflow_width: f32) -> TabFit`. Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. - `craft_behavior::fit::run_extent`: `pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) -> f64`. The length of the items marked in `shown`, with `gap` between neighbours of a section and `section_gap` between diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 6637bcf00c..18ac0a33a2 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -102,7 +102,7 @@ The host handles these `DockEvent`s: | `title_bar_docks` | on | Dragging a floating window's title bar onto a target docks the whole window. | | `close_menu_items`, `close_button` | on | Built-in Close items, and the close action on floating windows. | | `tab_close_buttons` | off | Close buttons on tabs (middle click closes too), for tabs that act as documents. | -| `tab_shrink` | `PanelTabShrink::FirstLetters` | How far panel tabs shrink before they overflow: to their first letters, clipped at the tab's edge, or with `PanelTabShrink::Ellipsis` to a readable prefix ending in "…" (`TextRun::READABLE_CHARACTERS` characters), the tabs that do not fit at that width going to the strip's overflow menu. | +| `tab_shrink` | `PanelTabShrink::FirstLetters` | How far panel tabs shrink before they overflow: to their first letters, clipped at the tab's edge, or with `PanelTabShrink::Ellipsis` each to a readable prefix ending in "…" (`TextRun::READABLE_CHARACTERS` characters), the shown tab too, the tabs that do not fit at that width going to the strip's overflow menu. | | `panel_menu_always` | off | Every group shows its panel menu button, with the dock's own rows when the shown panel has none. Off: only a panel with rows of its own (`DockPanels::panel_rows`) gets the button. | | `panel_menu_icon` | `more` | The panel menu button's icon; `menu` gives the three-line mark. | | `native_windows` | on | Floating windows open as OS windows where the window host opens them and reports their positions (not on Wayland) and `PanelSpec::allow_native` allows. | From 837bc646e0d40e374bef1cf5dff3d58fee148ddb Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 04:35:36 +0100 Subject: [PATCH 08/27] docs: regenerate contract-api.md --- docs/contract-api.md | 360 +++++++++++++++++++++++++++++++++---------- 1 file changed, 279 insertions(+), 81 deletions(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index 610b2674d0..061a81bccd 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -57,6 +57,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::ColumnWidth`: re-export of `craft_behavior::columns::ColumnWidth`. - `craft_behavior::CommandFlags`: re-export of `craft_behavior::command::CommandFlags`. - `craft_behavior::ControlMetrics`: re-export of `craft_behavior::sizing::ControlMetrics`. +- `craft_behavior::CopyKeys`: re-export of `craft_behavior::keys::CopyKeys`. - `craft_behavior::CountMark`: re-export of `craft_behavior::cursor::CountMark`. - `craft_behavior::Cursor`: re-export of `craft_behavior::cursor::Cursor`. - `craft_behavior::CursorBadge`: re-export of `craft_behavior::cursor::CursorBadge`. @@ -79,6 +80,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::Ended`: re-export of `craft_behavior::typing::Ended`. - `craft_behavior::EscapeRule`: re-export of `craft_behavior::typing::EscapeRule`. - `craft_behavior::Escaped`: re-export of `craft_behavior::typing::Escaped`. +- `craft_behavior::FRAME_STEP_MAX`: re-export of `craft_behavior::frame_step::FRAME_STEP_MAX`. - `craft_behavior::Flow`: re-export of `craft_behavior::flow::Flow`. - `craft_behavior::FreeLayout`: re-export of `craft_behavior::item_layout::FreeLayout`. - `craft_behavior::GESTURE_GAP`: re-export of `craft_behavior::wheel::GESTURE_GAP`. @@ -112,6 +114,8 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::MarqueeMode`: re-export of `craft_behavior::item_marquee::MarqueeMode`. - `craft_behavior::MarqueeSelect`: re-export of `craft_behavior::item_marquee::MarqueeSelect`. - `craft_behavior::Metrics`: re-export of `craft_behavior::sizing::Metrics`. +- `craft_behavior::MiddleButton`: re-export of `craft_behavior::middle_scroll::MiddleButton`. +- `craft_behavior::MiddleScroll`: re-export of `craft_behavior::middle_scroll::MiddleScroll`. - `craft_behavior::Mixed`: re-export of `craft_behavior::value::Mixed`. - `craft_behavior::Monitor`: re-export of `craft_behavior::monitor::Monitor`. - `craft_behavior::MonitorKey`: re-export of `craft_behavior::monitor::MonitorKey`. @@ -169,16 +173,19 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::PointerSample`: re-export of `craft_behavior::press::PointerSample`. - `craft_behavior::Positions`: `pub struct Positions`. The display order of a grid whose row keys are their positions (a sheet, a document table): `key(at) == at`, and - `pub const fn new(rows: u32) -> Self`. The order of `rows` rows. +- `craft_behavior::PressAside`: re-export of `craft_behavior::press::PressAside`. - `craft_behavior::PressCancel`: re-export of `craft_behavior::press::PressCancel`. - `craft_behavior::PressFocus`: re-export of `craft_behavior::focus::PressFocus`. - `craft_behavior::PressMachine`: re-export of `craft_behavior::press::PressMachine`. - `craft_behavior::PressPhase`: re-export of `craft_behavior::press::PressPhase`. +- `craft_behavior::PressPick`: re-export of `craft_behavior::press::PressPick`. - `craft_behavior::PressStart`: re-export of `craft_behavior::press::PressStart`. - `craft_behavior::PressState`: re-export of `craft_behavior::press::PressState`. - `craft_behavior::PressStep`: re-export of `craft_behavior::press::PressStep`. - `craft_behavior::Preview`: re-export of `craft_behavior::value::Preview`. - `craft_behavior::Proposal`: re-export of `craft_behavior::sizing::Proposal`. - `craft_behavior::Reader`: re-export of `craft_behavior::quantity::Reader`. +- `craft_behavior::ReorderKeys`: re-export of `craft_behavior::keys::ReorderKeys`. - `craft_behavior::ResolveFor`: re-export of `craft_behavior::hit::ResolveFor`. - `craft_behavior::RoleRule`: re-export of `craft_behavior::role_rule::RoleRule`. - `craft_behavior::Roving`: `pub struct Roving { pub shape: NavShape, pub wrap: bool, pub home_end: bool, pub page: Option, pub letters: Letters, pub arrows: Arrows, pub first_column: Option, pub hands_back: bool, pub no_lead: bool, pub keeps_lead_moves: bool }`. A roving group's rules: one Tab stop whose members take moves. @@ -195,13 +202,14 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `pub const fn state(&self, lead: Option) -> NavState`. The state a step over this group starts from, at `lead`, or from no lead when the group has none. - `pub const fn takes(&self, mv: NavMove, mods: MoveMods) -> bool`. Whether the group handles `mv` with `mods`: Page moves only with a page size and without `lead` (on a document - `craft_behavior::RowAt`: re-export of `craft_behavior::selection::RowAt`. -- `craft_behavior::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks }`. The ruler unit of one document axis: its size and its ticks. Rulers label their ticks with it; guides use it for - - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`. +- `craft_behavior::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; + - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. + - `pub const fn with_labels(mut self, labels: TickLabels) -> Self`. The units with their ticks written as `labels`. - `pub const fn pixels() -> Self`. Whole document pixels. - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` - `pub fn distance(&self, position: f64, zero: f64) -> f64`. The distance of `position` (document units) from `zero`, in ruler units. - - `pub fn label_decimals(&self, step: f64) -> usize`. The decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; a step of at + - `pub fn label_decimals(&self, step: f64) -> RangeInclusive`. The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; - `pub fn label_value(&self, value: f64, step: f64) -> f64`. The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: - `craft_behavior::SHEET_ZOOM`: re-export of `craft_behavior::item_layout::SHEET_ZOOM`. - `craft_behavior::ScopeKind`: re-export of `craft_behavior::focus::ScopeKind`. @@ -218,6 +226,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::SpanLayout`: re-export of `craft_behavior::item_layout::SpanLayout`. - `craft_behavior::SurroundingUnit`: re-export of `craft_behavior::editor::SurroundingUnit`. - `craft_behavior::TextPos`: re-export of `craft_behavior::intent::TextPos`. +- `craft_behavior::TickLabels`: `pub enum TickLabels { Distance, Signed }`. How a ruler writes the number at a labelled tick. - `craft_behavior::Ticks`: `pub enum Ticks { Decimal { whole: bool }, Custom(fn(f64) -> (f64, u32)) }`. How a ruler divides its unit at a zoom. - `pub const fn decimal(whole: bool) -> Self`. PhotoCraft's decimal steps; `whole` keeps the step a whole number of units without 2.5. - `craft_behavior::TileLayout`: re-export of `craft_behavior::item_layout::TileLayout`. @@ -238,6 +247,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::ViewPlace`: `pub struct ViewPlace { pub key: K, pub center: Point, pub zoom: f64 }`. Where a view stood: what it showed (`key`: a page, an artboard, a document) and the view's - `pub const fn new(key: K, center: Point, zoom: f64) -> Self`. The view of `key` centred on `center` at `zoom`. - `craft_behavior::Wheel`: re-export of `craft_behavior::wheel::Wheel`. +- `craft_behavior::WheelEase`: re-export of `craft_behavior::wheel::WheelEase`. - `craft_behavior::WheelFocus`: re-export of `craft_behavior::wheel::WheelFocus`. - `craft_behavior::WheelGesture`: re-export of `craft_behavior::wheel::WheelGesture`. - `craft_behavior::WheelNotch`: re-export of `craft_behavior::wheel::WheelNotch`. @@ -251,6 +261,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::ZoomScheme`: re-export of `craft_behavior::canvas::zoom::ZoomScheme`. - `craft_behavior::count_clicks`: re-export of `craft_behavior::press::count_clicks`. - `craft_behavior::decimals_for_step`: re-export of `craft_behavior::codec::decimals_for_step`. +- `craft_behavior::frame_step`: re-export of `craft_behavior::frame_step::frame_step`. - `craft_behavior::is_checkable`: re-export of `craft_behavior::role_rule::is_checkable`. - `craft_behavior::is_selectable`: re-export of `craft_behavior::role_rule::is_selectable`. - `craft_behavior::keyed`: re-export of `craft_behavior::item_source::keyed`. @@ -312,14 +323,16 @@ The transform a canvas body is shown through, and the canvas view with its zoom - `pub fn layer_transform(&self) -> Option`. The transform a canvas body is shown through when this view only scales and moves the document: unturned, - `pub fn axis_aligned(&self) -> bool`. Whether the rotation is a multiple of 90°, so document axes are screen axes. - `pub fn level(&self, zero: Point) -> CanvasView`. The view without its rotation, moved so it draws `zero` where this view does: the same -- `craft_behavior::canvas::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks }`. The ruler unit of one document axis: its size and its ticks. Rulers label their ticks with it; guides use it for - - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`. +- `craft_behavior::canvas::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; + - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. + - `pub const fn with_labels(mut self, labels: TickLabels) -> Self`. The units with their ticks written as `labels`. - `pub const fn pixels() -> Self`. Whole document pixels. - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` - `pub fn distance(&self, position: f64, zero: f64) -> f64`. The distance of `position` (document units) from `zero`, in ruler units. - - `pub fn label_decimals(&self, step: f64) -> usize`. The decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; a step of at + - `pub fn label_decimals(&self, step: f64) -> RangeInclusive`. The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; - `pub fn label_value(&self, value: f64, step: f64) -> f64`. The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: +- `craft_behavior::canvas::TickLabels`: `pub enum TickLabels { Distance, Signed }`. How a ruler writes the number at a labelled tick. - `craft_behavior::canvas::Ticks`: `pub enum Ticks { Decimal { whole: bool }, Custom(fn(f64) -> (f64, u32)) }`. How a ruler divides its unit at a zoom. - `pub const fn decimal(whole: bool) -> Self`. PhotoCraft's decimal steps; `whole` keeps the step a whole number of units without 2.5. - `craft_behavior::canvas::ViewHistory`: `pub struct ViewHistory`. The places a window jumped between, oldest first, with the one it shows now. The app records @@ -384,6 +397,8 @@ Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zo - `pub fn new(reader: Reader, decimals: usize) -> Self`. A codec reading with `reader` and writing at most `decimals` decimal places. - `pub fn fixed(mut self) -> Self`. The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown - `pub fn zoom_typing(mut self) -> Self`. The same codec with the typing rules of a zoom field: digits, `/` and the decimal separator, `a/b` as the + - `pub fn signed_zoom(mut self) -> Self`. Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign. + - `pub fn share_of_start(mut self) -> Self`. The same codec reading a lone percentage (`50%`, [`Reader::share`]) as that share of the value the edit - `pub fn at_most(mut self, decimals: usize) -> Self`. The same codec writing at most `decimals` decimal places. - `pub fn or_parse(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self`. The same codec with `parse` as a second reader: it runs when the reader rejects the text, so words of the - `pub fn widest(&self, range: &RangeInclusive) -> String`. The widest text the codec writes for a number in `range`: the longest of each end and the number one place of @@ -429,11 +444,11 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `craft_behavior::cursor::Cursor`: `pub enum Cursor { System(CursorIcon), Painted(PaintedCursor) }`. What a cursor request names. - `craft_behavior::cursor::CursorBadge`: `pub enum CursorBadge { Add, Subtract, Intersect, Copy, NotAllowed, Scissors, Close, Move, Arrow, Target, Continue, Count(CountMark), Corner }`. A mark beside a painted cursor. - `craft_behavior::cursor::CursorIcon`: `pub enum CursorIcon { Default, None, ContextMenu, Help, PointingHand, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, AllScroll, ResizeHorizontal, ResizeNeSw, ResizeNwSe, ResizeVertical, ResizeColumn, ResizeEast, ResizeSouthEast, ResizeSouth, ResizeSouthWest, ResizeWest, ResizeNorthWest, ResizeNorth, ResizeNorthEast, ZoomIn, ZoomOut }`. A system cursor: craft-behavior's copy of egui's set, converted by `runtime::egui::output`. -- `craft_behavior::cursor::CursorPriority`: `pub enum CursorPriority { Default, Tool, Hover, Part, DropTarget, Drag }`. Who asks, in ascending order of precedence. +- `craft_behavior::cursor::CursorPriority`: `pub enum CursorPriority { Default, Tool, Hover, Part, DropTarget, Drag, Hidden }`. Who asks, in ascending order of precedence. - `craft_behavior::cursor::IconId`: `pub struct IconId`. An icon's egui-free key (5.2), so plain data such as [`PaintedCursor::Tool`] names icons without egui. - `pub const fn new(name: &'static str) -> Self`. The icon named `name`. - `pub fn name(&self) -> &str`. The name. -- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool, toward: Option }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId }, Hidden, IBeam }`. A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush +- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool, toward: Option }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId, badge: Option }, Hidden, IBeam }`. A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush - `pub const CENTRE_ARM: f32`. The arm of the centre mark of a circle or an outline, in points. - `pub const fn circle(radius: f32) -> Self`. A circle of `radius` points, with no centre mark and no badge. - `pub fn outline(rings: Vec>) -> Self`. App shapes as closed rings, with no centre mark and no badge. @@ -448,6 +463,7 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `pub const fn arrow_toward(dir: Vec2) -> Self`. A solid arrow turned about its hotspot to point along `dir`. - `pub const fn path_text(start: bool, end: bool) -> Self`. An I-beam across the path with a triangle toward each grabbable side. - `pub const fn pointer_tool(pointer: PointerGlyph, icon: IconId) -> Self`. `pointer` with the tool's icon below and right of it. + - `pub const fn pointer_tool_badged(pointer: PointerGlyph, icon: IconId, badge: Option) -> Self`. `pointer` with the tool's icon below and right of it, and `badge` at the icon's lower right. - `pub const fn badged(base: CursorIcon, badge: CursorBadge) -> Self`. A system cursor with a mark. - `craft_behavior::cursor::PointerGlyph`: `pub enum PointerGlyph { Crosshair, Arrow }`. The pointer of a [`PaintedCursor::PointerTool`]. - `craft_behavior::cursor::pick`: `pub fn pick(requests: &[(Cursor, CursorPriority)]) -> Option<&Cursor>`. The winning request: the highest priority, the later request on a tie. @@ -655,7 +671,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `craft_behavior::edit_history::EditHistory`: `pub struct EditHistory`. Undo and redo stacks of a value `T`, at most 100 steps. A gesture is one step: `Begin` opens it, `Commit` closes it, - `pub fn new(now: &T) -> Self`. A history that starts at `now`. - `pub fn with_budget(mut self, max: usize, weight: fn(&T) -> usize) -> Self`. The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always - - `pub fn record(&mut self, event: &EditEvent)`. Takes in one event. Events of a gesture other than the open one are ignored. + - `pub fn record(&mut self, event: &EditEvent)`. Takes in one event. Events of a gesture other than the open one are ignored. A concrete - `pub fn is_open(&self) -> bool`. A gesture is open: a caller that restores a draft waits for it to end. - `pub fn step(&mut self, now: &mut T, step: Step) -> bool`. Steps `now` back or forward. False when there is nowhere to go. An open gesture is abandoned. - `pub fn take_back(&mut self) -> Option`. Takes back the newest undo step without a redo entry, for an edit that was refused: `settled` returns to the @@ -689,7 +705,7 @@ When a component's remembered state is due for eviction. ## `craft_behavior::fit` -The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and +The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`], - `craft_behavior::fit::Fit`: `pub struct Fit { pub shown: Vec, pub overflow: Vec, pub short: Vec }`. Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. - `craft_behavior::fit::FitItem`: `pub struct FitItem { pub extent: f32, pub section: u16, pub keep: FitKeep, pub short: Option }`. One item as the fit rule sees it: its extent along the strip, its section and whether it may overflow. @@ -749,6 +765,13 @@ Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the f - `craft_behavior::focus::key_owner`: `pub fn key_owner(blocked: bool, present: &[OwnerClass]) -> KeyOwner`. Key ownership, in the order blocked, `Menu`, `Recorder`, `Dialog`, `Text`, `Popup` and `PassivePopup`, - `craft_behavior::focus::route_escapes`: `pub fn route_escapes(escapes: usize, press_captured: bool) -> EscapeRouting`. Routes `escapes` Escapes of one pass: with a press captured, the first one is the press's (`escape_step`'s +## `craft_behavior::frame_step` + +The step of one pass of motion: a Hand glide, a held Zoom press and an autoscroll integrate over it. + +- `craft_behavior::frame_step::FRAME_STEP_MAX`: `pub const FRAME_STEP_MAX: f64`. The longest step motion integrates, in seconds, so a stalled pass never jumps the view. +- `craft_behavior::frame_step::frame_step`: `pub fn frame_step(dt: f64) -> f64`. The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the + ## `craft_behavior::geometry` Pure canvas geometry in document units: the transform box ([`quad`]), snapping ([`snap`]), the @@ -757,6 +780,7 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::AspectHold`: re-export of `craft_behavior::geometry::crop::AspectHold`. - `craft_behavior::geometry::BoxAllow`: re-export of `craft_behavior::geometry::quad::BoxAllow`. - `craft_behavior::geometry::BoxDrag`: re-export of `craft_behavior::geometry::quad::BoxDrag`. +- `craft_behavior::geometry::BoxHandles`: re-export of `craft_behavior::geometry::quad::BoxHandles`. - `craft_behavior::geometry::BoxPart`: re-export of `craft_behavior::geometry::quad::BoxPart`. - `craft_behavior::geometry::BoxRules`: re-export of `craft_behavior::geometry::quad::BoxRules`. - `craft_behavior::geometry::BoxState`: re-export of `craft_behavior::geometry::quad::BoxState`. @@ -831,7 +855,7 @@ The crop frame's pure geometry: the box, where a press lands on it, what each ge - `pub fn swapped(&self) -> Self`. Width and height swapped about the centre, the angle kept (X). - `pub fn nudged(&self, part: BoxPart, by: Vec2, ratio: Option) -> Self`. The frame after an arrow key moves `part` by `by`, as a plain drag of the part would, with `ratio` held. - `pub fn crop_size(&self) -> Option<(f64, f64)>`. The size Enter would crop to: the frame's own width and height in whole document units, at least 1; `None` - - `pub fn size_ok(&self) -> bool`. Whether both sides are at least one document unit. + - `pub fn size_ok(&self, min: f64) -> bool`. Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is - `pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option`. [`resized`](Self::resized) for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the - `pub fn turned_to(&self, grab: f64, to: Point, step: Option, image: bool) -> Self`. The frame turned from this one's angle by the pointer's sweep about the centre, from direction `grab` @@ -968,15 +992,19 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub const fn new(rotate: bool, skew: bool, distort: bool) -> Self`. What the content allows: turning, skewing and distorting. - `pub const fn with_warp(mut self, warp: bool) -> Self`. Whether the content allows warping. - `craft_behavior::geometry::quad::BoxDrag`: `pub enum BoxDrag { Move, Pivot, Rotate, Scale, Distort, Perspective, Skew, SlideCorner }`. What a drag of a box part does ([`BoxRules::drag_kind`]). +- `craft_behavior::geometry::quad::BoxHandles`: `pub enum BoxHandles { All, Corners, Sides }`. Which handles of a box are shown. - `craft_behavior::geometry::quad::BoxPart`: `pub enum BoxPart { Corner(u8), Edge(u8), Pivot, Inside, Outside }`. A part of a box under the pointer or picked from the keyboard. Edge `k` joins corners `k` and - `pub const fn index(self) -> u64`. The number a part is keyed by in a canvas control's part keys: 0 inside or outside, 1 to 4 the corners, 5 to - `pub const fn from_index(index: u64) -> Option`. The part keyed by `index`: the inverse of [`index`](Self::index), with 0 the inside. -- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64, pub min_side: f64 }`. How drags change a box. +- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64, pub min_side: f64, pub handles: BoxHandles, pub edge_band: f32 }`. How drags change a box. - `pub fn in_mode(mode: TransformMode) -> BoxRules`. The rules of `mode` with the default scale rule, a linked aspect, everything allowed and - `pub fn with_scale(mut self, scale: ScaleRule) -> BoxRules`. The rules with `scale` as the plain corner and edge drag rule. - `pub fn with_aspect_linked(mut self, linked: bool) -> BoxRules`. The rules with the options bar's aspect link on or off. - `pub fn with_allow(mut self, allow: BoxAllow) -> BoxRules`. The rules with `allow` as what the content permits. - `pub fn with_min_side(mut self, side: f64) -> BoxRules`. The rules with `side` as the minimum side of a scaled box, in document units. + - `pub fn with_handles(mut self, handles: BoxHandles) -> BoxRules`. The rules with `handles` as the handles the box shows. + - `pub fn with_edge_band(mut self, points: f32) -> BoxRules`. The rules with each side grabbed within `points` of its line ([`edge_band`](Self::edge_band)). + - `pub fn shows(&self, part: BoxPart) -> bool`. Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides - `pub fn effective_mode(&self) -> TransformMode`. The mode drags follow: a mode the content refuses scales as Free Transform does. - `pub fn allows(&self, part: BoxPart) -> bool`. Whether a drag of `part` changes the box: in Distort only the corners, the inside and the - `pub fn drag_kind(&self, part: BoxPart, mods: Mods) -> Option`. What a drag of `part` with `mods` held (as the host has them, before @@ -1006,7 +1034,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `craft_behavior::geometry::quad::Parts`: `pub struct Parts { pub w: f64, pub h: f64, pub angle: f64, pub skew_h: f64, pub skew_v: f64 }`. A box read as the options bar shows it: the starting rect scaled by `w` and `h`, skewed by - `pub const fn new(w: f64, h: f64, angle: f64, skew_h: f64, skew_v: f64) -> Self`. The readings: scale factors `w` and `h`, the `angle` in degrees and the two skews in degrees. - `craft_behavior::geometry::quad::SKEW_LIMIT`: `pub const SKEW_LIMIT: f64`. The skew fields' reach in degrees: a skew of ±90° would flatten the box (PhotoCraft's). -- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, Shape, Corners }`. What a plain corner or edge drag does. +- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, LargerAxis, Shape, Corners }`. What a plain corner or edge drag does. - `craft_behavior::geometry::quad::TransformMode`: `pub enum TransformMode { Free, Rotate, Skew, Distort, Perspective }`. Edit › Transform's modes. - `craft_behavior::geometry::quad::bisector`: `pub fn bisector(screen: &BoxState, i: usize) -> emath::Vec2`. Corner `i` of `screen`'s unit bisector, pointing into the box; zero for a collapsed corner. The - `craft_behavior::geometry::quad::drag`: `pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState`. The box after dragging `part` from `from` to `to` (document points) with `mods` held, from the @@ -1071,7 +1099,7 @@ The `Grid` cursor: columns resolved from last pass's measurements, and the cell - `craft_behavior::grid::GridCursor`: `pub struct GridCursor`. Hands out the cells of one `Grid` pass, row-major. Cells are placed from `last` pass's measurements; this - `pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A - `pub fn sized_by_content(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor for a measuring run under a body sized from its content: each `Fill` column of `columns` is placed - - `pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self`. A cursor for the sweep that asks each column for its least: every column but a `Fixed` one is placed as a + - `pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self`. A cursor for the sweep that asks each column for its least: the cells of every `Content` and `Fill` column - `pub fn each_alone(mut self) -> Self`. The cursor with each `Content` column measuring in the room the other columns leave at their least, whatever - `pub fn short(&self) -> bool`. Whether the columns, as this sweep measured them, do not fit beside each other: the columns that do not share - `pub fn cell(&mut self, size: Vec2) -> Rect`. The cell of the next child, whose measured size is `size`. @@ -1108,15 +1136,16 @@ Hit shapes, their priority and the arena's resolve rule (8.3). - `pub fn hit(&self, point: Pos2) -> bool`. Whether `point` hits the shape. - `craft_behavior::hit::LINE_REACH`: `pub const LINE_REACH: f32`. How far from a line a point still hits it, in points. - `craft_behavior::hit::ResolveFor`: `pub enum ResolveFor { Press, Hover }`. What a resolution is for. -- `craft_behavior::hit::Shape`: `pub struct Shape { pub shape: HitShape, pub sense: Sense, pub owner: O, pub part: Option, pub priority: HitPriority, pub position: u32, pub local: bool, pub min_across: f32 }`. One registered shape of the shape record: a root's, a member's or a part's. +- `craft_behavior::hit::Shape`: `pub struct Shape { pub shape: HitShape, pub sense: Sense, pub owner: O, pub part: Option, pub priority: HitPriority, pub position: u32, pub local: bool, pub min_across: f32, pub stacking: u32, pub drag_to_root: bool }`. One registered shape of the shape record: a root's, a member's or a part's. - `pub fn translated(&self, by: Vec2) -> Self`. The shape moved by `by`. - `pub fn snapped(&self, to: &Shape, within: f32) -> Self`. The shape with its geometry and least size across taken from `to`'s where they lie within `within` points - `pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self`. A shape of `owner` at stack `position`. - `pub const fn min_across(mut self, across: f32) -> Self`. The hit area is at least `across` points wide and high. + - `pub const fn stacking(mut self, order: u32) -> Self`. The shape's stacking order among shapes of its priority: the higher order wins before the nearest centre. - `pub const fn local(mut self, local: bool) -> Self`. The shape lies in the body layer's space. - `pub fn hits(&self, point: Pos2) -> bool`. Whether `point` lies in the hit area: the shape grown to be at least its `min_across` wide and high. The -- `craft_behavior::hit::Winner`: `pub struct Winner { pub index: usize, pub owner: O, pub part: Option, pub sense: Sense, pub local: bool }`. The shape that won a resolution. -- `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last +- `craft_behavior::hit::Winner`: `pub struct Winner { pub index: usize, pub owner: O, pub part: Option, pub sense: Sense, pub local: bool, pub drag_to_root: bool }`. The shape that won a resolution. +- `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest - `craft_behavior::hit::resolve_mapped`: `pub fn resolve_mapped(shapes: &[Shape], point: Pos2, what: ResolveFor, to_local: impl Fn(Pos2) -> Pos2) -> Option>`. [`resolve`] where shapes with `local` set are tested at `to_local(point)`. ## `craft_behavior::hold_repeat` @@ -1169,6 +1198,7 @@ Item geometry: where each item of a collection sits for a scroll offset and view - `fn visible(&self, offset: ScrollPos, view: Vec2, out: &mut Vec)`. The indices of the items that intersect a viewport of size `view` scrolled to `offset`, ascending. - `fn rect(&self, at: usize, offset: ScrollPos) -> Rect`. The rect of item `at`. - `fn hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item under `point`. + - `fn drop_hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item whose drop area contains `point`. Layouts with visible gaps can include those in a drop area while - `fn nav(&self) -> NavShape`. How arrow keys move through the items. - `fn row_len(&self, _row: usize) -> Option`. `NavShape::RaggedGrid`: the number of items in `row`, rows holding consecutive items and a run of hidden items - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows @@ -1243,6 +1273,7 @@ Where a collection's items come from: the data traits and the one way to show a - `fn open(&self, _at: usize) -> bool`. Whether the children of entry `at` show. - `fn is_section(&self, _at: usize) -> bool`. Whether entry `at` is a section header, which navigation skips. - `fn section_stop(&self, _at: usize) -> bool`. Whether section `at` is a stop of navigation: it holds the lead, takes Enter, the context-menu key and a + - `fn selectable_section(&self, _at: usize) -> bool`. Whether a section stop also represents an item that keyboard selection can pick or extend over. - `fn section_stops_before(&self, _at: usize) -> usize`. How many section stops (`section_stop`) come before entry `at`. They are not members of the set of items, so - `fn enabled(&self, _at: usize) -> bool`. Whether entry `at` can take the lead. - `fn text(&self, _at: usize) -> Option>`. The text type-ahead matches entry `at` against. @@ -1266,13 +1297,16 @@ Where a collection's items come from: the data traits and the one way to show a The key table (spec 9.2): the one place that maps a key press to an intent and modifiers to `MoveMods`. +- `craft_behavior::keys::ALT_ARROW_KEYS`: `pub const ALT_ARROW_KEYS: [Chord; 4]`. The four Alt+arrow chords of `ReorderKeys::AltArrows`. +- `craft_behavior::keys::CopyKeys`: `pub enum CopyKeys { Alt, Platform }`. Which held key turns a drag into a copy over a target. - `craft_behavior::keys::DropOperation`: `pub enum DropOperation { Move, Copy, Link }`. What a drop of a dragged payload does with it. -- `craft_behavior::keys::KeyRole`: `pub struct KeyRole { pub resettable: bool, pub space: bool, pub multi_select: bool, pub reorderable: bool, pub rename: bool, pub pages: bool, pub nudge: bool, pub document: bool, pub type_ahead: bool, pub digits: bool, pub value: bool, pub text: bool, pub moves: bool, pub deletes: bool, pub stacked: bool, pub owner_arrows: bool, pub home_row: usize }`. What the focused stop is, as far as the table's rows differ. +- `craft_behavior::keys::KeyRole`: `pub struct KeyRole { pub resettable: bool, pub space: bool, pub multi_select: bool, pub reorderable: Option, pub reorder_axis: Axis, pub rename: bool, pub pages: bool, pub nudge: bool, pub document: bool, pub type_ahead: bool, pub digits: bool, pub value: bool, pub text: bool, pub moves: bool, pub deletes: bool, pub stacked: bool, pub owner_arrows: bool, pub home_row: usize }`. What the focused stop is, as far as the table's rows differ. - `pub const fn new() -> KeyRole`. A role with no special rows. - `pub const fn resettable(mut self, on: bool) -> Self`. Delete resets the control. - `pub const fn space(mut self, on: bool) -> Self`. Space is the component's own intent. - `pub const fn multi_select(mut self, on: bool) -> Self`. Ctrl+Space toggles the lead's pick. - - `pub const fn reorderable(mut self, on: bool) -> Self`. The stacking keys move the selected items. + - `pub const fn reorderable(mut self, keys: Option) -> Self`. The scheme's keys move the selected items; `None` when the stop does not reorder. + - `pub const fn reorder_axis(mut self, axis: Axis) -> Self`. The axis the order is laid out along. - `pub const fn rename(mut self, on: bool) -> Self`. Rename has its key. - `pub const fn pages(mut self, on: bool) -> Self`. Ctrl+Tab switches pages. - `pub const fn nudge(mut self, on: bool) -> Self`. Arrows are nudges, not moves. @@ -1287,9 +1321,10 @@ The key table (spec 9.2): the one place that maps a key press to an intent and m - `pub const fn home_row(mut self, row: usize) -> Self`. Ctrl or Cmd with Home goes to item `row`. - `pub const fn text(mut self, on: bool) -> Self`. The stop is a text part. - `craft_behavior::keys::REORDER_KEYS`: `pub const REORDER_KEYS: [Chord; 6]`. The stacking keys (Photoshop's Bring Forward and Send Backward): Cmd+] moves the selected items one place toward the -- `craft_behavior::keys::drop_operation`: `pub fn drop_operation(os: Os, mods: Mods) -> DropOperation`. The drop operation the held modifiers pick. +- `craft_behavior::keys::ReorderKeys`: `pub enum ReorderKeys { Stacking, AltArrows }`. The named key scheme of a reorderable collection. +- `craft_behavior::keys::drop_operation`: `pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation`. The drop operation the held modifiers pick over a target that copies with `copy`. Link is Ctrl+Shift, Cmd+Option on - `craft_behavior::keys::intent`: `pub fn intent(os: Os, key: Key, mods: Mods, role: KeyRole) -> Option`. The intent a key press has for a stop of `role`, if any. `Enter` and `Space` as activation are not rows: -- `craft_behavior::keys::reorder_intent`: `pub fn reorder_intent(key: Key, mods: Mods) -> Option`. The `Intent::MoveItem` a stacking key asks for, `None` for any other press. +- `craft_behavior::keys::reorder_intent`: `pub fn reorder_intent(key: Key, mods: Mods, keys: ReorderKeys, axis: Axis) -> Option`. The `Intent::MoveItem` a key of the scheme `keys` asks for in an order laid out along `axis`, `None` for any other - `craft_behavior::keys::split_digits`: `pub fn split_digits(text: &str) -> (Vec, String)`. Typed `text` split for a role that takes digits: the ASCII digits it holds, in order, and the text without them. - `craft_behavior::keys::toward_end`: `pub fn toward_end(front: bool, axis: Axis) -> bool`. Whether a move toward the front goes toward the end of an order laid out along `axis`. The front of a vertical @@ -1313,6 +1348,20 @@ The tolerance rule of layout memory: when a measured size asks for a discard pas - `craft_behavior::layout_memory::measure_tolerance`: `pub fn measure_tolerance(pixels_per_point: f32) -> f32`. The tolerance in points under which a measured size equals the one placement used: half a physical pixel. - `craft_behavior::layout_memory::measured_change_asks_for_discard`: `pub fn measured_change_asks_for_discard(recorded: Option, real: Vec2, changed_last_frame: bool, tolerance: f32) -> bool`. Whether a measured size asks for a discard pass. `recorded` is the size placement used this frame +## `craft_behavior::middle_scroll` + +The middle button's auto-scroll latch: the gesture state of one middle press. + +- `craft_behavior::middle_scroll::MiddleButton`: `pub enum MiddleButton { Pan, AutoScroll }`. What the middle button does over a scroll area. +- `craft_behavior::middle_scroll::MiddleScroll`: `pub struct MiddleScroll`. The auto-scroll latch of one middle press. + - `pub fn press(&mut self, at: Pos2, inside: bool)`. A middle press: inside the scroll area it latches at `at`; a second press ends the latch. + - `pub fn release(&mut self)`. The button went up: after two held passes with the pointer past the dead zone the latch ends; an earlier + - `pub fn swallows(&mut self, phase: PressPhase) -> bool`. Whether a press's `phase` belongs to the press that ended a latch and so reaches nothing else: true for the + - `pub fn cancel(&mut self)`. Ends the latch. + - `pub fn step(&mut self, pointer: Pos2, held: bool, dt: f64, invert: bool) -> Vec2`. One pass: with this pass's `pointer` and `held` state it counts the held passes past the 15 pt dead zone and + - `pub fn anchor(&self) -> Option`. Where the latch is anchored, `None` when there is none. + - `pub fn active(&self) -> bool`. Whether a latch is active. + ## `craft_behavior::monitor` The connected monitors, as every window placement reads them. @@ -1492,6 +1541,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `craft_behavior::press::PointerSample`: `pub struct PointerSample { pub pressure: f32, pub tilt: [f32; 2], pub rotation: f32, pub eraser: bool, pub wheel: Option }`. Pressure and tilt of the current contact. - `pub const fn new(pressure: f32) -> Self`. A sample with no tilt or rotation. - `pub fn sanitized(self) -> Self`. The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value +- `craft_behavior::press::PressAside`: `pub struct PressAside { pub target: T, pub start: PressStart, pub pos: Pos2 }`. A secondary press made and released while a primary press was open ([`PressStep::aside`]). Its target is the one - `craft_behavior::press::PressCancel`: `pub enum PressCancel { Escape, FocusLost, Disabled, Removed, Host, Gesture }`. Why a captured press ended without a release. - `craft_behavior::press::PressMachine`: `pub struct PressMachine`. The press lifecycle of one root: the press winner it picked, kept until release or cancel. - `pub const fn new() -> Self`. A machine with no press. @@ -1501,7 +1551,8 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn start(&self) -> Option`. The press the open press began as. - `pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart)`. Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next - `pub fn release_held(&self) -> bool`. Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may - - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option<(T, Sense)>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None` + - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed + - `pub fn hand_over(&mut self, target: T, sense: Sense) -> Option>`. Makes `target` the open press's target in the pass that reported `passes`, dragging from the same - `craft_behavior::press::PressPhase`: `pub enum PressPhase { Idle, Hover, Down { start: PressStart }, Held { start: PressStart, pos: Pos2 }, DragStart { start: PressStart, pos: Pos2 }, Drag { start: PressStart, pos: Pos2, delta: Vec2 }, Release { start: PressStart, pos: Pos2, click: bool }, Cancel { start: PressStart, reason: PressCancel } }`. One part's press state in one pass. - `pub const fn is_press(&self) -> bool`. A press is in progress or just ended: not `Idle` or `Hover`. - `pub const fn start(&self) -> Option`. The press the phase belongs to. @@ -1509,16 +1560,20 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn is_drag(&self) -> bool`. Whether the phase is a drag in progress. - `pub const fn is_click(&self) -> bool`. Whether the phase is a click: a release within slop. - `pub fn mapped(self, point: impl Fn(Pos2) -> Pos2, delta: impl Fn(Vec2) -> Vec2) -> PressPhase`. The phase with its positions mapped by `point` and its drag delta by `delta`, for a part whose space +- `craft_behavior::press::PressPick`: `pub struct PressPick { pub target: T, pub sense: Sense, pub passed: bool }`. The press winner a root picks at a press position, as [`PressMachine::step`]'s `pick` returns it. + - `pub fn new(target: T, sense: Sense) -> Self`. `target`, sensing `sense`, takes the press. + - `pub fn passed(mut self) -> Self`. The press's click went to a shape above that passes its drag to this target. - `craft_behavior::press::PressStart`: `pub struct PressStart { pub origin: Pos2, pub button: PointerButton, pub time: f64, pub clicks: u32 }`. Where and when a press began. - `pub const fn new(origin: Pos2, button: PointerButton, time: f64, clicks: u32) -> Self`. A press of `button` at `origin`. -- `craft_behavior::press::PressState`: `pub struct PressState { pub phase: PressPhase, pub mods: Mods, pub sample: Option, pub captured: bool }`. A part's phase, the modifiers held, the pen sample and whether it holds the pointer. +- `craft_behavior::press::PressState`: `pub struct PressState { pub phase: PressPhase, pub mods: Mods, pub sample: Option, pub captured: bool, pub context: Option }`. A part's phase, the modifiers held, the pen sample and whether it holds the pointer. - `pub const IDLE: PressState`. A part with no press history. - - `pub const fn new(phase: PressPhase) -> Self`. A state in `phase` with no modifiers, sample or capture. + - `pub const fn new(phase: PressPhase) -> Self`. A state in `phase` with no modifiers, sample, capture or aside context request. + - `pub const fn context(mut self, at: Option) -> Self`. The aside secondary press that came up on the part at `at` in this pass. - `pub const fn mods(mut self, mods: Mods) -> Self`. The modifiers held. - `pub const fn sample(mut self, sample: Option) -> Self`. The pen sample of the contact. - `pub const fn captured(mut self, captured: bool) -> Self`. Whether a drag holds the pointer. - `pub const fn double_pressed(&self) -> bool`. Whether the phase is the `Down` of the second press of a double click: true once, false while the button is -- `craft_behavior::press::PressStep`: `pub struct PressStep { pub target: Option, pub phase: Option, pub dragging: bool, pub activated: Option }`. What one pass did to the press. +- `craft_behavior::press::PressStep`: `pub struct PressStep { pub target: Option, pub phase: Option, pub dragging: bool, pub activated: Option, pub passes: Option, pub aside: Option> }`. What one pass did to the press. - `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f64, mods: Mods, slop: f32) -> u32`. The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, ## `craft_behavior::quantity` @@ -1536,6 +1591,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn decimal_separator(&self) -> char`. The decimal separator the reader reads and writes. - `pub fn read(&self, text: &str, start: Option) -> Result`. The value of `text`. `start` is the value relative input applies to. - `pub fn read_tagged(&self, text: &str, start: Option) -> Result<(f64, Option), NotAValue>`. The value of `text` and the tag of the unit its last quantity named (`None` for a bare number or an untagged + - `pub fn share(&self, text: &str) -> Option`. The fraction a lone percentage writes (`50%` is 0.5): a number and `%`, with no sign, unit or operator; - `craft_behavior::quantity::is_unit_spelling`: `pub fn is_unit_spelling(spelling: &str) -> bool`. Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can ## `craft_behavior::role_rule` @@ -1777,7 +1833,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. - `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2 }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. - `pub const fn touch_zoom(mut self, zoom: f32) -> Self`. The same gesture with the two-finger touch zoom factor `zoom`. @@ -1786,6 +1842,11 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli - `pub const fn touch_pan(mut self, pan: Vec2) -> Self`. The same gesture with the two-finger touch movement `pan`, in points. - `pub const fn source(mut self, source: WheelSource) -> Self`. The same gesture from `source`. - `pub const fn at(mut self, at: Pos2) -> Self`. The same gesture with the pointer at `at`. +- `craft_behavior::wheel::WheelEase`: `pub struct WheelEase`. The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. + - `pub fn feed(&mut self, pan: Vec2, now: f64)`. Adds the line pan `pan` of this pass, at time `now`, to the owed motion; a burst of notches under 0.08 s apart + - `pub fn cancel_axis(&mut self, x: bool, y: bool)`. Drops the owed motion on the axes marked. + - `pub fn step(&mut self, now: f64) -> Vec2`. The step this pass pays at time `now`: `1 − 0.1^(dt/0.1)` of the owed motion, with `dt` since the last paid pass. + - `pub fn owes(&self) -> bool`. Whether motion is still owed. - `craft_behavior::wheel::WheelFocus`: `pub struct WheelFocus { pub taker: Option, pub app_field: bool, pub by_position: bool }`. Who holds key focus, as the split reads it. - `pub const fn new(taker: Option) -> Self`. Focus on `taker`, or on nothing that takes the wheel. - `pub const fn app_field(mut self, on: bool) -> Self`. The same focus, in a text field the app drew itself when `on`. @@ -1851,7 +1912,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn measures_items(&self) -> bool`. Whether the layout sizes its items from their own measure: the items step measures every item at its ideal - `fn dress_inputs(&self) -> u64`. What `dress` reads of the collection, hashed: a kept measure of the items serves only while it is the same. - `fn ideal_width(&self, _item: Option, _rows: usize, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of - - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. + - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env, _kept: Option<&Self::Key>,) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. `kept` is the - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this - `fn rename_editor(&mut self, _ui: &mut Ui, _draft: Bind<'_, String>, _label: Rect, _name: &str) -> Option>`. The rename editor at `label`: the label rect the renaming item reports (`ItemOutput::label_rect`), else its row. - `fn hosts_header(&self, _column: &ColumnKey) -> bool`. Whether the collection hosts a component in the header cell of `column`: the header then calls `header_cell` @@ -1862,7 +1923,8 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn accepts(&self, _drag: &ListDrag, _over: Option<&Self::Key>, _insert: usize) -> bool`. Whether the collection's own dragged items may land before `insert` (a position of the display order, `over` is - `fn drops(&self) -> &[DropKind<'_, Self::Key>]`. What the collection takes from drags that did not start in it, in order: the first kind that takes the drag's - `fn edge_press(&self) -> Option<&EdgePress<'_, Self::Key>>`. The press on the line between two adjacent rows the collection takes, reported as - - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): it reports + - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): the items step reports + - `fn zoom_anchor(&self, _wheel: Option) -> Option`. The point whose row stays in place across a zoom step this collection takes in the current pass, in screen - `fn empty_height(&self, width: f32, ui: &Ui, cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. The - `fn empty(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>)`. The empty state at the rect the item step placed. The default shows `CollectionProps::empty`. - `craft_ui::contract::Component`: `pub trait Component: Meta + Sized`. The core trait: every UI type is a `Component`. @@ -1874,6 +1936,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts - `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except - `const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy`. The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its + - `fn focus_scope(&self) -> crate::runtime::focus::FocusPolicy`. The focus scope this instance runs in. The default is `FOCUS_SCOPE`; a component whose scope is a choice of its - `const KEYS: crate::runtime::focus::KeyUse`. Keys the focused component keeps from egui and the shortcut dispatcher. - `fn keys(&self) -> crate::runtime::focus::KeyUse`. The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends - `const SHOWS_LABEL: bool`. Whether the component paints its label as visible text. `false` for a face that shows only an icon or a @@ -1887,6 +1950,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn shows_label(&self) -> bool`. Whether this instance paints its label as visible text; `SHOWS_LABEL` unless an instance prop decides, as - `fn label_detail(&self) -> Option`. The muted line a `LABELLED_AFTER` control's label shows after its text (`SideLabel::detail`), as a radio's - `fn paint_outset(_tokens: &crate::style::UiTokens) -> f32`. How far the component paints outside its rect by design, in points (a graph node's ports sit on its edge). + - `fn default_variant(_env: &crate::runtime::env::Env) -> Option`. The variant an instance that asks for none takes in `env`; `None` takes the style's first. A variant the caller - `fn style(cx: &StyleCx<'_>, key: Self::StyleKey) -> Self::Style`. Pure function of the resolved context and the key. - `fn padding(&self, _rect: Rect, style: &Self::Style) -> craft_behavior::Insets`. The insets from `rect` to the content rect where the component is shown: the style's padding. A component - `fn measure(&mut self, _cx: &MeasureCx<'_, Self>) -> Vec2`. Content size only; the pipeline adds padding and minimum size. @@ -1993,6 +2057,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn take_pick_answer(&self, ticket: craft_host::PickId) -> Option`. The host file service's answer to the picker `ticket`, taken once. A measuring run gets none and leaves - `pub fn is_exiting(&self) -> bool`. Whether the container has closed and its body only stays on screen while it fades out. `is_open` reads true - `pub fn field_message(&self) -> Option<(Message, craft_theme::variant::Tone)>`. The validity message of the first control in the container's label scope, recorded last frame, with the + - `pub fn moving(&self) -> bool`. Whether a drag of the container's move band (`DragBand::Move`) moves its layer in this pass, from the pass the - `pub fn is_open(&self) -> bool`. Whether the body is open. - `pub fn open(&mut self) -> &mut bool`. The open state: a title row's disclosure binds to it, and step 15 writes a change to its owner. - `pub fn gate(&mut self) -> Option<&mut bool>`. The gate's shown copy, for a container whose value is a bool: a title row's check box binds to it, and @@ -2015,20 +2080,26 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. - `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. +- `craft_ui::contract::CaptionColumn`: `pub struct CaptionColumn`. Whether the beside captions of a [`LabelScheme::Inline`] form share one column. Off (the default), each caption is + - `pub const SHARED: CaptionColumn`. The captions share one column. + - `pub const OWN: CaptionColumn`. Each caption is as wide as its own text (the default). + - `pub const fn shared(self) -> bool`. Whether the captions share one column. +- `craft_ui::contract::CaptionInk`: `pub enum CaptionInk { Muted, Normal }`. The ink of a side label's name, other than a link's ([`LinkLabelInk`]) and the text after a check box or a radio, - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. - `pub const fn new() -> Self`. A collapsible body that starts open, animated. - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. -- `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection { change: SelectionChange, by: LeadSource, mods: craft_keymap::Mods }, Picked { key: K, mods: craft_keymap::Mods }, LeadMoved { key: K, by: LeadSource }, Activate(K), Rested(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option

+ Send + Sync + 'static) -> Self`. A row drag carries `map` of it, for the drop targets of type `P`; a row the map gives `None` for does not drag - `pub fn carry(mut self, payload: DragPayload) -> Self`. A row drag carries `payload` of it too, beside the payloads given before: a host adds its own payload type to a - - `pub const fn drag_count(mut self, count: Counted) -> Self`. The drag badge reads `count` for the number of dragged items. + - `pub const fn drag_preview(mut self, preview: RowPreview) -> Self`. What a row drag shows while it runs (a badge by the pointer by default). + - `pub const fn drag_count(mut self, count: Counted) -> Self`. A row drag's preview reads `count` for the number of dragged items. - `pub const fn pages(mut self, on: bool) -> Self`. The items are pages (`CollectionProps::pages`). - `pub fn rename(mut self, on: bool) -> Self`. Rename runs through the collection's editor. - `pub fn rename_column(mut self, column: ColumnKey) -> Self`. A double click on `column` of a renamable item (`rename`, `Collection::can_rename`) opens its rename editor; the @@ -2052,17 +2123,22 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn item_keys(mut self, keys: ItemKeys) -> Self`. Who takes the arrow keys while the collection has the key focus. - `pub const fn marquee(mut self, on: bool) -> Self`. A drag from empty space selects with a marquee. - `pub const fn deletable(mut self, on: bool) -> Self`. Delete and Backspace at the lead report the items to delete (`CollectionEvent::Delete`). + - `pub const fn delete_target(mut self, target: DeleteTarget) -> Self`. Sets where a deletable collection takes Delete and Backspace. - `pub const fn natural_height(mut self, on: bool) -> Self`. The collection takes its full content height and owns no scroll (see [`CollectionProps::natural_height`]). - `pub const fn min_rows(mut self, rows: u16) -> Self`. The collection is at least `rows` rows tall (see [`CollectionProps::min_rows`]). - `pub const fn max_rows(mut self, rows: u16) -> Self`. The collection shows at most `rows` rows and scrolls the rest (see [`CollectionProps::max_rows`]). - `pub const fn row_height(mut self, height: RowHeight) -> Self`. The rows are `height` tall (see [`RowHeight`]). - `pub const fn command_click(mut self, on: bool) -> Self`. A Cmd/Ctrl click on an item is a command, not a pick (see [`CollectionProps::command_click`]). - `pub const fn notch(mut self, notch: Notch) -> Self`. The distance one wheel notch scrolls the rows (see [`CollectionProps::notch`]). + - `pub const fn middle_button(mut self, button: MiddleButton) -> Self`. What a middle press does: pan, or latched auto-scroll (see [`CollectionProps::middle_button`]). + - `pub const fn primary_picks(mut self, on: bool) -> Self`. Whether only a primary press picks an item (see [`CollectionProps::primary_picks`]). + - `pub const fn invert_middle(mut self, on: bool) -> Self`. Flips the direction of middle-button pan and auto-scroll (see [`CollectionProps::invert_middle`]). - `pub fn wheel_notch(&self, line: f32) -> craft_behavior::WheelNotch`. The wheel distance of one notch, with a text line `line` points high: the set notch, else the default. - `pub const fn overflow(mut self, axis: Axis) -> Self`. The axis the rows overflow along (see [`CollectionProps::overflow`]). - `pub fn current(mut self, key: Option) -> Self`. The current item: `Some(key)` marks the item with that key, `None` marks none. `K` is the collection's key type; + - `pub const fn picks_beside_current(mut self, on: bool) -> Self`. Keeps the selection a pick beside the current item (see [`CollectionProps::picks_beside_current`]). - `pub fn empty(mut self, text: impl Into

+ Send + Sync + 'static) -> Self`. The payload `map` makes of a drag of the collection whose keys are `K`; `None` for a row that carries none. @@ -2197,8 +2277,9 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn ime_application_change(&self, ctx: &egui::Context)`. Notes an application change of this editor part's committed text. - `pub fn ime_interrupt(&self, ctx: &egui::Context)`. Asks for the OS composition to be interrupted this pass, because this editor part refused an input method's - `craft_ui::contract::EditorStep`: `pub enum EditorStep { Input(EditorInput), Command(S, Fired) }`. One step of an editor's pass, in the order of the events it came from ([`Cx::editor_steps`]). -- `craft_ui::contract::EndRegion`: `pub struct EndRegion { pub full_height: bool, pub gap: Gap, pub rule: bool }`. An end region, filled by `Container::end`: content in reading order at the line's end edge, beside the body and +- `craft_ui::contract::EndRegion`: `pub struct EndRegion { pub full_height: bool, pub gap: Gap, pub rule: bool, pub fit: bool }`. An end region, filled by `Container::end`: content in reading order at the line's end edge, beside the body and - `pub const fn new() -> Self`. An end region as high as the line, `space.gap.tight` from the body, with no rule. + - `pub const fn fit(mut self, on: bool) -> Self`. Whether the region joins the body's fit. - `pub const fn rule(mut self, on: bool) -> Self`. Whether a rule separates the end region from the body. - `pub const fn full_height(mut self, on: bool) -> Self`. Whether the region takes the full height under the header. - `pub const fn gap(mut self, gap: Gap) -> Self`. Sets the gap between the body and the region. @@ -2220,6 +2301,8 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn icon_spec(&self) -> Option<&IconSpec<'static>>`. The icon before the label. - `pub fn is_enabled(&self) -> bool`. Whether the entry can be picked; false for a separator. - `pub fn is_stepped(&self) -> bool`. Whether a step over the closed control stops on the entry: an enabled, stepped item. + - `pub fn description(mut self, text: impl Into

`. What a component registers with `Pointer::window_drop_target`: a target over the whole window, which needs no +- `craft_ui::runtime::drag::WindowDropTarget`: `pub trait WindowDropTarget

`. What a component registers with `Pointer::window_drop_target`: a target over the whole window, optionally waiting - `type Drop`. What a drop on this target carries to the component's caller. + - `fn requires_pointer(&self) -> bool`. Whether this target waits for a pointer position before taking a drop. - `fn accept(&self, payload: &P, op: DropOperation) -> Option`. `None` rejects. `op` is the operation the held modifiers pick, which a target may refuse. - `fn mark(&self, drop: &Self::Drop) -> DropMark`. Where `drop` would land, a value the ghost layer paints. + - `fn under_modal(&self) -> bool`. Whether the target takes OS file drops (`OsFiles`) while a modal layer holds input, as - `craft_ui::runtime::drag::active`: `pub fn active(ctx: &Context) -> Option>`. The active drag payload of type `P`, from any viewport. For code without a `Cx`. - `craft_ui::runtime::drag::amend`: `pub fn amend(ctx: &Context, change: impl FnOnce(&mut P)) -> bool`. Changes the running session's payload of type `P` (or its further payload of that type) with `change`, in the frame - `craft_ui::runtime::drag::cancel`: `pub fn cancel(ctx: &Context, reason: CancelReason)`. Ends the session without a drop; the source's press ends with it, so nobody gets a drop. @@ -3683,6 +3831,7 @@ AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: - `craft_ui::runtime::egui::access::NodeId`: `pub type NodeId = accesskit::NodeId`. The AccessKit id of a node, as a host test holds it. - `craft_ui::runtime::egui::access::bounds`: `pub fn bounds(ctx: &Context, id: Id) -> Option`. The rect `id`'s response had in the last finished pass, converted as the node's bounds are; `None` when absent, +- `craft_ui::runtime::egui::access::focused_node`: `pub fn focused_node(ctx: &Context) -> Option`. The node that held key focus at the end of the running viewport's last finished pass, the one reported to - `craft_ui::runtime::egui::access::prune_controls`: `pub fn prune_controls(update: &mut egui::accesskit::TreeUpdate)`. The step itself: every `controls` id of `update` that names no node of `update` is dropped. Other - `craft_ui::runtime::egui::access::AccessTree`: `pub struct AccessTree`. The AccessKit tree update of one frame. - `pub fn has(&self, id: Id) -> bool`. Whether the node of `id` exists. @@ -3734,8 +3883,10 @@ AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: - `pub fn is_disabled_key(&self, key: NodeKey) -> bool`. Whether a node by key is reported as disabled. - `pub fn declares_key(&self, key: NodeKey, action: Declared) -> bool`. Whether a node by key declares `action`. - `pub fn children_of(&self, key: NodeKey) -> Vec`. The children of a node by key. -- `craft_ui::runtime::egui::access::Declared`: `pub enum Declared { Focus, Click, Increment, Decrement, SetValue, SetTextSelection, Expand, Collapse, Custom, ScrollUp, ScrollDown, ScrollLeft, ScrollRight }`. An action a node declares. +- `craft_ui::runtime::egui::access::Declared`: `pub enum Declared { Focus, Click, ContextMenu, Increment, Decrement, SetValue, SetTextSelection, Expand, Collapse, Custom, ScrollUp, ScrollDown, ScrollLeft, ScrollRight }`. An action a node declares. - `craft_ui::runtime::egui::access::NodeKey`: `pub struct NodeKey`. A node's number in the tree. + - `pub fn raw(self) -> u64`. The AccessKit node number. + - `pub fn from_raw(raw: u64) -> NodeKey`. The key of the node with AccessKit number `raw`. - `pub fn of(id: Id) -> NodeKey`. The key of the node of `id`. - `craft_ui::runtime::egui::access::TreeUpdate`: re-export of `accesskit::TreeUpdate` (outside these crates). - `craft_ui::runtime::egui::access::is_interactive`: `pub fn is_interactive(tree: &AccessTree, key: NodeKey) -> bool`. Whether the node declares an action a user can take: focus, click or a value change. @@ -3753,6 +3904,7 @@ AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: Injected input: pointer moves, clicks, keys and text an automation client asks for, and the event builders +- `craft_ui::runtime::egui::injected::InjectedFiles`: `pub struct InjectedFiles { pub paths: Vec, pub dropped: bool }`. Files an injected step hovers over a window, and whether the step after it drops them. - `craft_ui::runtime::egui::injected::InjectedPointer`: `pub enum InjectedPointer { Down { button: PointerButton, at: Pos2, mods: Mods, pen: Option }, Move { at: Pos2, mods: Mods, pen: Option, rest: f64 }, Up { at: Pos2, mods: Mods } }`. One pointer step an automation client drives as a device would, with the modifiers held and, for a pen, its - `pub const fn down(button: PointerButton, at: Pos2, mods: Mods, pen: Option) -> Self`. `button` goes down at `at` with `mods` held and the pen's reading `pen`. - `pub const fn move_to(at: Pos2, mods: Mods, pen: Option) -> Self`. The pointer moves to `at` with `mods` held and the pen's reading `pen`. @@ -3853,7 +4005,7 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `pub fn effective_tone(&self, warn: bool) -> Tone`. The tone the message shows in: its own, else `Warn` when it belongs to a `Validity::Warn` (`warn`), else `Bad`. - `craft_ui::runtime::env::MotionPolicy`: `pub struct MotionPolicy { pub mode: MotionMode, pub tokens: MotionTokens }`. The motion mode in effect, carried in `Env.motion`. - `pub const fn new(mode: MotionMode, tokens: MotionTokens) -> Self`. The policy that runs animations at `mode` with `tokens`. -- `craft_ui::runtime::env::Overrides`: `pub struct Overrides { pub size: Option, pub enabled: Option, pub read_only: Option, pub wheel: Option, pub motion: Option, pub direction: Option, pub words: Option, pub values: AppValues, pub id_salt: Option }`. Changes to the inherited values for a stretch of code. +- `craft_ui::runtime::env::Overrides`: `pub struct Overrides { pub size: Option, pub enabled: Option, pub read_only: Option, pub wheel: Option, pub motion: Option, pub direction: Option, pub flow: Option, pub words: Option, pub values: AppValues, pub id_salt: Option }`. Changes to the inherited values for a stretch of code. - `craft_ui::runtime::env::PageBandRoom`: `pub struct PageBandRoom { pub rect: Rect, pub start: f32, pub end: f32 }`. The room of the page band while a full-window page shows: the title-bar-high strip at the window's top and the room - `pub const fn new(rect: Rect, start: f32, end: f32) -> Self`. The band at `rect`, the window's start end taking `start` of it and its end end `end`. - `craft_ui::runtime::env::PaneEdge`: `pub enum PaneEdge { Center, Start, End, Top, Bottom }`. Where a shell pane sits. @@ -3861,7 +4013,7 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `pub const fn points_per_inch(self) -> f64`. How many points make an inch. - `craft_ui::runtime::env::ResolvedRoot`: `pub struct ResolvedRoot { pub mode: Mode, pub contrast: Contrast, pub motion: MotionMode }`. The mode, contrast and motion of a pass, with `System` resolved. - `craft_ui::runtime::env::RevealEdge`: `pub enum RevealEdge { Top, Start, End }`. An edge of the window whose slots a pointer at the edge reveals in body-only mode. The bottom edge and the centre -- `craft_ui::runtime::env::RootEnv`: `pub struct RootEnv { pub sizes: Arc, pub text_size: TextSize, pub direction: Direction, pub motion: MotionChoice, pub mode: ModeChoice, pub contrast: ContrastChoice, pub density: Size, pub scale: Scale, pub tab_all_controls: bool, pub tab_toggles_chrome: bool, pub dialog_tab: TabReach, pub canvas_pattern: bool, pub cursor_follows_zoom: bool, pub tooltips: bool, pub values: AppValues, pub today: Option, pub wheel: WheelSpeed, pub alt_codes: AltCodePages }`. The app's root values each frame. +- `craft_ui::runtime::env::RootEnv`: `pub struct RootEnv { pub sizes: Arc, pub text_size: TextSize, pub direction: Direction, pub motion: MotionChoice, pub mode: ModeChoice, pub contrast: ContrastChoice, pub density: Size, pub scale: Scale, pub tab_all_controls: bool, pub tab_toggles_chrome: bool, pub escape_leaves_fields: bool, pub shortcuts_repeat: bool, pub dialog_tab: TabReach, pub canvas_pattern: bool, pub cursor_follows_zoom: bool, pub tooltips: bool, pub values: AppValues, pub today: Option, pub wheel: WheelSpeed, pub alt_codes: AltCodePages, pub ctrl_wheel_pinch: bool }`. The app's root values each frame. - `pub fn new() -> Self`. A root with every value at its default. - `pub fn scale(mut self, scale: Scale) -> Self`. Sets the interface scale. - `pub fn direction(mut self, direction: Direction) -> Self`. Sets the layout direction. @@ -3884,6 +4036,7 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `pub fn today(mut self, date: CalendarDate) -> Self`. Sets today's date, as the host's clock and time zone give it. - `pub fn wheel_speed(mut self, speed: WheelSpeed) -> Self`. Sets this frame's wheel speed. - `pub fn alt_code_pages(mut self, pages: AltCodePages) -> Self`. Sets the code pages that decode Alt+numpad codes. + - `pub fn ctrl_wheel_pinch(mut self, pinch: bool) -> Self`. Sets whether a fractional Ctrl+wheel arrives as a pinch (`ctrl_wheel_pinch`). - `craft_ui::runtime::env::RowPressed`: `pub enum RowPressed { Row, Cell(ColumnKey), Part { was_lead: bool } }`. Where the collection holds a primary press on a row, within slop, or the press a part of the row holds. - `craft_ui::runtime::env::Scale`: `pub struct Scale(pub f32)`. The interface scale: pixels per point. - `pub const fn new(pixels_per_point: f32) -> Self`. `pixels_per_point` pixels per point. @@ -3938,6 +4091,7 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `pub fn points_per_inch(&self) -> f64`. How many points make an inch in the scope: the app's point-size preference. - `pub fn name(&self, kind: UnitKind) -> Label`. The unit's name in the user's language, as a list of units shows it: Pixels, Pixels/Inch. - `pub fn symbol(&self, kind: UnitKind) -> String`. The unit's spelling in the user's language without the number: `mm`, `px`. + - `pub fn affixes(&self, kind: UnitKind) -> (String, String)`. The text before and after the number in the user's language, spacing included: `("", " mm")`, `("", "%")`. - `pub fn text(&self, kind: UnitKind, n: f64, decimals: RangeInclusive) -> String`. `n` of `kind` with between the least and most digits of `decimals` after the decimal mark, in the user's - `pub fn show(&self, kind: UnitKind, n: f64) -> String`. `n` of `kind` with its default digits ([`UnitKind::decimals`]). - `pub fn pixels(&self, n: f64) -> String`. `n` pixels: `12 px`. @@ -3968,7 +4122,9 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `craft_ui::runtime::env::WordTemplate`: re-export of `craft_i18n::WordTemplate` (outside these crates). - `craft_ui::runtime::env::Words`: re-export of `craft_i18n::Words` (outside these crates). - `craft_ui::runtime::env::WordsOverride`: `pub enum WordsOverride { Replace(Arc), Overlay(WordRows) }`. How a scope changes the built-in text: the only override path for words. +- `craft_ui::runtime::env::in_room`: `pub fn in_room(ui: &mut Ui, rect: Rect, body: impl FnOnce(&mut Ui) -> R) -> R`. Runs `body` in a child `Ui` held to `rect` and clipped to it, as a layout room of its own: the flow grid, content - `craft_ui::runtime::env::system_appearance`: `pub fn system_appearance(ctx: &Context) -> SystemState`. What the OS reports on `ctx` now: the host's reader (`InstallSpec::system`), with the colour scheme egui's +- `craft_ui::runtime::env::system_text_scale`: `pub fn system_text_scale(ctx: &Context) -> Option`. The desktop text scale from the installed [`SystemReader`], `None` where the OS gives none. - `craft_ui::runtime::env::with_env`: `pub fn with_env(ui: &mut Ui, set: impl FnOnce(&mut Overrides), body: impl FnOnce(&mut Ui) -> R) -> R`. Runs `body` in a child `Ui` with `set`'s changes applied to the inherited values. A scope that disables ## `craft_ui::runtime::focus` @@ -3979,6 +4135,7 @@ The focus service: stops, scopes and roving groups registered per pass, the focu - `craft_ui::runtime::focus::FocusShape`: `pub enum FocusShape { Rect, Circle, Polygon(Vec) }`. The shape the focus ring takes around a part. - `craft_ui::runtime::focus::has`: `pub fn has(ctx: &Context, id: Id) -> bool`. Whether focus is on the component `id` or on one of its parts (a canvas's editor part), from the focus record of - `craft_ui::runtime::focus::host_canvas`: `pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse)`. Registers the app's own egui widget `id`, drawn in the running pass, as its window's document canvas: a focus stop +- `craft_ui::runtime::focus::is_focused`: `pub fn is_focused(ctx: &Context, id: Id) -> bool`. Whether the focus stop is the component `id`: the focused member or item of its arena, or a root that - `craft_ui::runtime::focus::request`: `pub fn request(ctx: &Context, target: FocusTarget) -> bool`. Moves focus to `target`, leaves modality unchanged and asks the enclosing scroll owner to reveal it. Called - `craft_ui::runtime::focus::takes_letters`: `pub fn takes_letters(keys: &KeyUse) -> bool`. Whether a stop with these keys takes typed letters: a text field or a shortcut recorder. The letters a keytip or a - `craft_ui::runtime::focus::ActivateKeys`: `pub enum ActivateKeys { Neither, Enter, Space, Both }`. The keys that activate a component. @@ -3991,7 +4148,7 @@ The focus service: stops, scopes and roving groups registered per pass, the focu - `pub const fn contains(self, command: EditCommand) -> bool`. Whether the set has `command`. - `craft_ui::runtime::focus::EndKey`: `pub enum EndKey { LastItem, EndMode }`. What a bare End means for a focused component. - `craft_ui::runtime::focus::EnterRule`: `pub enum EnterRule { Pass, Submit }`. What Enter does in a scope after the focused component declined it. -- `craft_ui::runtime::focus::FocusPolicy`: `pub struct FocusPolicy { pub kind: ScopeKind, pub trap: bool, pub restore: bool, pub initial: Initial, pub enter: EnterRule, pub cancel: CancelRule, pub pages: bool, pub list_enter: bool, pub list: Option }`. A focus scope's rules. +- `craft_ui::runtime::focus::FocusPolicy`: `pub struct FocusPolicy { pub kind: ScopeKind, pub trap: bool, pub restore: bool, pub initial: Initial, pub enter: EnterRule, pub cancel: CancelRule, pub pages: bool, pub list_enter: bool, pub list: Option, pub escape_keeps_typing: bool }`. A focus scope's rules. - `pub const NONE: FocusPolicy`. A scope that changes nothing. - `pub const PANE: FocusPolicy`. A pane: an F6 stop. - `pub const DIALOG: FocusPolicy`. A dialog: Tab stays inside, Enter submits, Escape closes. @@ -4004,14 +4161,16 @@ The focus service: stops, scopes and roving groups registered per pass, the focu - `pub const fn cancel(mut self, cancel: CancelRule) -> Self`. What Escape does. - `pub const fn list_enter(mut self, on: bool) -> Self`. Whether Enter on a text opener activates the layer's list. - `pub const fn list(mut self, list: Id) -> Self`. The collection in the layer that takes the opener's list keys. + - `pub const fn escape_keeps_typing(mut self, on: bool) -> Self`. Whether Escape in this dialog keeps the focused field's typing ([`FocusPolicy::escape_keeps_typing`]). - `pub const fn pages(mut self, on: bool) -> Self`. Whether Ctrl+Tab cycles pages. +- `craft_ui::runtime::focus::FocusRequest`: `pub enum FocusRequest { Take, WhenNone }`. A one-shot request for focus on a component's stop (`Props::request_focus`), for what opens without a layer of its - `craft_ui::runtime::focus::FocusTarget`: `pub enum FocusTarget { Id(Id), Part(Id, PartRef), Doc(DocKey) }`. What `runtime::focus::request` focuses. - `craft_ui::runtime::focus::Initial`: `pub enum Initial { Keep, First, FirstField, Default, Key(&'static str), KeepAnchor }`. Where focus goes the first time a scope is pushed. - `craft_ui::runtime::focus::Intents`: `pub struct Intents`. An owned copy of the intents routed to one id this pass; read through `cx.intents()`. - `pub fn take_digit(&mut self) -> Option`. Takes the next typed digit. - `pub fn take(&mut self, intent: Intent) -> bool`. Takes an intent of the kind of `intent`, once per pass: the first taker gets it. - `pub fn take_exact(&mut self, intent: &Intent) -> bool`. Takes an intent equal to `intent` in every field, once per pass: `Intent::delete(false, Granularity::Grapheme)` - - `pub fn take_move(&mut self) -> Option<(NavMove, MoveMods)>`. Takes the next move. + - `pub fn take_move(&mut self) -> Option<(NavMove, MoveMods)>`. Takes the next move, whichever it is: for a component that acts on every move. A move taken is the component's, - `pub fn take_move_where(&mut self, wanted: impl Fn(NavMove, MoveMods) -> bool) -> Option<(NavMove, MoveMods)>`. Takes the next move that `wanted` accepts; the others stay for a later taker, or for the scroll owner around a - `pub fn take_scroll_access(&mut self, into_view: bool) -> Option`. Takes the next AccessKit request that asks a scroll region to scroll, or with `into_view` to show its target. - `pub fn take_edit(&mut self) -> Option`. Takes the next edit command. @@ -4024,7 +4183,7 @@ The focus service: stops, scopes and roving groups registered per pass, the focu - `pub fn untaken(&self, intent: &Intent) -> bool`. Whether an intent of the kind of `intent` is routed and not taken. - `pub fn take_access(&mut self) -> Option`. Takes the next `Intent::Access` request. - `craft_ui::runtime::focus::KeepKeys`: `pub enum KeepKeys { None, Tab, InlineArrows, BlockArrows }`. The keys a focused component keeps from the key stage. -- `craft_ui::runtime::focus::KeyUse`: `pub struct KeyUse { pub keep: KeepKeys, pub activate: ActivateKeys, pub claims: &'static [Chord], pub edits: EditSet, pub inactive: EditSet, pub owner: OwnerClass, pub value: bool, pub moves: bool, pub chrome_key: bool, pub nudge: bool, pub deletes: bool, pub submits: bool, pub end: EndKey, pub session: bool, pub type_ahead: bool, pub holds_drafts: bool }`. A component's declared keys. +- `craft_ui::runtime::focus::KeyUse`: `pub struct KeyUse { pub keep: KeepKeys, pub activate: ActivateKeys, pub claims: &'static [Chord], pub edits: EditSet, pub inactive: EditSet, pub owner: OwnerClass, pub value: bool, pub moves: bool, pub chrome_key: bool, pub nudge: bool, pub nudge_mods: NudgeMods, pub deletes: bool, pub submits: bool, pub end: EndKey, pub session: bool, pub type_ahead: bool, pub holds_drafts: bool, pub command_keys: bool }`. A component's declared keys. - `pub const TEXT_MULTILINE: KeyUse`. A multi-line text field: Up and Down move the caret. - `pub const CODE: KeyUse`. A code editor: Tab inserts. - `pub const CANVAS: KeyUse`. A document canvas: all arrows, no activation, and the key that marks its window as showing a document. @@ -4032,6 +4191,7 @@ The focus service: stops, scopes and roving groups registered per pass, the focu - `pub const RECORDER: KeyUse`. A shortcut recorder: it takes the arrows of a canvas, but it is no document, so it marks no window and a Tab in - `pub const fn of(input: Input) -> KeyUse`. The default key use of a component that takes `input`. The only place egui key filters start from. - `pub const fn with_holds_drafts(mut self) -> Self`. The same use declaring that a press that would apply the focused draft leaves it unapplied (`holds_drafts`). + - `pub const fn with_command_keys(mut self) -> Self`. The same use letting command chords and function keys run the app's commands while it types (`command_keys`). - `pub const fn with_type_ahead(mut self) -> Self`. The same use taking typed letters as `Intent::Text`. - `pub const fn with_claims(mut self, claims: &'static [Chord]) -> Self`. The same use claiming `claims`. - `pub const fn with_edits(mut self, edits: EditSet) -> Self`. The same use listing `edits`. @@ -4045,9 +4205,16 @@ The focus service: stops, scopes and roving groups registered per pass, the focu - `pub const fn with_end(mut self, end: EndKey) -> Self`. The same use with `end` as the meaning of a bare End. - `pub const fn with_keep(mut self, keep: KeepKeys) -> Self`. The same use with `keep` as the keys it keeps from the key stage. - `pub const fn with_chrome_key(mut self, chrome_key: bool) -> Self`. The same use with `chrome_key` as whether the component marks its window as showing a document: a canvas + - `pub const fn with_nudge_mods(mut self, nudge_mods: NudgeMods) -> Self`. The same use with `nudge_mods` as the modifiers a document canvas acts on with the arrows. - `pub const fn is_document_editor(&self) -> bool`. Whether the component is a document canvas's editor part: the document (`chrome_key`) holding its editor's - `pub fn claims_chord(&self, chord: &Chord) -> bool`. Whether the component claims `chord`. - `craft_ui::runtime::focus::Letters`: `pub enum Letters { None, TypeAhead }`. Whether a roving group matches typed letters to entries. +- `craft_ui::runtime::focus::NudgeMods`: `pub struct NudgeMods`. A set of modifier combinations held with the arrows (`KeyUse::nudge_mods`): each is matched exactly, so Shift alone + - `pub const NONE: NudgeMods`. No arrow. + - `pub const STEPS: NudgeMods`. The plain arrows and the arrows with Shift: the step and the large step every nudge reads. + - `pub const fn with(self, mods: Mods) -> Self`. The same set with `mods` in it. + - `pub const fn union(self, other: NudgeMods) -> Self`. Every combination of either set. + - `pub const fn contains(self, mods: Mods) -> bool`. Whether `mods` is in the set. - `craft_ui::runtime::focus::Roving`: `pub struct Roving { pub shape: NavShape, pub wrap: bool, pub home_end: bool, pub page: Option, pub letters: Letters, pub arrows: Arrows, pub first_column: Option, pub hands_back: bool, pub no_lead: bool, pub keeps_lead_moves: bool }`. A roving group's rules: one Tab stop whose members take moves. - `pub const fn new(shape: NavShape) -> Roving`. A group of `shape` with Home and End, no wrap, no paging and no letters. - `pub const fn wrap(mut self, on: bool) -> Self`. Whether moves wrap. @@ -4068,13 +4235,16 @@ The focus service: stops, scopes and roving groups registered per pass, the focu The frame plugin: the per-pass and per-frame steps, with the inputs the app sets and the outputs it drains. - `craft_ui::runtime::frame::ChromeToggle`: `pub enum ChromeToggle { Panels, PanelsKeepTools, ShowPanels, Reveal(Option) }`. Which panels a window's chrome toggle hides (spec 1.8): the `window.toggle_panels` and -- `craft_ui::runtime::frame::FrameInput`: `pub struct FrameInput { pub root: RootEnv, pub commands: CommandInput, pub host: Option>, pub latched: Mods }`. What the app sets before each frame. +- `craft_ui::runtime::frame::FrameInput`: `pub struct FrameInput { pub root: RootEnv, pub commands: CommandInput, pub host: Option>, pub latched: Mods, pub app_modal: Option, pub window_input: WindowInput }`. What the app sets before each frame. - `pub fn new(root: RootEnv) -> Self`. A frame with `root` and no host. + - `pub fn window_input(mut self, window_input: WindowInput) -> Self`. Sets whether the window system's input reaches the hosted windows. - `pub fn commands(mut self, commands: CommandInput) -> Self`. Sets the command input. - `pub fn latched(mut self, mods: Mods) -> Self`. Sets the modifiers latched beyond the window's input. + - `pub fn app_modal(mut self, viewport: Option) -> Self`. Sets the window in which the app's own egui code shows a modal ([`FrameInput::app_modal`](Self::app_modal)). - `pub fn host(mut self, host: Arc) -> Self`. Sets the host: the same `Arc` every frame, a new one to switch (see [`FrameInput::host`](Self::host)). -- `craft_ui::runtime::frame::FrameOutput`: `pub struct FrameOutput { pub fired: Vec, pub delivered: Vec, pub dimmed: Vec, pub announcements: Vec, pub chrome_toggles: Vec<(ViewportId, ChromeToggle)>, pub removed_gestures: Vec, pub outer_edits: Vec, pub refused: bool, pub ended_previews: Vec }`. What the runtime accumulated since the last `take_output`, across passes and discarded passes. +- `craft_ui::runtime::frame::FrameOutput`: `pub struct FrameOutput { pub fired: Vec, pub delivered: Vec, pub dimmed: Vec, pub declined: Vec, pub announcements: Vec, pub chrome_toggles: Vec<(ViewportId, ChromeToggle)>, pub removed_gestures: Vec, pub outer_edits: Vec, pub refused: bool, pub ended_previews: Vec }`. What the runtime accumulated since the last `take_output`, across passes and discarded passes. - `craft_ui::runtime::frame::OuterEdit`: `pub enum OuterEdit { Begin { id: GestureId, label: Arc, doc_key: Option }, Commit { id: GestureId }, Cancel { id: GestureId } }`. A step of the outer gesture of a container whose `ContainerProps::outer_edit` is on: one undo step over the edits of +- `craft_ui::runtime::frame::WindowInput`: `pub enum WindowInput { Live, Dropped }`. Whether the window system's input reaches the OS windows the runtime hosts beside the root (a panel floated into - `craft_ui::runtime::frame::clock`: `pub fn clock(ctx: &Context) -> f64`. The running pass's time in seconds, the same on every pass of a frame: for app code that times a wait. Content - `craft_ui::runtime::frame::discard_pass`: `pub fn discard_pass(ctx: &Context, reason: &'static str)`. Discards the running pass, so nothing of it paints, and runs it again, when [`discardable`]: for a host that learns - `craft_ui::runtime::frame::discardable`: `pub fn discardable(ctx: &Context) -> bool`. Whether the running pass can still be discarded: egui runs a bounded number of passes a frame, and a discard asked @@ -4130,7 +4300,7 @@ Decision records and findings. Inspected regions ([`record`]) collect pipeline s - `pub fn frame_layers(mut self, painter: Option) -> Self`. Sets the end hook's ghost-layer painter. - `craft_ui::runtime::install::WheelModifiers`: `pub struct WheelModifiers { pub zoom: egui::Modifiers, pub sideways: egui::Modifiers }`. The modifiers the mouse wheel zooms and scrolls sideways with. - `pub const fn new(zoom: egui::Modifiers, sideways: egui::Modifiers) -> Self`. The wheel zooms with `zoom` held and scrolls sideways with `sideways` held. -- `craft_ui::runtime::install::install`: `pub fn install(ctx: &Context, spec: InstallSpec) -> Result<(), InstallError>`. Adds the runtime plugin to `ctx` and sets the egui options the runtime owns: interface scale is a command, quit goes +- `craft_ui::runtime::install::install`: `pub fn install(ctx: &Context, spec: InstallSpec) -> Result<(), InstallError>`. Adds the runtime plugin to `ctx` and sets the egui options the runtime owns: the interface scale is the app's ## `craft_ui::runtime::keys` @@ -4143,7 +4313,7 @@ The key stage (spec 9.1, 9.2, 9.3, 9.7): the input hook strips the keys the runt - `pub fn take_digit(&mut self) -> Option`. Takes the next typed digit. - `pub fn take(&mut self, intent: Intent) -> bool`. Takes an intent of the kind of `intent`, once per pass: the first taker gets it. - `pub fn take_exact(&mut self, intent: &Intent) -> bool`. Takes an intent equal to `intent` in every field, once per pass: `Intent::delete(false, Granularity::Grapheme)` - - `pub fn take_move(&mut self) -> Option<(NavMove, MoveMods)>`. Takes the next move. + - `pub fn take_move(&mut self) -> Option<(NavMove, MoveMods)>`. Takes the next move, whichever it is: for a component that acts on every move. A move taken is the component's, - `pub fn take_move_where(&mut self, wanted: impl Fn(NavMove, MoveMods) -> bool) -> Option<(NavMove, MoveMods)>`. Takes the next move that `wanted` accepts; the others stay for a later taker, or for the scroll owner around a - `pub fn take_scroll_access(&mut self, into_view: bool) -> Option`. Takes the next AccessKit request that asks a scroll region to scroll, or with `into_view` to show its target. - `pub fn take_edit(&mut self) -> Option`. Takes the next edit command. @@ -4162,7 +4332,8 @@ The key stage (spec 9.1, 9.2, 9.3, 9.7): the input hook strips the keys the runt - `craft_ui::runtime::keys::focus_holds`: `pub fn focus_holds(ctx: &Context, chord: Chord) -> bool`. Whether the focused component of the running viewport holds a press of `chord`, as routing decides for the press: - `craft_ui::runtime::keys::held`: `pub fn held(ctx: &Context) -> Vec`. The keys down in the running viewport this pass: the key stage's `down` (withheld presses included), plus each key - `craft_ui::runtime::keys::textless_paste`: `pub fn textless_paste(ctx: &Context) -> bool`. Whether the running viewport's input hook read a paste with no text in this pass: the paste chord came while the -- `craft_ui::runtime::keys::with_window_intents`: `pub fn with_window_intents(ctx: &Context, rtl: bool, take: impl FnOnce(&mut Intents) -> bool) -> bool`. Offers the window's intents to `take` while nothing in the window has framework focus or the focused stop is the +- `craft_ui::runtime::keys::with_canvas_window_intents`: `pub fn with_canvas_window_intents(ctx: &Context, rtl: bool, take: impl FnOnce(&mut Intents) -> bool) -> bool`. Offers window intents to a canvas while the canvas or one of its controls has focus, or nothing has focus. +- `craft_ui::runtime::keys::with_window_intents`: `pub fn with_window_intents(ctx: &Context, rtl: bool, take: impl FnOnce(&mut Intents) -> bool) -> bool`. Offers the window's intents and the focused framework stop's unused Escape to `take`, and writes back what it ## `craft_ui::runtime::layout_memory` @@ -4257,10 +4428,11 @@ The layer stack (15.2): the record of the egui layers shown, their order and the - `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen, with a popup's - `pub const fn modal(backdrop: Backdrop) -> Rank`. A modal rank with `backdrop`. - `craft_ui::runtime::overlay::any_open`: `pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool`. Whether any layer of the running viewport that `filter` counts was shown last frame. -- `craft_ui::runtime::overlay::close_popups`: `pub fn close_popups(ctx: &Context)`. Queues a close of every popup layer of the running viewport shown last frame: its menus, dropdowns and lists. The +- `craft_ui::runtime::overlay::close_popups`: `pub fn close_popups(ctx: &Context)`. Queues a close of every popup layer of the running viewport shown last frame that a command closes - `craft_ui::runtime::overlay::family`: `pub fn family(ctx: &Context, id: Id) -> SmallVec<[Id; 4]>`. `id` and everything opened from inside it, shown last frame. - `craft_ui::runtime::overlay::is_open`: `pub fn is_open(ctx: &Context, id: Id) -> bool`. Whether the layer `id` was shown last frame. - `craft_ui::runtime::overlay::pressed_outside`: `pub fn pressed_outside(ctx: &Context, id: Id) -> bool`. Whether a primary press landed outside the layer `id` in this pass while its dismissal kept it open. +- `craft_ui::runtime::overlay::raise`: `pub fn raise(ctx: &Context, id: Id)`. Brings the family of the open layer `id` in front of the other families of its class at the end of this pass, as a - `craft_ui::runtime::overlay::request_close`: `pub fn request_close(ctx: &Context, id: Id, why: CloseReason)`. Queues a close of the layer `id` (a popup or a container). The owner's step 9 or `OverlayUi::show` collects it and - `craft_ui::runtime::overlay::top`: `pub fn top(ctx: &Context) -> Option`. The layer that receives Cancel: the newest member of the topmost family that takes keys. @@ -4290,7 +4462,8 @@ Background results (14): one result per key in runtime memory, produced by a job The pointer snapshot, press targets, the shape record and press cancels (8.1, 8.3). -- `craft_ui::runtime::pointer::PointerFrame`: `pub struct PointerFrame { pub pos: Option, pub delta: Vec2, pub buttons: Buttons, pub press: Option, pub release: Option, pub mods: Mods, pub pick_mods: Mods, pub pick_pos: Option, pub multi_tap: Option, pub time: f64, pub kind: PointerKind, pub sample: Option, pub multi_touch: Option, pub scroll: Vec2, pub zoom: f32, pub rotation: f32, pub slop: f32, pub target: f32 }`. The pointer input of one pass of one viewport, egui-converted. Input enters a frame's first pass only (egui hands +- `craft_ui::runtime::pointer::PointerFrame`: `pub struct PointerFrame { pub pos: Option, pub delta: Vec2, pub buttons: Buttons, pub press: Option, pub press_mods: Option, pub release: Option, pub mods: Mods, pub pick_mods: Mods, pub pick_pos: Option, pub multi_tap: Option, pub time: f64, pub kind: PointerKind, pub sample: Option, pub multi_touch: Option, pub scroll: Vec2, pub zoom: f32, pub rotation: f32, pub slop: f32, pub target: f32 }`. The pointer input of one pass of one viewport, egui-converted. Input enters a frame's first pass only (egui hands +- `craft_ui::runtime::pointer::active_part`: `pub fn active_part(ctx: &Context, owner: Id) -> Option`. The part of `owner` holding the pointer's hover or an open press in this viewport. - `craft_ui::runtime::pointer::frame`: `pub fn frame(ctx: &Context) -> PointerFrame`. The running pass's pointer input. A tracked input (`runtime::inputs`): a memoized view that reads it runs when the - `craft_ui::runtime::pointer::hovers`: `pub fn hovers(ctx: &Context, id: Id) -> bool`. Whether a shape the component `id` registered shows hover in the running pass, by the pass's one resolution of - `craft_ui::runtime::pointer::mods`: `pub fn mods(ctx: &Context) -> Mods`. The modifiers held in the running pass, with the latched ones (`PointerFrame::mods`). A tracked input: a memoized @@ -4336,7 +4509,7 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con - `craft_ui::runtime::toast::Card`: `pub struct Card { pub id: ToastId, pub toast: Toast }`. A toast in the queue, as the host reads it. - `craft_ui::runtime::toast::MAX_CARDS`: `pub const MAX_CARDS: usize`. Most cards queued at once per window. Posting past it keeps the new card and drops the oldest earlier card that - `craft_ui::runtime::toast::TIMEOUT`: `pub const TIMEOUT: f32`. How long a toast stays when it names no timeout, in seconds: the source apps' notification duration. -- `craft_ui::runtime::toast::Toast`: `pub struct Toast { pub message: Label, pub timeout: Option, pub politeness: Politeness, pub tone: Tone, pub title: Option

, card: Option| { @@ -1554,7 +1553,6 @@ impl Pass<'_, P> { .within(within) .auto_collapse(scene.auto_collapse) .mode(mode) - .flyout_layer(flyout_layer) .tab_look(scene.config.tab_look) .framed(scene.config.flush_docks && !in_window); let shown = match card { diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index e999f4a297..7c902208d3 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -4,7 +4,6 @@ use craft_behavior::Axis; use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at}; use craft_theme::{AppSizes, SizeValue}; use craft_ui::buttons::Button; -use craft_ui::contract::overlay::PopupLayer; use craft_ui::contract::{Bind, BodyCx, PlainData, Role, Show as _, SizeLimits, Tracked}; use craft_ui::display::Text; use craft_ui::docking::{ @@ -428,7 +427,8 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses const FLYOUT_HEIGHT: f32 = 300.0; /// Panels for a docked flyout under a floating window: Alpha's group, in the flyout, is a view that measures -/// [`FLYOUT_HEIGHT`] and records the rect it shows in; Beta, in the window, shows a button that counts its clicks. +/// [`FLYOUT_HEIGHT`] and records the rect it shows in, this pass; Beta, in the window, shows a button that counts its +/// clicks. struct UnderWindow { flyout: Rc>>, clicks: Rc>, @@ -464,49 +464,61 @@ fn flyout_dock(window: Option) -> Arc> { Arc::new(Workspace::new(Layout::new(Some(root), windows))) } -/// What shows where a floating window lies over part of Alpha's open flyout, with docked flyouts standing at `layer`: -/// whether the layer on top there is the flyout's, whether it stands above the flyout's in egui's layer order, and how -/// many clicks a click there gave the window's button. -fn flyout_under_window(layer: PopupLayer) -> (bool, bool, u32) { +/// The rect of the floating window of [`flyout_dock`] over the flyout at `flyout`: it starts inside the flyout, so +/// the window's button lies over it, and reaches past its end edge and bottom, so part of the window lies clear of it. +fn window_over(flyout: Rect) -> Rect { + Rect::from_min_size(flyout.min + Vec2::new(40.0, 30.0), Vec2::new(300.0, 360.0)) +} + +/// A collapsed column's flyout stands among the floating windows, for every app, in the order egui keeps for them: a +/// flyout opened after a window is drawn over it and takes the presses where they overlap, and a press on the window +/// then brings the window back in front of the flyout. The flyout stays open throughout, and its own presses raise it. +#[trial] +fn a_flyout_stands_among_the_floating_windows_in_their_order() { let workspace = Rc::new(RefCell::new(flyout_dock(None))); let (flyout, clicks) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(0))); let mut panels = UnderWindow { flyout: Rc::clone(&flyout), clicks: Rc::clone(&clicks) }; - let (held, specs) = (Rc::clone(&workspace), Tracked::new(Sides)); + let (held, specs, pass_rect) = (Rc::clone(&workspace), Tracked::new(Sides), Rc::clone(&flyout)); let mut fixture = Fixture::new(move |ui| { - let config = DockConfig::default().native_windows(false).flyout_layer(layer); + // The cell holds this pass's flyout rect, so a flyout that does not show reads as `None`. + pass_rect.set(None); + let config = DockConfig::default().native_windows(false); let shown = Bind::given(Arc::clone(&held.borrow())); - DockArea::new("Flyout dock", shown, &specs, &mut panels, config).flyout(Bind::given(Some(10))).show(ui); + DockArea::new("Flyout dock", shown, &specs, &mut panels, config).show(ui); }); fixture.room(Vec2::new(900.0, 600.0)).settle(); + let icon = fixture.by_label("Alpha").expect("Alpha's icon").rect.center(); + fixture.click_at(icon).settle(); let open = flyout.get().expect("Alpha's flyout shows its group"); - // The window covers the flyout's end two thirds from its top and reaches past its end edge. - let window = Rect::from_min_size(open.min + Vec2::new(open.width() / 3.0, 0.0), Vec2::new(open.width() + 100.0, 220.0)); - *workspace.borrow_mut() = flyout_dock(Some(window)); + // The floating window shows over the flyout. It is raised as the newest layer while the flyout stands there; the + // flyout is then closed and opened again, so it is the one opened after the window. + *workspace.borrow_mut() = flyout_dock(Some(window_over(open))); fixture.settle(); + fixture.click_at(icon).settle(); + assert!(flyout.get().is_none(), "the icon of the open panel closes its flyout"); + fixture.click_at(icon).settle(); + let open = flyout.get().expect("the flyout is open again"); let button = fixture.by_label("Beta button").expect("the floating window shows Beta's button").center(); - assert!(open.contains(button), "the window's button lies over the flyout: {button:?} in {open:?}"); - let alone = Pos2::new(open.left() + open.width() / 6.0, open.center().y); + assert!(open.contains(button), "the window's button lies over the open flyout: {button:?} in {open:?}"); let ctx = fixture.ctx().clone(); - let flyout_layer = ctx.layer_id_at(alone).expect("the flyout is on top beside the window"); - let top = ctx.layer_id_at(button).expect("a layer lies under the button"); - let place = |layer: egui::LayerId| ctx.memory(|memory| memory.layer_ids().position(|listed| listed == layer)); - let above = place(top) > place(flyout_layer); + let window_layer = ctx.layer_id_at(button).expect("a layer lies under the button"); + let alone = Pos2::new(open.left() + 8.0, open.center().y); + let flyout_layer = ctx.layer_id_at(alone).expect("the flyout shows beside the window"); + assert_ne!(flyout_layer, window_layer, "the flyout and the window are layers of their own: {flyout_layer:?}"); + assert_eq!(ctx.layer_id_at(button), Some(flyout_layer), "the flyout opened after the window is on top where they overlap"); fixture.click_at(button).settle(); - (top == flyout_layer, above, clicks.get()) -} + assert_eq!(clicks.get(), 0, "and the press there does not reach the window's button"); -/// A docked column's open flyout stands above a floating window over it, as popups do: it is drawn over the window -/// and takes the press there. With `DockConfig::flyout_layer(PopupLayer::BelowWindows)` the window stays in front: its -/// layer lies above the flyout's and the press reaches its button. -#[trial] -fn a_floating_window_stays_above_a_docked_flyout_that_stands_below_the_windows() { - let (flyout_on_top, _, clicks) = flyout_under_window(PopupLayer::AboveWindows); - assert!(flyout_on_top, "by default the flyout is on top where it overlaps the window"); - assert_eq!(clicks, 0, "and the press there does not reach the window"); - - let (flyout_on_top, window_above, clicks) = flyout_under_window(PopupLayer::BelowWindows); - assert!(!flyout_on_top && window_above, "below the windows, the window's layer lies above the flyout's"); - assert_eq!(clicks, 1, "and the press where they overlap reaches the window's button"); + // A press on the window where the flyout does not reach raises the window, as a press raises any floating window. + let clear = [Pos2::new(open.right() + 24.0, open.center().y), Pos2::new(open.center().x, open.bottom() + 24.0)] + .into_iter() + .find(|point| !open.contains(*point) && fixture.ctx().layer_id_at(*point) == Some(window_layer)) + .expect("part of the window lies clear of the flyout"); + fixture.frame(vec![pointer::moved(clear)]).frame(vec![pointer::press(clear)]).frame(vec![pointer::release(clear)]).settle(); + assert!(flyout.get().is_some(), "the flyout stays open: Auto-Collapse Iconic Panels is off"); + assert_eq!(ctx.layer_id_at(button), Some(window_layer), "the pressed window is in front of the flyout"); + fixture.click_at(button).settle(); + assert_eq!(clicks.get(), 1, "and a press at the button now reaches it"); } #[derive(PlainData)] diff --git a/docs/contract-api.md b/docs/contract-api.md index c212699f30..3ba92399c8 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2495,7 +2495,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn unshown(response: Response) -> Option where Self: Sized,`. The output of a layer-like container that shows nothing this pass (closed, past its exit fade): `response` is - `fn value_text(&self) -> Option<&str>`. The shown value as the component words it to assistive technology; `None` for a component that gives none. - `fn story_facts(&self) -> crate::testing::StoryOutput`. The facts a story reports about this output: its id, click, edit kinds, collection kinds and visible range. -- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub popup_layer: PopupLayer }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. +- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub among_windows: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. @@ -2527,7 +2527,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it. - `pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay`. Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]): - `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]). - - `pub fn popup_layer(mut self, layer: PopupLayer) -> Overlay`. Sets where a popup stands against the floating windows ([`Overlay::popup_layer`]). + - `pub fn among_windows(mut self, on: bool) -> Overlay`. Sets whether the layer stands among the floating windows ([`Overlay::among_windows`]). - `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer. - `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]). - `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer @@ -2834,7 +2834,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `craft_ui::contract::overlay::OpenFilter`: re-export of `craft_ui::runtime::overlay::OpenFilter`. - `craft_ui::contract::overlay::Opener`: `pub struct Opener { pub id: Id, pub rect: Rect, pub layer: areas::Layer, pub trigger: Trigger, pub enabled: bool, pub anchor: Option, pub others: Vec }`. A component that opens a free-standing popup, and how. A layer with several openers keeps the first as its - `craft_ui::contract::overlay::Outside`: `pub enum Outside { Close, Keep, Absorb }`. What a press outside the layer and its anchor does. -- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub popup_layer: PopupLayer }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. +- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub among_windows: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. @@ -2866,7 +2866,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it. - `pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay`. Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]): - `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]). - - `pub fn popup_layer(mut self, layer: PopupLayer) -> Overlay`. Sets where a popup stands against the floating windows ([`Overlay::popup_layer`]). + - `pub fn among_windows(mut self, on: bool) -> Overlay`. Sets whether the layer stands among the floating windows ([`Overlay::among_windows`]). - `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer. - `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]). - `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer @@ -2909,7 +2909,6 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub fn changed(self, cx: &mut Cx<'_, C>) -> bool`. Whether a toggle, `open` or `close` queued in this pass leaves the popup's open state different from the - `pub fn bind_open(self, cx: &mut Cx<'_, C>, mut open: BindMut<'_, bool>) -> bool`. Binds the popup's open state to `open`: call it in `update`, after the toggles and closes the component - `pub fn is_open(self, cx: &mut Cx<'_, C>) -> bool`. Whether the popup is open in this pass: valid from step 8, with the changes queued so far applied. -- `craft_ui::contract::overlay::PopupLayer`: re-export of `craft_ui::runtime::overlay::PopupLayer`. - `craft_ui::contract::overlay::PopupRegion`: `pub struct PopupRegion(pub Option)`. The screen rect the popups opened in an env are contained in, and the popups opened from those: the menus of a menu - `pub fn new(region: Option) -> Self`. Popups contained in `region`; `None` lets them take the whole safe rect. - `craft_ui::contract::overlay::Resize`: `pub struct Resize { pub edges: ResizeEdges, pub by_caller: bool }`. How the user may resize a layer. @@ -4430,7 +4429,6 @@ The layer stack (15.2): the record of the egui layers shown, their order and the - `craft_ui::runtime::overlay::CloseReason`: `pub enum CloseReason { Requested, Escape, Outside, FocusLeft(crate::runtime::focus::FocusMove), Activated, Enter, Timeout, AnchorGone }`. Why a layer closes. - `craft_ui::runtime::overlay::LayerRole`: `pub enum LayerRole { Plain, Progress, InPlaceEditor }`. What a layer is for, beyond its rank. - `craft_ui::runtime::overlay::OpenFilter`: `pub enum OpenFilter { Any, Modal, Keys }`. What `any_open` counts. -- `craft_ui::runtime::overlay::PopupLayer`: `pub enum PopupLayer { AboveWindows, BelowWindows }`. Where a popup stands against the floating windows of its window. - `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen, with a popup's - `pub const fn modal(backdrop: Backdrop) -> Rank`. A modal rank with `backdrop`. - `craft_ui::runtime::overlay::any_open`: `pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool`. Whether any layer of the running viewport that `filter` counts was shown last frame. diff --git a/docs/glossary.md b/docs/glossary.md index 13ddc3563b..317b2a8587 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -216,7 +216,6 @@ One row per name in the author table (Overview) and per `pub` item a component a | `PointerButton`, `Buttons` | Pointer buttons, egui-free | craft-behavior | 8.1 | | `Politeness` | An announcement's or live region's urgency | `craft_ui::runtime::access` | 12.1 | | `PopupHandle` | A `Copy` id and name for one of a component's own popups, from `cx.popup(name)`, with `trigger`, `open`, `close` and `is_open` | `craft_ui::contract` | 15.5 | -| `PopupLayer` | Where a popup stands against the floating windows: above them, or below them for one opened outside every layer (a dock column's flyout) | `craft_ui::runtime` (layer stack) | 15.2 | | Prelude | The stable surface of a crate | each crate | 1.11 | | Press-target rule | Exactly one root starts each press: on the topmost layer under it, the root whose press-taking shape is painted on top there; none when egui's hit test names a raw egui widget | `craft_ui::primitives` (sensing core) | 8.3 | | `PressPhase`, `PressState` | A press lifecycle's phase, and its state with mods, sample and capture | craft-behavior | 8.2 | diff --git a/docs/ui-docking.md b/docs/ui-docking.md index 52b0a8d915..6a3a940cf3 100644 --- a/docs/ui-docking.md +++ b/docs/ui-docking.md @@ -112,7 +112,6 @@ The host handles these `DockEvent`s: | `panel_menu_always` | off | Every group shows its panel menu button, with the dock's own rows when the shown panel has none. Off: only a panel with rows of its own (`DockPanels::panel_rows`) gets the button. | | `panel_menu_icon` | `more` | The panel menu button's icon; `menu` gives the three-line mark. | | `native_windows` | on | Floating windows open as OS windows where the window host opens them and reports their positions (not on Wayland) and `PanelSpec::allow_native` allows. | -| `flyout_layer` | `PopupLayer::AboveWindows` | Where docked columns' flyouts stand against the floating windows. `PopupLayer::BelowWindows` keeps a floating window in front of a docked flyout it overlaps: drawn over it and taking the presses there. The flyout still closes by its rules, and menus opened from it stand above everything. A floating window's own flyouts stand above it either way. | The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords` holds the words. @@ -131,7 +130,7 @@ The theme's docking sizes (`DockSizes`) set the drop bands and zones. `DockWords - A flyout is as tall as its group measures, within the room below its top, and at least the `DockHeights::default` of each of its panels whose `PanelSpec::flyout_height` is `FlyoutHeight::Docked`, the default. A panel with `FlyoutHeight::Content` opens a flyout as tall as its body measures, while its `DockHeights` still size its group docked in a column. A group the user sized keeps that height. - Split handles are Tab stops, and the arrow keys move them. A pointer press or drag on a handle leaves key focus where it was, so the arrows after a drag still reach the app; only a handle reached by Tab takes them. A divider drag is one gesture in `DockAreaOutput::edit`. - A pointer press on a panel tab (a click, a drag's press, the tab menu's secondary press) leaves key focus where it was, so the document's keys keep working; Tab still reaches the tab row. -- Floating windows stack with the app's own egui windows in egui's area order: the one shown, pressed or raised last (`FloatingGroup::raise`, which the host's `DockArea::focus` request sets on the window holding the panel) is on top, so a dialog the app opens over a floating panel shows above it. A docked flyout with `DockConfig::flyout_layer(PopupLayer::BelowWindows)` stands below all of them. +- Floating windows stack with the app's own egui windows in egui's area order: the one shown, pressed or raised last (`FloatingGroup::raise`, which the host's `DockArea::focus` request sets on the window holding the panel) is on top, so a dialog the app opens over a floating panel shows above it. A collapsed column's flyout stands in that order too: one opened after a window is over it, and a press on either brings it in front, while the menus opened from a flyout stand above every window. - A panel command (`DockCommands`) acts on the shown panel of the group that takes it. A menu row, a key and the command palette run the same code: `actions` turns the command into `Action`s. ## Commands and workspaces From cac8725f59b46fddfe06de085bd747a219b961f5 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 17:56:05 +0100 Subject: [PATCH 15/27] Panel tabs clip and overflow: drop the ellipsis shrink Panel tabs keep the framework's clip and overflow: they shrink to their first letters with the label clipped at the tab's edge, the shown tab whole, and the tabs that do not fit go to the strip's overflow menu. PanelTabShrink::Ellipsis goes with the option that chose it: DockConfig::tab_shrink, the group's tab_shrink, TabStrip::panel_shrink, Tab::panel_shrink, FitMode::ShrinkToLeast, TabKind::fit_mode_for and clips_label_in, and craft_behavior::fit::fit_to_least with its docs. Trials: the two ellipsis trials and the helpers they alone used are removed with the option. --- crates/behavior/src/fit.rs | 52 +------ crates/ui-panels/src/docking/config.rs | 14 +- crates/ui-panels/src/docking/group.rs | 9 +- crates/ui-patterns/src/patterns/dock/area.rs | 1 - crates/ui-widgets/src/tabs/mod.rs | 2 +- crates/ui-widgets/src/tabs/rules.rs | 43 +----- crates/ui-widgets/src/tabs/strip.rs | 34 +--- crates/ui-widgets/src/tabs/tab.rs | 24 +-- crates/ui-widgets/tests/it/tabs.rs | 154 +------------------ docs/contract-api.md | 1 - docs/ui-docking.md | 1 - 11 files changed, 22 insertions(+), 313 deletions(-) diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 3712ca15e2..4e767cb6b0 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,7 +1,6 @@ -//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`], -//! [`fit_to_least`] and [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); -//! [`fit_items`] shortens items that have a short form, then drops command items and titles from the end. All of them -//! read no egui types. +//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and +//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens +//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -176,51 +175,6 @@ pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32 TabFit { shown, overflow, overflow_width } } -/// Fit tab widths into `available` points, each tab shrinking to its own `least` before any tab overflows. -/// Every tab shrinks, the selected one too: the widest tabs shrink first to a common cap, and each keeps at least -/// `min(natural, least)` of its own. Only when the tabs do not all fit at their least is an overflow button -/// `overflow_width` wide reserved; the selected tab stays, the others follow in order while their least widths fit -/// beside it, and the rest overflow, the last ones first. A selected tab whose least alone is wider than the strip -/// less the button takes the room left. A tab past the end of `least` keeps its natural width as its least. -/// -/// Dimensions are sanitized as in [`fit`], and the shown widths plus `overflow_width` never exceed the sanitized -/// available width. Work and storage are linear in the input count (with at most 32 fitting passes). -pub fn fit_to_least(natural: &[f32], least: &[f32], selected: usize, available: f32, overflow_width: f32) -> TabFit { - let available = tab_extent(available); - let natural: Vec = natural.iter().map(|&w| tab_extent(w)).collect(); - let floors: Vec = natural.iter().enumerate().map(|(i, &w)| least.get(i).map_or(w, |&least| w.min(tab_extent(least)))).collect(); - let all: Vec = (0..natural.len()).collect(); - let total = |widths: &[f32]| widths.iter().map(|&w| f64::from(w)).sum::(); - if total(natural.as_slice()) <= f64::from(available) { - return TabFit { shown: all.into_iter().zip(natural).collect(), ..Default::default() }; - } - // One tab has nowhere to overflow; all available space belongs to it. - if natural.len() == 1 { - return TabFit { shown: vec![(0, available)], ..Default::default() }; - } - let floor = |i: usize| floors.get(i).copied().unwrap_or(0.0); - if total(floors.as_slice()) <= f64::from(available) { - return TabFit { shown: squeeze_floored(&natural, &all, available, 0.0, floor), ..Default::default() }; - } - let overflow_width = tab_extent(overflow_width).min(available); - let budget = available - overflow_width; - let selected = selected.min(natural.len().saturating_sub(1)); - let mut used = f64::from(floor(selected)); - let mut open = true; - let (shown, overflow): (Vec, Vec) = all.into_iter().partition(|&i| { - if i == selected { - return true; - } - open = open && used + f64::from(floor(i)) <= f64::from(budget); - if open { - used += f64::from(floor(i)); - } - open - }); - let shown = squeeze_floored(&natural, &shown, budget, 0.0, floor); - TabFit { shown, overflow, overflow_width } -} - fn squeeze(natural: &[f32], indices: &[usize], total: f32, minimum: f32) -> Vec<(usize, f32)> { squeeze_floored(natural, indices, total, minimum, |i| natural.get(i).copied().unwrap_or(0.0).min(minimum)) } diff --git a/crates/ui-panels/src/docking/config.rs b/crates/ui-panels/src/docking/config.rs index 7d35042691..90cdca42d9 100644 --- a/crates/ui-panels/src/docking/config.rs +++ b/crates/ui-panels/src/docking/config.rs @@ -3,7 +3,7 @@ use super::targets::ZoneRule; use super::{ColumnCards, IconicMode}; -use crate::tabs::{PanelTabLook, PanelTabShrink}; +use crate::tabs::PanelTabLook; use craft_behavior::{DockSide, IconId}; /// A set of the sides of the layout's outer edge or of a group. @@ -109,10 +109,6 @@ pub struct DockConfig { /// filled rounded pill ([`PanelTabLook::Pill`]), or a square filled block on a canvas strip /// ([`PanelTabLook::Block`]). pub tab_look: PanelTabLook, - /// How far the groups' panel tabs shrink before they overflow: to their first letters, clipped - /// ([`PanelTabShrink::FirstLetters`]), or each to a readable prefix ending in "…", the shown tab too - /// ([`PanelTabShrink::Ellipsis`]), the tabs that do not fit at that width going to the strip's overflow menu. - pub tab_shrink: PanelTabShrink, /// A floating window opens in an OS window of its own where the window host opens OS windows and reports where /// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and /// with this off, it shows in the app window. A window that takes over a held press (`DockArea::continue_move`) @@ -150,7 +146,6 @@ impl Default for DockConfig { titled_headers: false, wheel_selects_tabs: false, tab_look: PanelTabLook::Plain, - tab_shrink: PanelTabShrink::FirstLetters, native_windows: true, group_order_items: false, panel_menu_always: false, @@ -280,13 +275,6 @@ impl DockConfig { self } - /// How far the groups' panel tabs shrink ([`tab_shrink`](Self::tab_shrink)). - #[must_use] - pub fn tab_shrink(mut self, shrink: PanelTabShrink) -> Self { - self.tab_shrink = shrink; - self - } - /// Flush docks on or off ([`flush_docks`](Self::flush_docks)). #[must_use] pub fn flush_docks(mut self, on: bool) -> Self { diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 4b277b8b48..29c277e8ac 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -22,7 +22,7 @@ use crate::runtime::focus::{self, FocusRequest, FocusTarget}; use crate::runtime::memory::sub; use crate::sections::FooterBar; use crate::style::{ComponentStyle, Corners, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind, TypeRole}; -use crate::tabs::{PanelTabLook, PanelTabShrink, Tab, TabKind, TabStrip, TornOff}; +use crate::tabs::{PanelTabLook, Tab, TabKind, TabStrip, TornOff}; use craft_behavior::{CursorIcon, CursorPriority, DockSide, IconId, Metrics, PartKey, PressPhase, Sense, keyed}; use craft_theme::{ControlSize, GripMark, GripShape, Tokens}; use egui::{Id, Pos2, Rect, Response, Ui, Vec2}; @@ -374,9 +374,6 @@ pub struct DockGroup<'a, P: Clone + Hash + Send + Sync + 'static> { wheel_selects_tabs: bool, /// The look of the tabs: [`tab_look`](DockGroup::tab_look). tab_look: PanelTabLook, - /// How far the tabs shrink ([`DockConfig::tab_shrink`](super::DockConfig::tab_shrink)). - #[prop] - tab_shrink: PanelTabShrink, /// The header shows the shown panel's title (with its count) and a close button in place of the tab strip, as a /// single titled panel does: the panels are shown from a rail, not by tabs. #[prop(flag)] @@ -441,7 +438,6 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< closable: false, wheel_selects_tabs: false, tab_look: PanelTabLook::Plain, - tab_shrink: PanelTabShrink::FirstLetters, titled: false, take_focus: false, dock: None, @@ -766,7 +762,6 @@ impl Container for closable: self.closable, wheel_selects: self.wheel_selects_tabs, look: self.tab_look, - shrink: self.tab_shrink, take_focus: self.take_focus, dock: self.dock, sent: Outbox::new(&mut sent), @@ -861,7 +856,6 @@ struct TabRow<'a, P> { closable: bool, wheel_selects: bool, look: PanelTabLook, - shrink: PanelTabShrink, /// The strip takes key focus in this pass (`DockGroup::take_focus`): in the key, so the row runs and the strip /// takes it while it runs. take_focus: bool, @@ -950,7 +944,6 @@ fn tab_row(row: &mu .kind(TabKind::Panel) .keeps_focus() .panel_look(row.look) - .panel_shrink(row.shrink) .shown(shown_tab(panels, active)) .tear_off() .natural_height(true) diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index b05261bbc5..7a70fe737a 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -1246,7 +1246,6 @@ impl Pass<'_, P> { .panel_menu_shown(*hosted || scene.config.panel_menu_always) .panel_menu_icon(scene.config.panel_menu_icon.clone()) .tab_look(scene.config.tab_look) - .tab_shrink(scene.config.tab_shrink) .command_states(states.clone()); if look.in_window { group = group.in_window(); diff --git a/crates/ui-widgets/src/tabs/mod.rs b/crates/ui-widgets/src/tabs/mod.rs index 554d1946d6..7a68e3be2e 100644 --- a/crates/ui-widgets/src/tabs/mod.rs +++ b/crates/ui-widgets/src/tabs/mod.rs @@ -6,7 +6,7 @@ mod words; mod rules; pub(crate) mod tab; -pub use rules::{CloseSide, DocumentTabLook, FitMode, OverflowMenu, OverflowPlace, PanelTabLook, PanelTabShrink, TabCloseLook, TabKind, close_side}; +pub use rules::{CloseSide, DocumentTabLook, FitMode, OverflowMenu, OverflowPlace, PanelTabLook, TabCloseLook, TabKind, close_side}; pub use tab::{Tab, TabOutput, TabPartEvent, TabRole, TabStyle}; pub use words::TabWords; diff --git a/crates/ui-widgets/src/tabs/rules.rs b/crates/ui-widgets/src/tabs/rules.rs index 5cc4de1bdb..e3fb27b917 100644 --- a/crates/ui-widgets/src/tabs/rules.rs +++ b/crates/ui-widgets/src/tabs/rules.rs @@ -1,6 +1,6 @@ //! The pure rules of a tab strip: what each kind of strip does, and which side a tab's close button is on. -use craft_behavior::fit::{TabFit, fit, fit_to_least, fit_whole}; +use craft_behavior::fit::{TabFit, fit, fit_whole}; use craft_host::target::Os; /// The look of document tabs ([`TabKind::Document`]) app-wide. An app sets it once at its root (`RootEnv::values`); @@ -51,22 +51,6 @@ pub enum PanelTabLook { Block, } -/// How far panel tabs ([`TabKind::Panel`]) shrink before they overflow, and how a label too long for its tab ends: a -/// strip's choice ([`TabStrip::panel_shrink`](super::TabStrip)), which a dock makes for its groups' tabs. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)] -#[non_exhaustive] -pub enum PanelTabShrink { - /// Tabs shrink to their title's first letters, the label clipped at the tab's edge with no ellipsis. - #[default] - FirstLetters, - /// Tabs shrink no further than their label's readable least, its first - /// [`TextRun::READABLE_CHARACTERS`](crate::primitives::TextRun::READABLE_CHARACTERS) characters and an ellipsis (a - /// title at most one character longer stays whole), and a cut label ends in "…". Every tab shrinks, the shown one - /// too, the widest first; only the tabs that do not fit at their least go to the overflow menu, the last ones - /// first ([`FitMode::ShrinkToLeast`]). - Ellipsis, -} - /// The kind of a strip. It sets the defaults below; the host picks one per strip. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] @@ -99,22 +83,16 @@ pub enum FitMode { /// Whether the selected tab keeps its natural width. keep_selected: bool, }, - /// Every tab shrinks towards its own least width, the selected one too, the widest first; only the tabs that do - /// not fit at their least overflow, the last ones first (`fit_to_least`). Panel tabs under - /// [`PanelTabShrink::Ellipsis`]. - ShrinkToLeast, } impl FitMode { /// Fits tabs of the `natural` widths into `available`, keeping the `selected` tab. Whole widths give the tabs /// marked in `kept` the room before the other tabs (`fit_whole`); shrinking tabs have no kept tabs. `minimum` is - /// the narrowest a shrinking tab becomes and `overflow` the width of the overflow button; [`FitMode::ShrinkToLeast`] - /// takes it as every tab's least (a strip passes each tab's own to `fit_to_least`). + /// the narrowest a shrinking tab becomes and `overflow` the width of the overflow button. pub fn fit(self, natural: &[f32], selected: usize, kept: &[bool], available: f32, minimum: f32, overflow: f32) -> TabFit { match self { FitMode::Whole => fit_whole(natural, selected, kept, available, overflow), FitMode::Shrink { keep_selected } => fit(natural, selected, available, minimum, overflow, keep_selected), - FitMode::ShrinkToLeast => fit_to_least(natural, &vec![minimum; natural.len()], selected, available, overflow), } } } @@ -154,20 +132,12 @@ impl TabKind { if self.shrinks_in(look) { FitMode::Shrink { keep_selected: self.keeps_active_width() } } else { self.fit_mode() } } - /// How tab widths are fitted under the app's document tab look and the strip's panel shrink: panel tabs under - /// [`PanelTabShrink::Ellipsis`] all shrink to their own readable least, the shown tab too, before any overflows - /// ([`FitMode::ShrinkToLeast`]); every other kind and shrink is [`TabKind::fit_mode_in`]. - pub fn fit_mode_for(self, look: DocumentTabLook, shrink: PanelTabShrink) -> FitMode { - if self == Self::Panel && shrink == PanelTabShrink::Ellipsis { FitMode::ShrinkToLeast } else { self.fit_mode_in(look) } - } - /// Whether these are document tabs under [`DocumentTabLook::Shrinking`]. pub fn shrinks_in(self, look: DocumentTabLook) -> bool { self == Self::Document && look == DocumentTabLook::Shrinking } - /// Whether the shown tab keeps its whole title while the other tabs shrink: panel tabs that shrink to their first - /// letters (under [`PanelTabShrink::Ellipsis`] the shown tab shrinks with the others, [`TabKind::fit_mode_for`]). + /// Whether the shown tab keeps its whole title while the other tabs shrink: panel tabs. pub fn keeps_active_width(self) -> bool { self == Self::Panel } @@ -178,13 +148,6 @@ impl TabKind { self == Self::Panel } - /// Whether a label too long for its tab is clipped at the tab's edge under the strip's `shrink`: panel tabs that - /// shrink to their first letters ([`PanelTabShrink::FirstLetters`]); under [`PanelTabShrink::Ellipsis`] they end - /// in an ellipsis as the other kinds do. - pub fn clips_label_in(self, shrink: PanelTabShrink) -> bool { - self.clips_label() && shrink == PanelTabShrink::FirstLetters - } - /// Where the overflow button sits: at the strip's end for document and text tabs, after the last tab for panel /// tabs. pub fn overflow_place(self) -> OverflowPlace { diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index 23bb277528..52f4604363 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -30,7 +30,7 @@ use crate::primitives::{PaintShape, StrokeWidth}; use crate::runtime::commands::FireSource; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleColor, StyleCx}; -use craft_behavior::fit::{FitItem, fit_items, fit_to_least}; +use craft_behavior::fit::{FitItem, fit_items}; use craft_behavior::{ Flow, HitLevel, HitPriority, IconId, Insets, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, SelectionChange, Sense, @@ -332,21 +332,8 @@ impl StripLayout { .collect(); let selected = lane.iter().position(|place| matches!(*place, Lane::Tab(at) if at == *selected)).unwrap_or(usize::MAX); let available = (*width - ends_room).max(0.0) + tab_gap; - let fit = if *mode == FitMode::ShrinkToLeast { - // Each tab shrinks no further than its own least; a tab fading out keeps its width. - let least: Vec = lane - .iter() - .map(|place| match *place { - Lane::Tab(at) => min.get(at).copied().unwrap_or(0.0), - Lane::Ghost(k) => ghosts.get(k).map_or(0.0, |ghost| ghost.width), - }) - .map(|width| width + tab_gap) - .collect(); - fit_to_least(&padded, &least, selected, available, *height) - } else { - let minimum = min.iter().copied().fold(0.0, f32::max); - mode.fit(&padded, selected, &held, available, minimum + tab_gap, *height) - }; + let minimum = min.iter().copied().fold(0.0, f32::max); + let fit = mode.fit(&padded, selected, &held, available, minimum + tab_gap, *height); *shown = vec![false; count]; *left = vec![*width; count]; *wide = vec![0.0; count]; @@ -528,9 +515,8 @@ impl TabRoles<'_, K> { /// asks for the tab's context menu. /// /// The `kind` picks the rules: document and text tabs keep whole titles and send the rest to an overflow menu of -/// every tab; panel tabs shrink before they overflow and the menu lists the hidden ones. Panel tabs shrink to their -/// first letters, clipped, beside the shown tab whole, or with `panel_shrink(PanelTabShrink::Ellipsis)` each to a -/// readable prefix ending in "…", the shown tab too, before any overflows. The shown tab is always visible. A tab +/// every tab; panel tabs shrink to their first letters, clipped, beside the shown tab whole, before they overflow, +/// and the menu lists the hidden ones. The shown tab is always visible. A tab /// dragged out of the strip and released where no other strip, dock or drop target takes it is reported as /// `torn_off`. #[derive(crate::contract::Component, crate::contract::Props)] @@ -551,11 +537,6 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + ' /// The look of a panel strip's tabs ([`TabKind::Panel`]). #[prop] panel_look: super::PanelTabLook, - /// How far a panel strip's tabs ([`TabKind::Panel`]) shrink before they overflow: to their first letters, clipped - /// (the default), or each to a readable prefix ending in an ellipsis, the shown tab too - /// ([`PanelTabShrink::Ellipsis`](super::PanelTabShrink)). - #[prop] - panel_shrink: super::PanelTabShrink, /// The tab the host shows. A click, Space, Enter or a drop reports the new one in the output. #[prop] shown: Option, @@ -628,7 +609,6 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStri kind: TabKind::Document, large: false, panel_look: super::PanelTabLook::Plain, - panel_shrink: super::PanelTabShrink::FirstLetters, shown: None, tear_off: false, wheel_selects: false, @@ -1085,7 +1065,7 @@ impl Collection // Each end item is measured in this pass, with its label and icon only. let ends = self.trailing.iter().map(|end| end.fit_item(cx)).collect(); let look = cx.env::(); - let mode = self.kind.fit_mode_for(look, self.panel_shrink); + let mode = self.kind.fit_mode_in(look); let fitting = Fitting { selected, mode, kept, ends, gap: cx.tokens.space.gap.inline, ghosts, departed }; // Shrinking document tabs stand apart by the inline gap; the other kinds and looks touch. let tab_gap = if self.kind.shrinks_in(look) { cx.tokens.space.gap.inline } else { 0.0 }; @@ -1094,7 +1074,7 @@ impl Collection /// Every tab takes the strip's kind, panel look, panel shrink and size. fn dress<'r>(&self, tab: Self::Item<'r>, _: &RowState) -> Self::Item<'r> { - let tab = tab.kind(self.kind).panel_look(self.panel_look).panel_shrink(self.panel_shrink); + let tab = tab.kind(self.kind).panel_look(self.panel_look); if self.large { tab.large() } else { tab } } diff --git a/crates/ui-widgets/src/tabs/tab.rs b/crates/ui-widgets/src/tabs/tab.rs index 4da01bba8e..875f513371 100644 --- a/crates/ui-widgets/src/tabs/tab.rs +++ b/crates/ui-widgets/src/tabs/tab.rs @@ -3,10 +3,9 @@ //! Selection, the lead, the focus ring and the drag ghost belong to the collection that shows the tab; the tab draws //! the look the item step gives it and reports what its own parts do. The strip gives the tab a rect: the tab's //! measure is its natural width (`Proposal::Min` the room for the first letters of its title beside its icon and close -//! button, or for a panel tab under `PanelTabShrink::Ellipsis` its label's readable least), and a narrower rect cuts the -//! label first, then the detail, and shows the whole text as a tooltip. +//! button), and a narrower rect cuts the label first, then the detail, and shows the whole text as a tooltip. -use super::rules::{CloseSide, PanelTabLook, PanelTabShrink, TabCloseLook, TabKind, close_side}; +use super::rules::{CloseSide, PanelTabLook, TabCloseLook, TabKind, close_side}; use super::words::TabWords; use std::borrow::Cow; @@ -208,9 +207,6 @@ pub struct Tab<'a> { #[style_key] #[prop] panel_look: PanelTabLook, - /// How far a panel tab ([`TabKind::Panel`]) shrinks and how its cut label ends; the other kinds have their own. - #[prop] - panel_shrink: PanelTabShrink, /// Secondary text after the label (a colour mode, a zoom). #[prop(into)] detail: Option

::register_room(ui.ctx(), dock, cell); } let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; - // Only a docked column's icons are a rail; a floating window's open flyouts, which stand above its window. + // Only a docked column's icons are a rail; a floating window's open flyouts, which stand in the windows' order. let mode = if in_window { IconicMode::Flyouts } else { scene.config.iconic_mode }; // The width the user gives a column by its inner edge leaves out its card's inset. let inset = card.map_or(0.0, |place| scene.sizes.inset(place)); diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index 7c902208d3..50d32a7146 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -492,28 +492,29 @@ fn a_flyout_stands_among_the_floating_windows_in_their_order() { let open = flyout.get().expect("Alpha's flyout shows its group"); // The floating window shows over the flyout. It is raised as the newest layer while the flyout stands there; the // flyout is then closed and opened again, so it is the one opened after the window. - *workspace.borrow_mut() = flyout_dock(Some(window_over(open))); + let window = window_over(open); + *workspace.borrow_mut() = flyout_dock(Some(window)); fixture.settle(); + // The window is there and the flyout too; a corner of the window clear of the flyout names the window's layer. + let clear = Pos2::new(window.right() - 24.0, window.top() + 24.0); + let ctx = fixture.ctx().clone(); + let window_layer = ctx.layer_id_at(clear).expect("the floating window shows"); + let flyout_layer = ctx.layer_id_at(Pos2::new(open.left() + 8.0, open.center().y)).expect("the flyout shows beside the window"); + assert_ne!(flyout_layer, window_layer, "the flyout and the window are layers of their own: {flyout_layer:?}"); + + // Closed and opened again, the flyout is the one opened after the window. fixture.click_at(icon).settle(); assert!(flyout.get().is_none(), "the icon of the open panel closes its flyout"); fixture.click_at(icon).settle(); let open = flyout.get().expect("the flyout is open again"); let button = fixture.by_label("Beta button").expect("the floating window shows Beta's button").center(); assert!(open.contains(button), "the window's button lies over the open flyout: {button:?} in {open:?}"); - let ctx = fixture.ctx().clone(); - let window_layer = ctx.layer_id_at(button).expect("a layer lies under the button"); - let alone = Pos2::new(open.left() + 8.0, open.center().y); - let flyout_layer = ctx.layer_id_at(alone).expect("the flyout shows beside the window"); - assert_ne!(flyout_layer, window_layer, "the flyout and the window are layers of their own: {flyout_layer:?}"); assert_eq!(ctx.layer_id_at(button), Some(flyout_layer), "the flyout opened after the window is on top where they overlap"); fixture.click_at(button).settle(); assert_eq!(clicks.get(), 0, "and the press there does not reach the window's button"); // A press on the window where the flyout does not reach raises the window, as a press raises any floating window. - let clear = [Pos2::new(open.right() + 24.0, open.center().y), Pos2::new(open.center().x, open.bottom() + 24.0)] - .into_iter() - .find(|point| !open.contains(*point) && fixture.ctx().layer_id_at(*point) == Some(window_layer)) - .expect("part of the window lies clear of the flyout"); + assert!(!open.contains(clear), "the window's corner lies clear of the flyout: {clear:?} in {open:?}"); fixture.frame(vec![pointer::moved(clear)]).frame(vec![pointer::press(clear)]).frame(vec![pointer::release(clear)]).settle(); assert!(flyout.get().is_some(), "the flyout stays open: Auto-Collapse Iconic Panels is off"); assert_eq!(ctx.layer_id_at(button), Some(window_layer), "the pressed window is in front of the flyout"); From 53eff3ec5a9c358aaee92249f66c7b932a7e2073 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 18:16:35 +0100 Subject: [PATCH 20/27] among_windows: the doc says it applies to any layer that sets it The field said it was read only for `Rank::Popup`, but the tier and the pass's order honour it for a layer of any rank, a collapsed column's flyout included. --- crates/ui-contract/src/contract/overlay/props.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 7274c05426..829e4e6974 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -162,9 +162,9 @@ pub struct Overlay { pub continue_move: Option, /// What the layer is for; a progress window is left out of `any_open`. pub role: LayerRole, - /// The layer stands among the floating windows, in the order egui keeps for them: the last of them shown, pressed - /// or raised is on top, and the app's own egui windows stack with it. Read only for `Rank::Popup`, which otherwise - /// stands above every window. + /// The layer stands among the floating windows, in the order egui keeps for them, whatever its rank: the last of + /// them shown, pressed or raised is on top, and the app's own egui windows stack with it. Unset, a `Rank::Popup` + /// stands above every window instead; a collapsed dock column's flyout sets it. pub among_windows: bool, /// Set only by [`Overlay::full_window`]. full_window: bool, From a92c72bbb8ef857eb2e6d21ce6bf1460c4c3b9ab Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 18:16:42 +0100 Subject: [PATCH 21/27] Hit test: next's let chain for the press that raises a family The nested ifs were left from a two-pass hit test that is gone; the chain reads the same and keeps the diff to next small. --- crates/ui-contract/src/runtime/overlay.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 872ff3bfa3..966e728809 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -925,14 +925,14 @@ pub(crate) fn end_pass(ctx: &Context) { persist.raised.retain(|id, _| roots.contains(id)); persist.appeared.retain(|id, _| current.iter().any(|entry| entry.id == *id)); let before = families(¤t, &persist.raised); - if let Some(point) = pressed { - let hit = before + if let Some(point) = pressed + && let Some(hit) = before .iter() .rev() - .find(|members| members.iter().filter(live).filter(|entry| entry.interactable()).any(|entry| entry.rect.contains(point))); - if let Some(root) = hit.and_then(|members| members.first()) { - stamp(root.id, persist); - } + .find(|members| members.iter().filter(live).filter(|entry| entry.interactable()).any(|entry| entry.rect.contains(point))) + && let Some(root) = hit.first() + { + stamp(root.id, persist); } let families = families(¤t, &persist.raised); let mut order: Vec = Vec::new(); From 86f19be81886f985446063a9d6570ab99c3b818e Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 19:16:31 +0100 Subject: [PATCH 22/27] docs: regenerate contract-api.md --- docs/contract-api.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index 35ef5bbb1c..38680adb07 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2823,7 +2823,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub const fn on_activate(mut self, on: bool) -> Self`. Closes when a component inside is activated, except an opener toggling its popup. - `pub const fn commands(mut self, on: bool) -> Self`. Closes when a key, a native menu pick or the palette runs a command from outside it; off for a layer its host - `pub const fn timeout(mut self, seconds: Option) -> Self`. Closes after `seconds`. -- `craft_ui::contract::overlay::DragBounds`: `pub enum DragBounds { Inside, TitleVisible }`. How much of a floating layer stays inside the window when the user moves it, when it is placed at a position, and when it shows at the placement a pass stored: +- `craft_ui::contract::overlay::DragBounds`: `pub enum DragBounds { Inside, TitleVisible }`. How much of a floating layer stays inside the window when the user moves it, when it is placed at a position, and - `craft_ui::contract::overlay::FloatPlace`: `pub struct FloatPlace { pub pos: Option, pub corner: Align2 }`. Where a floating layer sits. - `pub const fn centred() -> Self`. Centred in the viewport. - `pub const fn at(pos: Pos2) -> Self`. With its left-top at `pos`. @@ -4428,7 +4428,7 @@ The layer stack (15.2): the record of the egui layers shown, their order and the - `craft_ui::runtime::overlay::CloseReason`: `pub enum CloseReason { Requested, Escape, Outside, FocusLeft(crate::runtime::focus::FocusMove), Activated, Enter, Timeout, AnchorGone }`. Why a layer closes. - `craft_ui::runtime::overlay::LayerRole`: `pub enum LayerRole { Plain, Progress, InPlaceEditor }`. What a layer is for, beyond its rank. - `craft_ui::runtime::overlay::OpenFilter`: `pub enum OpenFilter { Any, Modal, Keys }`. What `any_open` counts. -- `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` is the only place a layer's egui order is chosen, with a popup's +- `craft_ui::runtime::overlay::Rank`: `pub enum Rank { Window, Toast, Popup, Modal { backdrop: Backdrop }, ModalChrome, Tooltip }`. An overlay's place in the order. `Rank` chooses a layer's egui order; a popup that stands among the floating - `pub const fn modal(backdrop: Backdrop) -> Rank`. A modal rank with `backdrop`. - `craft_ui::runtime::overlay::any_open`: `pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool`. Whether any layer of the running viewport that `filter` counts was shown last frame. - `craft_ui::runtime::overlay::close_popups`: `pub fn close_popups(ctx: &Context)`. Queues a close of every popup layer of the running viewport shown last frame that a command closes @@ -4470,6 +4470,7 @@ The pointer snapshot, press targets, the shape record and press cancels (8.1, 8. - `craft_ui::runtime::pointer::frame`: `pub fn frame(ctx: &Context) -> PointerFrame`. The running pass's pointer input. A tracked input (`runtime::inputs`): a memoized view that reads it runs when the - `craft_ui::runtime::pointer::hovers`: `pub fn hovers(ctx: &Context, id: Id) -> bool`. Whether a shape the component `id` registered shows hover in the running pass, by the pass's one resolution of - `craft_ui::runtime::pointer::mods`: `pub fn mods(ctx: &Context) -> Mods`. The modifiers held in the running pass, with the latched ones (`PointerFrame::mods`). A tracked input: a memoized +- `craft_ui::runtime::pointer::pressed_part`: `pub fn pressed_part(ctx: &Context, owner: Id) -> Option`. The part of `owner` holding a press in this viewport that was open when the pass began: in the pass that ends the - `craft_ui::runtime::pointer::shapes_at`: `pub fn shapes_at(ctx: &Context, at: Pos2) -> Vec<(Id, Option)>`. Every shape of the last pass on the topmost layer at `at` (screen points) whose area contains it, as - `craft_ui::runtime::pointer::withhold_members`: `pub fn withhold_members(ctx: &Context, root: Id, withheld: bool)`. Whether the arena of `root` resolves the presses and hover of the next pass without its members' shapes. A canvas @@ -4615,7 +4616,7 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con - `pub fn install_hit_sink(&self, viewport: ViewportId) -> HitSink`. The hit-test sink of `viewport`'s window, made on the first call. The platform layer calls it once it has put - `pub fn pointer_in(&self, viewport: ViewportId) -> Option`. The desktop pointer in the coordinates of `viewport`, when it lies inside that window. - `craft_ui::runtime::windows::WindowLevel`: `pub enum WindowLevel { Normal, Palette, AlwaysOnTop }`. Where a window stands in the stack of windows. -- `craft_ui::runtime::windows::WindowSpec`: `pub struct WindowSpec { pub kind: WindowKind, pub chrome: Option, pub captions: Option, pub level: WindowLevel, pub taskbar: bool, pub shown_after_first_paint: bool, pub takes_focus: bool, pub passes_pointer: bool }`. How an OS window opens (21.2): what it is for, who draws its frame, where it stands and whether it has a taskbar +- `craft_ui::runtime::windows::WindowSpec`: `pub struct WindowSpec { pub kind: WindowKind, pub chrome: Option, pub captions: Option, pub level: WindowLevel, pub taskbar: bool, pub shown_after_first_paint: bool, pub takes_focus: bool, pub passes_pointer: bool, pub hands_on_cancel: bool }`. How an OS window opens (21.2): what it is for, who draws its frame, where it stands and whether it has a taskbar - `pub fn tool() -> Self`. A tool window (a native dock window): its own title row in place of the OS title bar - `pub fn popup() -> Self`. A popup window: a layer opened from a palette window (a flyout, menu or tooltip) in an OS window of its own. It - `pub fn document() -> Self`. A document window with the installed decision's frame. @@ -4628,6 +4629,7 @@ The toast queues: one per window (`WindowKey`), filled from any code with a `Con - `pub fn taskbar(mut self, taskbar: bool) -> Self`. Sets whether the window has a taskbar or Dock entry. - `pub fn takes_focus(mut self, takes_focus: bool) -> Self`. Sets whether the window takes OS focus when it opens. - `pub fn passes_pointer(mut self, passes_pointer: bool) -> Self`. Sets whether pointer input passes through the window to the window below it (a tooltip's). + - `pub fn hands_on_cancel(mut self, hands_on_cancel: bool) -> Self`. Sets whether an Escape nothing in the window takes is the Cancel of the window it was opened from. - `craft_ui::runtime::windows::act`: `pub fn act(ctx: &Context, viewport: ViewportId, action: WindowAction) -> bool`. Sends `action` to `viewport`. It is the only sender of window commands: it checks the capabilities and the - `craft_ui::runtime::windows::double_click_action`: `pub fn double_click_action(frame: &Frame, setting: DoubleClick, maximized: bool) -> Option`. What a double click on a window's free move band (its title bar, or the strip a modal leaves over it) asks of the @@ -4714,6 +4716,7 @@ The style layer: the state set and its resolver, style parts and `ComponentStyle - `pub fn env(&self) -> T`. An app value set by a scope. Its hash is part of the style cache key. - `pub fn color(&self, color: Rgba) -> StyleColor`. The constructor of `StyleColor` for styles: a semantic token read or a token-group field becomes a style colour - `pub fn ink_on(&self, fill: DataColor) -> StyleColor`. The ink for text on a user colour: the higher-contrast of `text.normal` and `text.on_strong` on the fill, + - `pub fn icon_ink_on(&self, fill: DataColor) -> StyleColor`. The ink for icons and non-text on a user colour: the higher-contrast of `text.normal` and `text.on_strong` on the fill, - `pub fn ink_of(&self, color: DataColor, on: Rgba) -> StyleColor`. The ink of a glyph or label in the data colour `color` on the surface `on`, pushed to the contrast the text - `pub fn focus_look(&self) -> FocusLook`. The one builder of the focus ring: the line's focus colour at the medium stroke, on the shape's edge. - `pub fn tone(&self, tone: Tone) -> StyleColor`. The colour text and icons of `tone` read in. From 7c78ddc28e58df9cdadc283ff97149ed8d8e8465 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 20:14:29 +0100 Subject: [PATCH 23/27] A root that reopens during its fade is raised in egui's area order end_pass stamped a root only when the last pass did not have it, and a layer that shows again while its exit fade runs was in that pass. A layer left to egui's own area order, a floating window or a popup that stands among them such as a dock column's flyout, got no raise either: egui raises an area when it first shows or when it is pressed, and this area showed in the pass before. A flyout opened again in its fade therefore stayed under a window the fade had let over it. The pass reads the last pass's entries with their exiting flag now: a root that appears, or that faded out then and is open again, is stamped, and one that stands in the floating windows' order goes into the pass's raise list, which reaches move_to_top. A root that first shows asks no raise, since egui raises it itself and a pass whose last one was skipped has every root missing. Trial, beside a_flyout_stands_among_the_floating_windows_in_their_order: a_flyout_opened_again_during_its_fade_is_above_the_window_over_it closes the flyout with a floating window over its tab, which takes the top in the fade, opens the flyout again over the nine frames of the fade, and reads the top layer at its tab. --- crates/ui-contract/src/runtime/overlay.rs | 30 ++++++++++---- .../ui-patterns/tests/it/docking/columns.rs | 40 +++++++++++++++++++ 2 files changed, 62 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 966e728809..bcb22aff24 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -885,13 +885,16 @@ fn families(entries: &[OpenEntry], raised: &IdMap) -> Vec> { groups.into_iter().map(|(_, members)| members).collect() } -/// The end hook: raises the families that appeared, were pressed or were asked to (`raise`), hands egui the order of -/// every layer above the floating windows (which keep egui's own area order, where an asked raise moves them to the -/// top), and records the open-modal fact. +/// The end hook: raises the families that appeared, also one that reopened during its own exit fade, those that were +/// pressed and those that were asked to (`raise`), hands egui the order of every layer above the floating windows +/// (which keep egui's own area order, where an asked raise moves them to the top), and records the open-modal fact. +/// A family that stands in the floating windows' order is raised there when it reopens during its fade: egui showed its +/// area in the pass before, so egui raises none. pub(crate) fn end_pass(ctx: &Context) { let viewport = pass::current_viewport(ctx); - let (current, last_ids, raise) = - with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::>(), pass.raise.clone())); + let (current, last, raise) = with_pass(ctx, |pass| { + (pass.current.clone(), pass.last.iter().map(|entry| (entry.id, entry.exiting)).collect::>(), pass.raise.clone()) + }); let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin); let now = pass::root_frame_nr(ctx); let (order, to_top, floats, asked) = with_persist(ctx, viewport, |persist| { @@ -906,12 +909,23 @@ pub(crate) fn end_pass(ctx: &Context) { .filter(|entry| entry.parent.is_none_or(|parent| !current.iter().any(|other| other.id == parent))) .map(|entry| entry.id) .collect(); + let mut asked: Vec = Vec::new(); for root in &roots { - if !last_ids.contains(root) { - stamp(*root, persist); + let shown = current.iter().find(|entry| entry.id == *root); + // A root the last pass did not have appears, and so does one that faded out then and is open again + // (`reopened`): it shows over whatever the fade let over it. + let kept = last.iter().any(|(id, _)| id == root); + let reopened = last.iter().any(|(id, exiting)| id == root && *exiting) && shown.is_none_or(|entry| !entry.exiting); + if kept && !reopened { + continue; + } + stamp(*root, persist); + // A root that reopens during its own fade is raised in egui's area order as a press raises it: egui showed + // its area in the pass before, so it raises none. A root that first shows there is raised by egui itself. + if reopened && shown.is_some_and(|entry| !entry.window && (entry.rank == Rank::Window || entry.among_windows)) { + asked.push(*root); } } - let mut asked: Vec = Vec::new(); for id in raise { let mut at = current.iter().find(|entry| entry.id == id); while let Some(parent) = at.and_then(|entry| entry.parent).and_then(|parent| current.iter().find(|other| other.id == parent)) { diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index 50d32a7146..1ebc4dc6bc 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -522,6 +522,46 @@ fn a_flyout_stands_among_the_floating_windows_in_their_order() { assert_eq!(clicks.get(), 1, "and a press at the button now reaches it"); } +/// A flyout closed and opened again while its exit fade runs is raised over the window the fade let in front of it. A +/// flyout stands in the floating windows' order, where egui raises a layer when it first shows and when it is pressed, +/// and it does neither for a layer that shows again while its area is still up. +#[trial] +fn a_flyout_opened_again_during_its_fade_is_above_the_window_over_it() { + let workspace = Rc::new(RefCell::new(flyout_dock(None))); + let flyout = Rc::new(Cell::new(None)); + let mut panels = UnderWindow { flyout: Rc::clone(&flyout), clicks: Rc::new(Cell::new(0)) }; + let (held, specs, pass_rect) = (Rc::clone(&workspace), Tracked::new(Sides), Rc::clone(&flyout)); + let mut fixture = Fixture::new(move |ui| { + // The cell holds this pass's flyout rect, so a flyout that does not show reads as `None`. + pass_rect.set(None); + let config = DockConfig::default().native_windows(false); + let shown = Bind::given(Arc::clone(&held.borrow())); + DockArea::new("Flyout dock", shown, &specs, &mut panels, config).show(ui); + }); + fixture.room(Vec2::new(900.0, 600.0)).settle(); + let icon = fixture.by_label("Alpha").expect("Alpha's icon").rect.center(); + fixture.click_at(icon).settle(); + let open = flyout.get().expect("Alpha's flyout shows its group"); + // A point of the flyout's own top that the floating window covers too. + let tab = Pos2::new(open.left() + 60.0, open.top() + 40.0); + let ctx = fixture.ctx().clone(); + let flyout_layer = ctx.layer_id_at(tab).expect("the flyout shows at its tab"); + + // The floating window shows over the flyout, as the newest layer, so it is on top where they overlap. + *workspace.borrow_mut() = flyout_dock(Some(window_over(open))); + fixture.settle(); + let window_layer = ctx.layer_id_at(tab).expect("the window over the flyout shows"); + assert_ne!(window_layer, flyout_layer, "the window over the flyout is the layer on top at its tab"); + + // Closed, the flyout fades out over the nine frames of its 150 ms fade at 1/60 s rather than at once. + fixture.frame(vec![pointer::moved(icon)]).frame(vec![pointer::press(icon)]).frame(vec![pointer::release(icon)]); + assert!(flyout.get().is_some(), "the closed flyout still shows while its exit fade runs"); + // Opened again in the fade, the flyout is the newer layer and takes the top back. + fixture.frame(vec![pointer::moved(icon)]).frame(vec![pointer::press(icon)]).frame(vec![pointer::release(icon)]).frame(Vec::new()); + assert!(flyout.get().is_some(), "the icon opens the flyout again while it fades"); + assert_eq!(ctx.layer_id_at(tab), Some(flyout_layer), "the flyout opened again during its fade is above the window over it"); +} + #[derive(PlainData)] struct RailWithMenu; From d17976c5b4c183e89e5620e5b07b16888418dc83 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Thu, 26 Nov 2026 04:01:46 +0100 Subject: [PATCH 24/27] Flyout order trial: run the exit fade out before opening the flyout again a_flyout_stands_among_the_floating_windows_in_their_order clicked the icon of the open panel, settled, and read the flyout gone. A closed flyout still shows its group over the nine frames of its 150 ms exit fade at 1/60 s, and a settle runs four: the trial read the fade, not the close, and failed on the hosted runner. The step now runs frames until the flyout has gone, bounded by the fade's frames, and asserts the close after them; the icon then opens the flyout as the layer that shows after the window, which is what the press and raise steps below the trial check. The fade the trial crosses is the one a_flyout_opened_again_during_its_fade_is_above_the_window_over_it opens the flyout in, and it still holds: no framework code changes here. --- crates/ui-patterns/tests/it/docking/columns.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index 1ebc4dc6bc..1ddd561c1d 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -426,6 +426,10 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses /// How tall the flyout of [`UnderWindow`]'s Alpha group measures. const FLYOUT_HEIGHT: f32 = 300.0; +/// The frames a flyout closed in a pass still shows its group over: its 150 ms `motion.open` exit fade at 1/60 s, which +/// is nine, and a few to spare. A `settle` runs four. +const FLYOUT_FADE_FRAMES: usize = 12; + /// Panels for a docked flyout under a floating window: Alpha's group, in the flyout, is a view that measures /// [`FLYOUT_HEIGHT`] and records the rect it shows in, this pass; Beta, in the window, shows a button that counts its /// clicks. @@ -502,8 +506,15 @@ fn a_flyout_stands_among_the_floating_windows_in_their_order() { let flyout_layer = ctx.layer_id_at(Pos2::new(open.left() + 8.0, open.center().y)).expect("the flyout shows beside the window"); assert_ne!(flyout_layer, window_layer, "the flyout and the window are layers of their own: {flyout_layer:?}"); - // Closed and opened again, the flyout is the one opened after the window. - fixture.click_at(icon).settle(); + // Closed and opened again, the flyout is the one opened after the window. A closed flyout keeps showing over the + // frames of its exit fade, more than a settle runs, so the icon is clicked again once they have run. + fixture.click_at(icon); + for _ in 0..FLYOUT_FADE_FRAMES { + if flyout.get().is_none() { + break; + } + fixture.frame(Vec::new()); + } assert!(flyout.get().is_none(), "the icon of the open panel closes its flyout"); fixture.click_at(icon).settle(); let open = flyout.get().expect("the flyout is open again"); From bf307d9f0ea38bd13908331377fb0849fc8ba7d4 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Thu, 26 Nov 2026 04:38:24 +0100 Subject: [PATCH 25/27] Flyout order trial: probe the window's foot, the one part clear of the flyout a_flyout_stands_among_the_floating_windows_in_their_order read the floating window's layer at a corner 24 points in from the window's top and end edges, then pressed there to raise the window. A flyout opens as wide as the dock's column, 340 points, while window_over starts the window 40 points inside the flyout and makes it 300 wide, so the window's end edge meets the flyout's end edge: that corner lay inside the flyout at both of the flyout's opens, and the assert that it lies clear of the flyout failed. The reopened flyout is neither wider nor placed otherwise than the first open: its width is the group's saved width else the column's expanded width and its height the group's own else the body's measure, read every pass from the column, the theme and the body and never from the layer, and the rect it reported, 340 by 300 at (40, 31), is exactly that plan. The window's rect comes from the first open, and the corner read gives the first open the same (40, 31), so both opens are the same rect and no framework code changes here. The window reaches 90 points past the flyout's foot, so the trial probes there: a point 24 points below the flyout's foot at the flyout's centre, in the window's body, clear of its edges and of the fixed layer's. It asserts the point lies in the window and clear of the flyout before reading the window's layer there, and clear of the reopened flyout before the press, so the press that raises the window cannot land on the flyout. window_over's doc gives the window's geometry that the probe relies on. --- crates/ui-patterns/tests/it/docking/columns.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index 1ddd561c1d..7102d58c88 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -468,8 +468,9 @@ fn flyout_dock(window: Option) -> Arc> { Arc::new(Workspace::new(Layout::new(Some(root), windows))) } -/// The rect of the floating window of [`flyout_dock`] over the flyout at `flyout`: it starts inside the flyout, so -/// the window's button lies over it, and reaches past its end edge and bottom, so part of the window lies clear of it. +/// The rect of the floating window of [`flyout_dock`] over the flyout at `flyout`: it starts 40 points inside the +/// flyout, so the window's button lies over it, and it reaches past the flyout's foot; at the flyout's own width, the +/// dock's column, its end edge meets the flyout's, so the window's foot alone lies clear of the flyout. fn window_over(flyout: Rect) -> Rect { Rect::from_min_size(flyout.min + Vec2::new(40.0, 30.0), Vec2::new(300.0, 360.0)) } @@ -499,8 +500,14 @@ fn a_flyout_stands_among_the_floating_windows_in_their_order() { let window = window_over(open); *workspace.borrow_mut() = flyout_dock(Some(window)); fixture.settle(); - // The window is there and the flyout too; a corner of the window clear of the flyout names the window's layer. - let clear = Pos2::new(window.right() - 24.0, window.top() + 24.0); + // The window is there and the flyout too; a point of the window's foot, below the flyout's foot, names the window's + // layer. The flyout opens as wide as the dock's column, while the window starts 40 points inside it and is 300 + // wide, so the window's end edge meets the flyout's: of the window, only its foot lies clear of the flyout. + let clear = Pos2::new(open.center().x, open.bottom() + 24.0); + assert!( + window.contains(clear) && !open.contains(clear), + "the window's foot lies in the window and clear of the flyout: {clear:?} in {window:?}, clear of {open:?}" + ); let ctx = fixture.ctx().clone(); let window_layer = ctx.layer_id_at(clear).expect("the floating window shows"); let flyout_layer = ctx.layer_id_at(Pos2::new(open.left() + 8.0, open.center().y)).expect("the flyout shows beside the window"); @@ -525,7 +532,7 @@ fn a_flyout_stands_among_the_floating_windows_in_their_order() { assert_eq!(clicks.get(), 0, "and the press there does not reach the window's button"); // A press on the window where the flyout does not reach raises the window, as a press raises any floating window. - assert!(!open.contains(clear), "the window's corner lies clear of the flyout: {clear:?} in {open:?}"); + assert!(!open.contains(clear), "the window's foot lies clear of the reopened flyout: {clear:?} in {open:?}"); fixture.frame(vec![pointer::moved(clear)]).frame(vec![pointer::press(clear)]).frame(vec![pointer::release(clear)]).settle(); assert!(flyout.get().is_some(), "the flyout stays open: Auto-Collapse Iconic Panels is off"); assert_eq!(ctx.layer_id_at(button), Some(window_layer), "the pressed window is in front of the flyout"); From 05345c06d35cafaf2fdfa5dda212c5b564f894c2 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Thu, 26 Nov 2026 23:17:50 +0100 Subject: [PATCH 26/27] Dock windows: the `DragBounds` summary says both policies and the default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviewer finding on #3446: the summary ended at a colon ("How much of a floating layer stays inside the window when the user moves it, when it is placed at a position, and ..."), and the catalog lists that line only — a variant's own doc is never extracted. So the line is now a complete summary: the whole layer (`Inside`, the default) or a strip of its title, with where the rule holds and the overlay's own `bounds` in the paragraph under it. The variants keep their detailed docs for rustdoc. Regenerated with the branch's own generator; a second run leaves the file byte for byte as it was. The run also picks up two entries the branch's merges added without regenerating (`Action::restore`, and `floated`'s doc). --- crates/ui-contract/src/contract/overlay/place.rs | 9 +++++---- docs/contract-api.md | 7 ++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index 842aab0b82..6b939084c5 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -61,10 +61,11 @@ impl FloatPlace { } } -/// How much of a floating layer stays inside the window when the user moves it, when it is placed at a position, and -/// when it shows at the placement a pass stored: the window's safe rect, cut to the overlay's -/// [`bounds`](super::Overlay::bounds) when it sets them. Bounds of the overlay's own still hold the whole layer while -/// the user moves it. +/// How much of a floating layer stays inside the window: the whole layer (`Inside`, the default) or a strip of its title. +/// +/// It holds while the user moves the layer, when the layer is placed at a position, and when it shows at the placement +/// a pass stored: the window's safe rect, cut to the overlay's [`bounds`](super::Overlay::bounds) when it sets them. +/// Bounds of the overlay's own still hold the whole layer while the user moves it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DragBounds { diff --git a/docs/contract-api.md b/docs/contract-api.md index 82cd867b2d..c06b1a011f 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -504,7 +504,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `craft_behavior::dock::DockSide`: `pub enum DockSide { Start, End, Top, Bottom, Center }`. The side of a group a dropped panel docks on, in reading order: `Start` is the left half in a left-to-right - `pub const fn axis(self) -> Option`. The axis the side splits along; `None` for `Center`. - `pub fn area(self, group: Rect) -> Rect`. The part of `group` a panel docked on this side takes: the half on that side, or the whole group. -- `craft_behavior::dock::Action`: `pub enum Action

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect, edge: Option }, ResizeSplit { path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, SetColumnSteps { panel: P, steps: u16 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

} }`. Groups, columns and floating windows are named by a panel they contain. +- `craft_behavior::dock::Action`: `pub enum Action

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect, edge: Option }, ResizeSplit { path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, SetColumnSteps { panel: P, steps: u16 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

}, Restore { panel: P, location: Location

} }`. Groups, columns and floating windows are named by a panel they contain. - `pub fn move_beside(panel: P, anchor: P, placement: DockPlacement

) -> Self`. Builds [`Action::Move`]. - `pub fn float(panel: P, rect: Rect) -> Self`. Builds [`Action::Float`]. - `pub fn close(panel: P) -> Self`. Builds [`Action::Close`]. @@ -533,6 +533,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn resize_iconic(panel: P, width: Option) -> Self`. Builds [`Action::ResizeIconic`]. - `pub fn set_native(panel: P, placement: Option) -> Self`. Builds [`Action::SetNative`]. - `pub fn move_panel(panel: P, to: Target

) -> Self`. Builds [`Action::MovePanel`]. + - `pub fn restore(panel: P, location: Location

) -> Self`. Builds [`Action::Restore`]. - `craft_behavior::dock::Arrangement`: `pub enum Arrangement { TileAllVertically, TileAllHorizontally, TwoUpVertical, TwoUpHorizontal, ThreeUpVertical, ThreeUpHorizontal, ThreeUpStacked, FourUp, SixUp, ConsolidateAllToTabs, Cascade, Tile, FloatInWindow, FloatAllInWindows, NewWindowForDocument, MatchZoom, MatchLocation, MatchRotation, MatchAll }`. One Window › Arrange entry. The n-up entries split the document area into that many - `pub fn group_count(self, documents: usize) -> Option`. How many document groups an n-up or tile arrangement wants, `None` for the window and - `pub fn enabled(self, documents: usize, groups: usize, floating: usize) -> bool`. Whether the entry is enabled with `documents` open and `floating` floating windows: @@ -633,7 +634,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn version(&self) -> u32`. The format version the workspace was read with. - `pub fn layout(&self) -> &Layout

`. The current arrangement. - `pub fn hidden(&self) -> &[(P, Location

)]`. The closed panels, and panels the application does not register now, with where each one goes back. - - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels with the docked location each one left. + - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels, and the closed panels that were floating, with the docked location each one left. - `pub fn revision(&self) -> Revision`. The revision of this workspace value: it moves with every write, and no other value has it. - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a @@ -2823,7 +2824,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub const fn on_activate(mut self, on: bool) -> Self`. Closes when a component inside is activated, except an opener toggling its popup. - `pub const fn commands(mut self, on: bool) -> Self`. Closes when a key, a native menu pick or the palette runs a command from outside it; off for a layer its host - `pub const fn timeout(mut self, seconds: Option) -> Self`. Closes after `seconds`. -- `craft_ui::contract::overlay::DragBounds`: `pub enum DragBounds { Inside, TitleVisible }`. How much of a floating layer stays inside the window when the user moves it, when it is placed at a position, and +- `craft_ui::contract::overlay::DragBounds`: `pub enum DragBounds { Inside, TitleVisible }`. How much of a floating layer stays inside the window: the whole layer (`Inside`, the default) or a strip of its title. - `craft_ui::contract::overlay::FloatPlace`: `pub struct FloatPlace { pub pos: Option, pub corner: Align2 }`. Where a floating layer sits. - `pub const fn centred() -> Self`. Centred in the viewport. - `pub const fn at(pos: Pos2) -> Self`. With its left-top at `pos`. From 98422dfab5a5cef789daa37fd4270b7885abd57e Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Fri, 27 Nov 2026 04:58:09 +0100 Subject: [PATCH 27/27] cargo fmt: wrap the merged OpenEntry::new call as rustfmt asks --- crates/ui-contract/src/contract/overlay/host.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 538ad6736f..c44e356766 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -531,8 +531,13 @@ pub(crate) fn host_window(ctx: &Context, layer: &Layer<'_>, rect: Rect) -> Layer let overlay = layer.overlay; let mut memory = recall(layer, ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); - let mut entry = - OpenEntry::new(layer.id, overlay.rank, overlay.keys, rect, areas::layer_of(overlay::layer_tier(ctx, overlay.rank, overlay.among_windows), area_id(layer.id))); + let mut entry = OpenEntry::new( + layer.id, + overlay.rank, + overlay.keys, + rect, + areas::layer_of(overlay::layer_tier(ctx, overlay.rank, overlay.among_windows), area_id(layer.id)), + ); entry.role = overlay.role; entry.scoped = scope.is_some(); entry.window = true;