fw sync: floating window bodies keep to the window's rounded corners (frame_surfaces, FloatingGroup::rounded_body, DockConfig::floating_rounded_body); CaptionColumn env value for inline forms

Trial a_rounded_window_body_keeps_its_surfaces_inside_the_rounded_corners (ui-patterns docking/floating_rail.rs).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Dylan M. Taylor
2026-11-23 12:24:54 -05:00
co-authored by Claude
parent 40442e2f69
commit e93d468b76
14 changed files with 268 additions and 10 deletions
+1 -1
View File
@@ -13,5 +13,5 @@ mod step;
pub use leaf::colon_of;
pub(crate) use place::{control_after, label_gap};
pub(crate) use props::inside;
pub use props::{CellWidth, FieldLayout, GlyphLabel, InsideLabel, LabelKind, LabelScheme, Scrub, SideLabel};
pub use props::{CaptionColumn, CellWidth, FieldLayout, GlyphLabel, InsideLabel, LabelKind, LabelScheme, Scrub, SideLabel};
pub(crate) use step::{LabelIn, LeafLabel, Trailing, flow_leaf, in_column, leaf, leaf_under, report_after_reach, run, show_leaf_in_flow};
@@ -1,7 +1,7 @@
//! Where the label and its control sit: the beside, above and after placements and the gap.
use super::leaf::{LabelLeaf, colon};
use super::props::{FieldLayout, LabelKind, LabelScheme};
use super::props::{CaptionColumn, FieldLayout, LabelKind, LabelScheme};
use super::step::LabelIn;
use crate::contract::Show;
use crate::runtime::access::scope::{self};
@@ -110,8 +110,9 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids:
let (column, stack_below) = match input.side.layout {
FieldLayout::Beside => {
let own = natural.x;
// An inline form shares no label column: each caption is as wide as its own text.
let shared = env.values.get::<LabelScheme>() != LabelScheme::Inline;
// An inline form shares no label column unless it asks for one ([`CaptionColumn`]): each caption is as wide
// as its own text.
let shared = env.values.get::<LabelScheme>() != LabelScheme::Inline || env.values.get::<CaptionColumn>().shared();
let width = crate::layout::ambient_width(ctx, &if glyph { crate::layout::GLYPHS } else { crate::layout::LABELS }, own)
.filter(|width| shared && *width > 0.0)
.unwrap_or(own);
@@ -92,6 +92,31 @@ impl crate::runtime::env::EnvValue for LabelScheme {
}
}
/// Whether the beside captions of a [`LabelScheme::Inline`] form share one column. Off (the default), each caption is
/// as wide as its own text and its control follows it at once. On, the captions keep to the row start in one column as
/// wide as the widest, so the controls after them line up (production's Rotate Pages dialog: Direction:, Pages: and
/// Rotate: in a column). Other schemes always share their column.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)]
pub struct CaptionColumn(bool);
impl CaptionColumn {
/// The captions share one column.
pub const SHARED: CaptionColumn = CaptionColumn(true);
/// Each caption is as wide as its own text (the default).
pub const OWN: CaptionColumn = CaptionColumn(false);
/// Whether the captions share one column.
pub const fn shared(self) -> bool {
self.0
}
}
impl crate::runtime::env::EnvValue for CaptionColumn {
fn root() -> Self {
CaptionColumn::OWN
}
}
/// Where a side label sits relative to its control.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
+1 -1
View File
@@ -92,7 +92,7 @@ pub use items::{ColumnCommands, SweepApply, SweepStep, item_part_open, request_r
pub use items::{measure_item, show_item, show_item_in_flow};
#[doc(hidden)]
pub use label::colon_of;
pub use label::{CellWidth, FieldLabelRole, FieldLayout, GlyphLabel, InsideLabel, LabelKind, LabelScheme, Scrub, SideLabel};
pub use label::{CaptionColumn, CellWidth, FieldLabelRole, FieldLayout, GlyphLabel, InsideLabel, LabelKind, LabelScheme, Scrub, SideLabel};
pub use lazy::Lazy;
#[doc(hidden)]
#[cfg(feature = "suite")]
@@ -84,7 +84,8 @@ pub(crate) fn paint_surface(ui: &Ui, env: &Env, core: &CxCore<'_>, style: &dyn S
if core.faded {
core.paint.borrow_mut().surface_radius = look.radius;
}
let shapes = surface_look_shapes(&env.tokens, look, &core.state, core.rect, env.direction, ui.ctx().pixels_per_point());
let mut shapes = surface_look_shapes(&env.tokens, look, &core.state, core.rect, env.direction, ui.ctx().pixels_per_point());
crate::primitives::fit_to_frame(ui.ctx(), ui.layer_id(), &mut shapes);
match core.surface_slot {
Some(slot) => ui.painter().set(slot, egui::Shape::Vec(shapes)),
None => {
+12 -1
View File
@@ -587,7 +587,18 @@ impl<'a> Draw<'a> {
/// Paints a surface of `kind` (tracks, plot wells).
pub fn surface(&self, rect: Rect, kind: SurfaceKind, corners: Corners) {
let style = surface_style(self.env.tokens, kind);
self.painter.extend(Surface::shapes(&style, None, rect, corners, self.env.direction, self.painter.pixels_per_point()));
let mut shapes = Surface::shapes(&style, None, rect, corners, self.env.direction, self.painter.pixels_per_point());
super::fit_to_frame(self.painter.ctx(), self.painter.layer_id(), &mut shapes);
self.painter.extend(shapes);
}
/// Paints the edge alone of a surface of `kind` over `rect`, with no shadow or fill: a floating window draws its
/// edge again over its content, which covers it where it reaches the window's sides.
pub fn surface_edge(&self, rect: Rect, kind: SurfaceKind) {
let mut style = surface_style(self.env.tokens, kind);
style.shadow = None;
style.fill = egui::Color32::TRANSPARENT;
self.painter.extend(Surface::shapes(&style, None, rect, Corners::All, self.env.direction, self.painter.pixels_per_point()));
}
/// Paints a surface of an already resolved `style` (a kind's look with one field changed, as a knob's round radius).
+2 -2
View File
@@ -53,8 +53,8 @@ pub use rule::{RectSide, Rule, RuleKind};
pub use scroll_bar::{HiddenContent, ScrollBar};
pub use sensing::{PartResult, TextOutcome, cancel_press_of, member_gesture_running};
pub use state_layer::{StateLayer, StateLayerKind};
pub use surface::Surface;
pub(crate) use surface::SurfaceSlot;
pub(crate) use surface::{Frames as SurfaceFrames, SurfaceSlot, fit_to_frame};
pub use surface::{Surface, frame_surfaces};
pub use surround::paint_surround;
#[cfg(feature = "testing")]
pub(crate) use svg_set::Layer;
@@ -43,6 +43,80 @@ impl Surface {
}
}
/// The rounded frames surfaces keep to, at most one per layer: a floating window's body ([`frame_surfaces`]).
#[derive(Default)]
pub(crate) struct Frames(Vec<(crate::runtime::egui::areas::Layer, Rect, CornerRadius)>);
/// The most layers that keep a frame at once: the frame a closed window left gives way to newer ones.
const MOST_FRAMES: usize = 32;
/// How far a surface's edge may lie from the frame's and still meet it, in points: the rounding to the pixel grid.
const FRAME_SLACK: f32 = 0.75;
/// Rounds the surfaces painted from here on in `ui`'s layer that meet a corner of `rect`: such a surface takes
/// `radius` at that corner where its own is smaller. A floating window sets its body's rect and its own lower corners,
/// so the square surfaces of the panels and rails inside it (a dock column, a tool rail's chrome) keep to its rounded
/// corners instead of covering them.
pub fn frame_surfaces(ui: &Ui, rect: Rect, radius: CornerRadius) {
// A measuring run paints nothing.
if crate::runtime::measure::active(ui.ctx()) {
return;
}
let layer = ui.layer_id();
crate::runtime::pass_state::with::<Frames, _>(ui.ctx(), |frames| {
frames.0.retain(|(at, ..)| *at != layer);
if frames.0.len() >= MOST_FRAMES {
frames.0.remove(0);
}
frames.0.push((layer, rect, radius));
});
}
/// Fits `shapes`, painted in `layer`, to the layer's frame ([`frame_surfaces`]); a layer without one keeps them.
pub(crate) fn fit_to_frame(ctx: &egui::Context, layer: crate::runtime::egui::areas::Layer, shapes: &mut [Shape]) {
if crate::runtime::measure::active(ctx) {
return;
}
let frame = crate::runtime::pass_state::with::<Frames, _>(ctx, |frames| {
frames.0.iter().find(|(at, ..)| *at == layer).map(|(_, rect, radius)| (*rect, *radius))
});
let Some((rect, radius)) = frame else { return };
for shape in shapes {
fit_shape(shape, rect, radius);
}
}
/// Rounds each corner of a rect `shape` that meets the same corner of `frame` to at least the frame's radius there.
fn fit_shape(shape: &mut Shape, frame: Rect, radius: CornerRadius) {
match shape {
Shape::Rect(rect) => {
let near = |a: f32, b: f32| (a - b).abs() <= FRAME_SLACK;
let at = rect.rect;
let (left, right) = (near(at.left(), frame.left()), near(at.right(), frame.right()));
let (top, bottom) = (near(at.top(), frame.top()), near(at.bottom(), frame.bottom()));
let corners = &mut rect.corner_radius;
if top && left {
corners.nw = corners.nw.max(radius.nw);
}
if top && right {
corners.ne = corners.ne.max(radius.ne);
}
if bottom && left {
corners.sw = corners.sw.max(radius.sw);
}
if bottom && right {
corners.se = corners.se.max(radius.se);
}
}
Shape::Vec(shapes) => {
for shape in shapes {
fit_shape(shape, frame, radius);
}
}
_ => {}
}
}
/// The surface under content that runs before its rect is known: [`reserve`](SurfaceSlot::reserve) takes its place in
/// the paint order, [`paint`](SurfaceSlot::paint) fills it at the rect the content took.
pub(crate) struct SurfaceSlot {
@@ -92,6 +92,7 @@ pass_state! {
shrink_reports: crate::layout::body::ShrinkReports,
least_reports: crate::layout::body::LeastReports,
bar_rules: crate::contract::BarRules,
surface_frames: crate::primitives::SurfaceFrames,
fill_counts: crate::layout::body::FillCounts,
held_widths: crate::layout::body::HeldWidths,
first_lines: crate::layout::body::FirstLines,
+12
View File
@@ -76,6 +76,10 @@ pub struct DockConfig {
/// A floating window's title row is a bare grip (no menu, float or close action, no column arrow): a quick-action
/// strip's look.
pub floating_grip: bool,
/// The surfaces inside a floating window keep to its rounded corners, and its edge shows over them along its
/// sides ([`FloatingGroup::rounded_body`](super::FloatingGroup)): a floating tool rail reads as one rounded piece.
/// Off: the panels and rails inside paint their own square surfaces to the window's edge.
pub floating_rounded_body: bool,
/// Shows a close button on the tabs of closable panels in docked and floating groups, where a middle click also
/// closes them, for tabs that act as documents. Off: panels close from their menu. Accordion headers and iconic
/// columns never show it.
@@ -110,6 +114,7 @@ impl Default for DockConfig {
close_menu_items: true,
close_button: true,
floating_grip: false,
floating_rounded_body: false,
tab_close_buttons: false,
titled_headers: false,
wheel_selects_tabs: false,
@@ -205,6 +210,13 @@ impl DockConfig {
self
}
/// A floating window's body keeping to its rounded corners on or off ([`floating_rounded_body`](Self::floating_rounded_body)).
#[must_use]
pub fn floating_rounded_body(mut self, on: bool) -> Self {
self.floating_rounded_body = on;
self
}
/// Close buttons on tabs on or off.
#[must_use]
pub fn tab_close_buttons(mut self, on: bool) -> Self {
+18 -1
View File
@@ -267,6 +267,10 @@ pub struct FloatingGroup<'a> {
/// column arrow and no rule under it: a quick-action strip's look.
#[prop]
grip: bool,
/// The surfaces the body paints keep to the window's rounded lower corners (`frame_surfaces`), and the window's
/// edge is drawn again over the body, which covers it along the sides: the window reads as one rounded piece.
#[prop]
rounded_body: bool,
/// Always open: the caller shows the group while its window exists, and a close comes out as the Close action.
open: Bind<'a, bool>,
taken: Option<HeaderAction>,
@@ -323,6 +327,7 @@ impl<'a> FloatingGroup<'a> {
menu: None,
actions: ACTIONS.to_vec(),
grip: false,
rounded_body: false,
open: Bind::given(true),
taken: None,
menu_opener: None,
@@ -394,7 +399,16 @@ impl<'a> FloatingGroup<'a> {
let mount = self.mount();
self.props = self.props.mount(mount);
let minimized = self.minimized;
let shown = self.show(ui, |ui, cx| (!minimized).then(|| body(ui, cx)));
// The window's lower corners: its body ends at the window's foot and sides.
let window = UiTokens::corner(env.tokens.shape.radius.window);
let lower = egui::CornerRadius { nw: 0, ne: 0, sw: window.sw, se: window.se };
let rounded = self.rounded_body;
let shown = self.show(ui, |ui, cx| {
if rounded {
crate::primitives::frame_surfaces(ui, cx.rect, lower);
}
(!minimized).then(|| body(ui, cx))
});
Inner { output: shown.output, inner: shown.inner.flatten(), settle: shown.settle }
}
@@ -494,6 +508,9 @@ impl Component for FloatingGroup<'_> {
/// The double arrow, over the title row's surface.
fn paint_over(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
if self.rounded_body {
ui.draw().surface_edge(cx.rect, SurfaceKind::Floating);
}
let Some(column) = self.column.filter(|_| self.chevron_declared) else { return };
paint_chevron(ui, column.edge, column.arrow, column.collapsed.is_none(), cx.flow.is_rtl(), &cx.words::<DockWords>());
}
@@ -1522,6 +1522,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
.column(shape)
.actions(actions)
.grip(scene.config.floating_grip)
.rounded_body(scene.config.floating_rounded_body)
.window_of(anchor.clone())
.takes_drops(target, &dropped)
.command_scope(DockCommands::SCOPE)
@@ -0,0 +1,114 @@
//! A floating tool rail window: the window and every surface its content paints keep the window's rounded corners.
use craft_behavior::dock::{Column, Floating, Group, Layout, Workspace};
use craft_ui::contract::{Bind, BodyCx, Tracked};
use craft_ui::docking::{DockConfig, DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs};
use craft_ui::patterns::dock::DockArea;
use craft_ui::rails::{LastUsed, RailTool, ToolRail, ToolSlot};
use craft_ui::testing::{Fixture, trial};
use egui::{Pos2, Rect, Ui, Vec2};
use std::sync::Arc;
const RAIL: usize = 1;
const WINDOW_AT: Rect = Rect { min: Pos2::new(100.0, 40.0), max: Pos2::new(148.0, 440.0) };
#[derive(craft_ui::contract::PlainData)]
struct Specs;
impl PanelSpecs<usize> for Specs {
fn spec(&self, _: &usize) -> PanelSpec {
PanelSpec::new("Toolbar").grid(DockGrid::rail(4))
}
}
struct Panels {
slots: Tracked<Vec<ToolSlot<u8>>>,
last: Tracked<LastUsed<u8>>,
}
impl DockPanels<usize> for Panels {
fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {}
fn group_view(&mut self, _: &[usize], _: usize, ui: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option<f32> {
let rail = ToolRail::new("Toolbar", &self.slots, &0u8, &self.last);
match at {
GroupAt::Measure(width) => Some(rail.measure_rail(ui, width, |_, _| {}).y),
GroupAt::Show(rect) => {
rail.show_rail(ui, |_, _| {});
Some(rect.height())
}
}
}
}
fn panels() -> Panels {
let slots = (0..4u8).map(|id| ToolSlot::new(u32::from(id), vec![RailTool::new(id, craft_ui::runtime::commands::EditCommands::Undo)])).collect();
Panels { slots: Tracked::new(slots), last: Tracked::new(LastUsed::default()) }
}
/// The window's own surface: the rect painted at its place with an opaque fill and round corners.
fn window_of(shapes: &[(Rect, egui::Shape)]) -> egui::epaint::RectShape {
let mut rects = shapes.iter().filter_map(|(_, shape)| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None });
let window = rects.find(|rect| rect.fill.a() == 255 && (rect.rect.min - WINDOW_AT.min).length() < 1.0 && rect.corner_radius.sw > 0);
window.cloned().unwrap_or_else(|| panic!("the window's surface is painted at {WINDOW_AT:?}"))
}
/// The opaque rect surfaces that reach a lower corner of `window` with a smaller radius there than the window's.
fn square_at_the_foot(shapes: &[(Rect, egui::Shape)], window: &egui::epaint::RectShape) -> Vec<String> {
let near = |a: egui::Pos2, b: egui::Pos2| (a - b).length() <= 0.75;
let (rect, radius) = (window.rect, window.corner_radius);
let mut out = Vec::new();
for (_, shape) in shapes {
let egui::Shape::Rect(inner) = shape else { continue };
if inner.fill.a() < 255 || inner.rect == rect {
continue;
}
let left = near(inner.rect.left_bottom(), rect.left_bottom()) && inner.corner_radius.sw < radius.sw;
let right = near(inner.rect.right_bottom(), rect.right_bottom()) && inner.corner_radius.se < radius.se;
if left || right {
out.push(format!("{:?} {:?}", inner.rect, inner.corner_radius));
}
}
out
}
fn shown(rounded: bool) -> Vec<(Rect, egui::Shape)> {
let layout = Layout::new(None, vec![Floating::new(1, Column::new(vec![Group::new(vec![RAIL], 0)]).with_steps(1), WINDOW_AT)]);
let workspace = std::cell::RefCell::new(Arc::new(Workspace::new(layout)));
let specs = Tracked::new(Specs);
let mut panels = panels();
let mut fixture = Fixture::new(move |ui| {
let mut shown = workspace.borrow().clone();
let config = DockConfig::default().native_windows(false).floating_grip(true).floating_rounded_body(rounded);
let _ = DockArea::new("Dock", Bind::bound(&mut shown), &specs, &mut panels, config).show(ui);
*workspace.borrow_mut() = shown;
});
fixture.room(Vec2::new(600.0, 600.0));
fixture.settle();
fixture.frame_clipped_shapes()
}
/// A floating tool rail (production's quick toolbar) is one rounded piece: the dock column and the rail's chrome inside
/// the window keep to its rounded lower corners, and the window's edge is drawn again over them. Without the opt-in the
/// inner surfaces run square to the window's foot, over its corners.
#[trial]
fn a_rounded_window_body_keeps_its_surfaces_inside_the_rounded_corners() {
let plain = shown(false);
let window = window_of(&plain);
assert!(!square_at_the_foot(&plain, &window).is_empty(), "by default the inner surfaces run square to the window's foot");
let rounded = shown(true);
let window = window_of(&rounded);
let square = square_at_the_foot(&rounded, &window);
assert!(square.is_empty(), "no inner surface squares a corner of {:?}: {square:?}", window.rect);
let rect_at = |at: usize| if let Some((_, egui::Shape::Rect(rect))) = rounded.get(at) { Some(rect) } else { None };
let edge = (0..rounded.len())
.rev()
.find(|at| rect_at(*at).is_some_and(|rect| rect.rect == window.rect && rect.fill.a() == 0 && rect.stroke.width > 0.0));
let inner = (0..rounded.len()).rev().find(|at| {
rect_at(*at).is_some_and(|rect| {
rect.fill.a() == 255 && rect.rect != window.rect && window.rect.contains_rect(rect.rect) && rect.rect.width() >= window.rect.width() - 1.0
})
});
assert!(edge.zip(inner).is_some_and(|(edge, inner)| edge > inner), "the window's edge ({edge:?}) is drawn over the inner surfaces ({inner:?})");
}
@@ -17,6 +17,7 @@ pub(crate) mod drop_session;
pub(crate) mod floating;
pub(crate) mod floating_area;
pub(crate) mod floating_rail;
pub(crate) mod hidden;
pub(crate) mod columns;