Merge branch 'fw/mac1-edges' into fw/mac1

This commit is contained in:
aiongg
2026-11-16 16:20:25 +00:00
30 changed files with 393 additions and 240 deletions
+4 -4
View File
@@ -11,7 +11,7 @@ use craft_behavior::scroll::ScrollSpan;
use craft_behavior::{Axis, EditEvent, Granularity, Intent, Metrics, Mixed, NavMove, PartKey, Sense, Wheel};
use craft_ui::contract::{
Access, Bind, BindMut, CommandSet, Commands as _, Common, Component, Container, ContainerProps, Cx, Edit as _, EditResponse, Focus as _, Name,
Outcome, PaintUi, PartsCx, Pointer as _, Props, Remember as _, Role, Sizing, THUMB, WordSetCx as _,
Outcome, PaintUi, PartsCx, Pointer as _, Props, Remember as _, Role, Sizing, WordSetCx as _,
};
use craft_ui::primitives::{PaintShape, StrokeWidth};
use craft_ui::runtime::access::Numeric;
@@ -19,7 +19,7 @@ use craft_ui::runtime::commands::CommandState;
use craft_ui::runtime::env::{AppValues, EnvValue, EnvView, Label};
use craft_ui::runtime::focus::KeyUse;
use craft_ui::runtime::motion::{Animate as _, spec};
use craft_ui::style::{ComponentStyle, ScrollBarKind, ScrollBarLook, StyleColor, StyleCx};
use craft_ui::style::{ComponentStyle, ScrollBarLook, StyleColor, StyleCx};
use egui::{CornerRadius, Pos2, Rect, Response};
use std::cell::Cell;
use std::ops::Deref;
@@ -447,7 +447,7 @@ impl Component for TimelineView<'_> {
fn style(cx: &StyleCx<'_>, _: TimelineViewStyleKey) -> TimelineViewStyle {
TimelineViewStyle {
metrics: Metrics::new(),
look: cx.scroll_bar(ScrollBarKind::Docked),
look: cx.scroll_bar(),
playhead: cx.color(cx.tokens.color.accent.solid),
snap: cx.color(cx.tokens.color.overlay.line),
marquee_fill: cx.color(cx.tokens.color.accent.soft),
@@ -545,7 +545,7 @@ impl Component for TimelineView<'_> {
let style = cx.style;
let track = self.bar(cx.rect, cx.flow, style);
let span = self.span(&view, width);
ui.draw().scroll_bar(&style.look, track, Axis::X, cx.flow.is_rtl(), &span, &cx.part_state(BAR.at(THUMB)));
ui.draw().scroll_bar(&style.look, track, Axis::X, cx.flow.is_rtl(), &span, &cx.scroll_bar_state(BAR));
}
/// The lines and the marquee over the panes, after the body has reported them.
+7 -13
View File
@@ -1,5 +1,6 @@
//! `CanvasScrollbars`: the scroll bars of a canvas, as Photoshop's document window has them (20.6): a horizontal bar
//! along the bottom of the view and a vertical one along the right, always shown. The thumb is the visible fraction of
//! `CanvasScrollbars`: the scroll bars of a canvas (20.6): a horizontal bar along the bottom of the view and a vertical
//! one along the right, always shown, in the floating look every scroll area has (`ScrollBarLook`): a thin line at rest
//! over the view's edge, the whole bar under the pointer. The thumb is the visible fraction of
//! the scrollable extent (the document, plus wherever the view has been scrolled past it); drag it to scroll, or press
//! the track to page by one screenful. With overscroll on, a document smaller than the window can also be scrolled from
//! one edge of the window to the other. With overscroll off the app clamps the view before it draws
@@ -16,15 +17,14 @@ use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _, Props as _,
Role, Styled as _, THUMB, WordSetCx as _,
};
use crate::primitives::PaintShape;
use crate::runtime::access::Numeric;
use crate::runtime::env::Label;
use crate::runtime::focus::KeyUse;
use crate::style::{ComponentStyle, ScrollBarKind, ScrollBarLook, StyleCx};
use crate::style::{ComponentStyle, ScrollBarLook, StyleCx};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::scroll::ScrollSpan;
use craft_behavior::{Axis, CanvasView, Metrics, PartKey, PartRef, PressPhase};
use egui::{CornerRadius, Pos2, Rect, Response, Vec2};
use egui::{Pos2, Rect, Response, Vec2};
use std::ops::{Deref, Range};
const HORIZONTAL: PartKey = PartKey::new("horizontal");
@@ -242,7 +242,7 @@ impl Component for CanvasScrollbars<'_> {
type Output = CanvasScrollbarsOutput;
fn style(cx: &StyleCx<'_>, _: CanvasScrollbarsStyleKey) -> ScrollbarsStyle {
ScrollbarsStyle { metrics: Metrics::new(), look: cx.scroll_bar(ScrollBarKind::Docked) }
ScrollbarsStyle { metrics: Metrics::new(), look: cx.scroll_bar() }
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
@@ -287,14 +287,8 @@ impl Component for CanvasScrollbars<'_> {
let style = cx.style;
let bars = self.bars(&view, cx.rect, style.look.thickness);
let draw = ui.draw();
if let (Some(h), Some(v)) = (&bars.horizontal, &bars.vertical) {
draw.fill(
&PaintShape::Rect(Rect::from_min_max(Pos2::new(v.rect.left(), h.rect.top()), cx.rect.max), CornerRadius::ZERO),
cx.resolve(&style.look.track),
);
}
for (key, axis, bar) in bars.each() {
draw.scroll_bar(&style.look, bar.rect, axis, cx.flow.is_rtl(), &bar.span, &cx.part_state(thumb_of(key)));
draw.scroll_bar(&style.look, bar.rect, axis, cx.flow.is_rtl(), &bar.span, &cx.scroll_bar_state(key));
}
}
+31 -21
View File
@@ -5,7 +5,7 @@ use super::open::open_now;
use super::placement::{Placement, measure_layer, overlay_of, shown_placement};
use super::regions::{
LabelColumns, LabelsFound, RegionFrame, RegionSizes, RuleBands, end_full_height, footer_in_end, footer_rule_under, gap_of, header_gap_of,
label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line,
label_extra_of, least_of, pad_of, pad_vec, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line,
};
use super::reorder::REORDER_BAND;
use super::scroll::{
@@ -33,7 +33,7 @@ use crate::runtime::overlay::CloseReason;
use crate::runtime::pass_state;
use crate::runtime::{keys, layout_memory, pointer, wheel, windows};
use crate::style::ComponentStyle as _;
use crate::style::{ScrollBarKind, StyleCx, SurfaceKind, band_color, scroll_bar_look, surface_style};
use crate::style::{StyleCx, SurfaceKind, band_color, scroll_bar_look, surface_style};
use craft_behavior::layout_memory::measure_tolerance;
use craft_behavior::{CancelRule, CursorIcon, EditEvent, KeyRole, Mixed, Roving, ScrollPos, ScrollSpan, WheelRoom, WheelTaker};
use egui::{Context, CornerRadius, Id, Pos2, Rect, Shape, Ui, UiBuilder, Vec2};
@@ -283,12 +283,12 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
self.given.1 |= self.over_room(props, &env, at, ui.ctx(), id);
let measured = self.measured_body.unwrap_or(Vec2::ZERO);
let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO };
let room = self.room.x - 2.0 * pad_of(scx.tokens, props.pad);
let room = self.room.x - 2.0 * pad_vec(scx.tokens, props).x;
let width = if self.measured_body.is_some() { self.shared_width(room, props) } else { 0.0 };
self.overflow = self.wanted_width(props).map_or(0.0, |wanted| (wanted - room.max(0.0)).max(0.0));
let (header, end) = (self.measured_header.unwrap_or(Vec2::ZERO), self.measured_end.unwrap_or(Vec2::ZERO));
let height = self.regions_size(props, body, header, self.measured_footer, end).y;
Vec2::new(width, height) + Vec2::splat(2.0 * pad_of(scx.tokens, props.pad))
Vec2::new(width, height) + 2.0 * pad_vec(scx.tokens, props)
}
/// The regions run once in an invisible sizing pass over the room, as `content` runs them, and the container takes
@@ -371,7 +371,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
if at.ui.is_sizing_pass() && self.given == (true, true) && self.room.is_finite() && !scrolled_share {
return self.room;
}
let pad = Vec2::splat(2.0 * pad_of(at.scx.tokens, props.pad));
let pad = 2.0 * pad_vec(at.scx.tokens, &props);
let vertical = scroll_of(&props).is_some_and(|scroll| scroll.vertical_on());
let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx));
// A record a run of this pass left serves as before; a kept one serves only while the inputs it was measured
@@ -539,8 +539,9 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
return None;
}
let tokens = cx.tokens;
let inner = content.shrink(pad_of(tokens, props.pad));
let regions = self.regions(&props, inner, pad_of(tokens, props.pad), self.room_size(rect, inner), rtl, self.measured_sizes());
let pad = pad_vec(tokens, &props);
let inner = content.shrink2(pad);
let regions = self.regions(&props, inner, pad, self.room_size(rect, inner), rtl, self.measured_sizes());
let (_, slots) = self.header_line(regions.header, pad_of(tokens, header.inset), parts, rtl);
Some(std::rc::Rc::new(slots))
}
@@ -550,9 +551,10 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
let ctx = pcx.ui.ctx().clone();
let rtl = pcx.flow.is_rtl();
let tokens = pcx.tokens;
let inner = pcx.content_rect.shrink(pad_of(tokens, props.pad));
let pad = pad_vec(tokens, &props);
let inner = pcx.content_rect.shrink2(pad);
let room = self.room_size(rect, inner);
let regions = self.regions(&props, inner, pad_of(tokens, props.pad), room, rtl, self.measured_sizes());
let regions = self.regions(&props, inner, pad, room, rtl, self.measured_sizes());
let scroll = scroll_of(&props);
if self.open && scroll.is_some() {
let at = regions.body;
@@ -677,8 +679,8 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
let rtl = env.direction.is_rtl();
let node = matches!(C::ROLE, Role::Node(_));
let scroll = scroll_of(&props);
let pad = pad_of(&env.tokens, props.pad);
let inner = cx.core.content_rect.shrink(pad);
let pad = pad_vec(&env.tokens, &props);
let inner = cx.core.content_rect.shrink2(pad);
let room = self.room_size(rect, inner);
let mut regions = self.regions(&props, inner, pad, room, rtl, self.measured_sizes());
let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_)));
@@ -698,6 +700,20 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
register_instances(&ctx, &props, id, window);
}
let region_env = env.derive(|scoped| self.scope_regions(scoped, &props, cx, window, values, real));
// The size and glyph role the container gives its children reach every region: header, body, end region and
// footer.
let region_env = if props.child_size.is_none() && props.child_glyphs.is_none() {
region_env
} else {
region_env.derive_local(|scoped| {
if let Some(size) = props.child_size {
scoped.size = size;
}
if let Some(role) = props.child_glyphs {
scoped.glyphs = role;
}
})
};
let body_id = sub(id, "body");
let gap = Vec2::splat(gap_of(&env.tokens, props.body_gap));
let owner = BodyOwner::new(cx.style, gap.y);
@@ -734,19 +750,13 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
let animated = props.collapse.is_some_and(|collapse| collapse.animated);
let is_open = open || (animated && self.presence.visible);
let enabled = gate.unwrap_or(true);
// What the body and the end region share: gate, size, roving group and commands. The body adds its arena,
// What the body and the end region share: gate, roving group and commands. The body adds its arena,
// transform and scroll owner; the end region lies outside them.
let line_env = if enabled && props.child_size.is_none() && props.child_glyphs.is_none() && props.roving.is_none() {
let line_env = if enabled && props.roving.is_none() {
region_env.clone()
} else {
region_env.derive_local(|scoped| {
scoped.enabled &= enabled;
if let Some(size) = props.child_size {
scoped.size = size;
}
if let Some(role) = props.child_glyphs {
scoped.glyphs = role;
}
if props.roving.is_some() {
scoped.roving = Some(crate::contract::steps::body_group(id));
}
@@ -865,7 +875,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
Some(scroll) => {
let off = self.offset;
let big = crate::contract::MAX_EXTENT;
let bar = scroll_bar_look(&body_env.tokens, ScrollBarKind::Overlay).thickness;
let bar = scroll_bar_look(&body_env.tokens).thickness;
let last = Vec2::new(self.last_extent.0, self.last_extent.1);
let inset = overflow_inset(scroll, last, at.size(), bar);
let shows = view_within(scroll, last, at, self.strip);
@@ -1246,7 +1256,7 @@ impl BodyHooks<'_> {
) -> Vec2 {
let props = Arc::clone(&self.props);
let (id, ctx) = (cx.core.id, at.ui.ctx().clone());
let pad = Vec2::splat(2.0 * pad_of(at.scx.tokens, props.pad));
let pad = 2.0 * pad_vec(at.scx.tokens, &props);
#[cfg(feature = "testing")]
crate::runtime::measure::count_body(&ctx, id);
layout_memory::begin_measure(&ctx, id);
@@ -2,7 +2,7 @@
use super::BodyHooks;
use super::reorder::REORDER_SCOPE;
use crate::contract::{Container, ContainerProps, Cx, DragBand, Mount, PaneEdge, Scroll, Sizing};
use crate::contract::{Container, ContainerProps, Cx, DragBand, Mount, Scroll, Sizing};
use crate::runtime::commands::{self, CommandSet as _, WindowCommand};
use crate::runtime::env::{AppValues, ArenaId, Scoped, ScrollOwner};
use crate::style::{ComponentStyle as _, SurfaceKind};
@@ -104,11 +104,6 @@ impl BodyHooks<'_> {
scoped.arena = Some(ArenaId::new(id));
}
scoped.transform = props.transform;
match &props.mount {
Mount::Pane(pane) if pane.edge != PaneEdge::Center => scoped.pane_edge = Some(pane.edge),
Mount::Inline => {}
_ => scoped.pane_edge = None,
}
scoped.content_column = content_column;
scoped.given_column = !content_column && matches!(props.layout, crate::layout::BodyLayout::Stack);
scoped.row_room = None;
+16 -14
View File
@@ -2,7 +2,7 @@
use super::BodyHooks;
use crate::contract::cx::BodyCx;
use crate::contract::{Container, ContainerProps, FooterPlace, Gap, HeaderParts, LeastWidth, Mount, Pad, PaneEdge, Sizing};
use crate::contract::{Container, ContainerProps, FooterPlace, Gap, HeaderParts, LeastWidth, Mount, Pad, PadEdges, Sizing};
use crate::layout::{ColumnGroup, Columns, Reached};
use crate::primitives::{RectSide, Rule};
use crate::runtime::access::{self};
@@ -49,6 +49,15 @@ pub fn pad_of(tokens: &UiTokens, pad: Pad) -> f32 {
}
}
/// A container's padding on each side along each axis: its tier on the edges its props name, none on the others.
pub(super) fn pad_vec(tokens: &UiTokens, props: &ContainerProps) -> Vec2 {
let pad = pad_of(tokens, props.pad);
match props.pad_edges {
PadEdges::All => Vec2::splat(pad),
PadEdges::Block => Vec2::new(0.0, pad),
}
}
/// The room the rules between a container's regions take, in points: the divider rule's width on the display for each
/// rule the container draws, none for one it doesn't. Each rule lies in a band of its own, so it shares no pixel with
/// a region's content at any scale.
@@ -172,18 +181,11 @@ impl RegionFrame<'_> {
}
}
/// The divider along the inner edge of the edge pane that encloses a container with `edge_rule`, inside `rect`: the
/// edge toward the window's centre, mirrored for a start or end pane under right-to-left.
/// The divider along the inner edge of an edge pane with `edge_rule`, inside `rect`: the edge toward the window's
/// centre (`RectSide::toward_centre`).
pub(super) fn paint_edge_rule(ui: &mut Ui, props: &ContainerProps, env: &Env, rect: Rect) {
let Some(edge) = env.pane_edge.filter(|_| props.edge_rule) else { return };
let rtl = env.direction.is_rtl();
let side = match edge {
PaneEdge::Start => RectSide::end(rtl),
PaneEdge::End => RectSide::start(rtl),
PaneEdge::Top => RectSide::Bottom,
PaneEdge::Bottom => RectSide::Top,
PaneEdge::Center => return,
};
let Mount::Pane(pane) = &props.mount else { return };
let Some(side) = RectSide::toward_centre(pane.edge, env.direction.is_rtl()).filter(|_| props.edge_rule) else { return };
let rule = rule_look(&env.tokens, RuleKind::Divider);
ui.painter().extend(Rule::edge(&rule, rect, side, ui.ctx().pixels_per_point()));
}
@@ -347,7 +349,7 @@ impl<'b> BodyHooks<'b> {
/// The regions inside `inner` (the rect minus padding and the padding tier), placed from `sizes`. A header with a
/// band spreads over the `bleed` the padding leaves around `inner` at the top and the sides.
pub(super) fn regions(&self, props: &ContainerProps, inner: Rect, bleed: f32, room: Vec2, rtl: bool, sizes: RegionSizes) -> Regions {
pub(super) fn regions(&self, props: &ContainerProps, inner: Rect, bleed: Vec2, room: Vec2, rtl: bool, sizes: RegionSizes) -> Regions {
let inline = props.header.is_some_and(|header| header.inline);
let (in_end, full) = (footer_in_end(props), end_full_height(props));
let header_h = if props.header.is_some() { sizes.header.unwrap_or(Vec2::ZERO).y } else { 0.0 };
@@ -456,7 +458,7 @@ impl<'b> BodyHooks<'b> {
_ => band(footer_top, footer_top + footer_h),
};
let header = if props.header.is_some_and(|header| header.fill.is_some()) {
Rect::from_min_max(header.min - Vec2::splat(bleed), Pos2::new(header.max.x + bleed, header.max.y - bleed))
Rect::from_min_max(header.min - bleed, Pos2::new(header.max.x + bleed.x, header.max.y - bleed.y))
} else {
header
};
+5 -10
View File
@@ -11,7 +11,7 @@ use crate::runtime::egui::{repaint, sizing};
use crate::runtime::env::Env;
use crate::runtime::lazy;
use crate::runtime::pass_state;
use crate::style::{ScrollBarKind, SurfaceKind, UiTokens, scroll_bar_look, surface_style};
use crate::style::{SurfaceKind, UiTokens, scroll_bar_look, surface_style};
use craft_behavior::{Axis, PartKey, ScrollPos, ScrollSpan};
use egui::{Context, Id, Pos2, Rect, Ui, Vec2};
@@ -164,7 +164,7 @@ impl BodyHooks<'_> {
/// The edge fades and the scroll bars over the body. The fades blend the content into the surface it sits on.
pub(super) fn paint_scroll_bars<C: Container>(&self, ui: &mut Ui, cx: &Cx<'_, C>, props: &ContainerProps, rtl: bool, env: &Env) {
let tokens = &*env.tokens;
let look = scroll_bar_look(tokens, ScrollBarKind::Overlay);
let look = scroll_bar_look(tokens);
if let Some(at) = self.view
&& let Some(scroll) = scroll_of(props)
&& let Some(strips) = self.strips(scroll, at)
@@ -191,13 +191,8 @@ impl BodyHooks<'_> {
if !overflow {
continue;
}
let enabled = cx.core.looks_enabled();
let state = crate::contract::steps::part_state(
cx.core.results.get(&(bar.key, Some(crate::contract::cx::THUMB))).unwrap_or(&crate::primitives::PartResult::IDLE),
enabled,
None,
);
ui.painter().extend(ScrollBar::shapes(&look, bar.track, bar.axis, rtl, &span, &state, ui.ctx().pixels_per_point()));
let state = cx.core.scroll_bar_state(bar.key);
ui.painter().extend(ScrollBar::shapes(&look, bar.track, bar.axis, rtl, &span, &state));
}
}
}
@@ -280,7 +275,7 @@ impl<'b> BodyHooks<'b> {
pub(super) fn scroll_geometry(&self, props: &ContainerProps, view: Rect, rtl: bool, tokens: &UiTokens) -> Vec<(Bar, ScrollSpan)> {
let Some(scroll) = scroll_of(props) else { return Vec::new() };
let thickness = scroll_bar_look(tokens, ScrollBarKind::Overlay).thickness;
let thickness = scroll_bar_look(tokens).thickness;
let (v_on, h_on) = (scroll.vertical_on(), scroll.horizontal_on());
let (ex, ey) = self.last_extent;
let mut bars = Vec::new();
+32 -7
View File
@@ -137,6 +137,18 @@ pub enum Pad {
Roomy,
}
/// The edges a container's padding tier applies to.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PadEdges {
/// Every edge.
#[default]
All,
/// The top and bottom edges only: a column given its width whose children centre across it, as a tool rail does
/// in its pane.
Block,
}
/// The padding of every popup surface around its content.
pub const POPUP_PAD: Pad = Pad::Control;
@@ -167,6 +179,8 @@ pub enum LeastWidth {
DialogButton,
/// `size.dialog.side_button`: a button in a dialog's column of buttons beside the body.
DialogSideButton,
/// `size.rail.width` per column: a tool rail of this many columns, as wide as the shell slot that holds it.
Rail(std::num::NonZeroU8),
}
impl LeastWidth {
@@ -177,6 +191,7 @@ impl LeastWidth {
LeastWidth::Dialog => tokens.size.dialog.least,
LeastWidth::DialogButton => tokens.size.dialog.button,
LeastWidth::DialogSideButton => tokens.size.dialog.side_button,
LeastWidth::Rail(columns) => tokens.size.rail.width * f32::from(columns.get()),
}
}
}
@@ -672,6 +687,8 @@ pub struct ContainerProps {
pub surface: Option<SurfaceKind>,
/// The padding tier.
pub pad: Pad,
/// The edges the padding tier applies to; a collection pads every edge.
pub pad_edges: PadEdges,
/// How the size follows the content.
pub sizing: Sizing,
/// The height the body offers its children in flow, in place of the flow's (unbounded in a scrolling body): the
@@ -704,12 +721,12 @@ pub struct ContainerProps {
pub least_width: Option<LeastWidth>,
/// The line length of the body's paragraphs while the container takes its width from its content, from a size role.
pub wrap_width: Option<WrapWidth>,
/// A divider along the inner edge of the edge pane the container sits in: the edge that faces the window's centre.
/// Outside an edge pane it draws nothing.
/// A divider along the inner edge of a container mounted as an edge pane (`Mount::Pane` at an edge): the edge that
/// faces the window's centre. Any other container draws nothing.
pub edge_rule: bool,
/// A scope size for the body.
/// A scope size for the regions: header, body, end region and footer.
pub child_size: Option<ControlSize>,
/// A scope glyph role for the body: how the icon-only buttons in it show their glyph.
/// A scope glyph role for the regions: how the icon-only buttons in them show their glyph.
pub child_glyphs: Option<GlyphRole>,
/// The container is an arena root.
pub arena: bool,
@@ -758,6 +775,7 @@ impl ContainerProps {
self.mount == other.mount
&& self.surface == other.surface
&& self.pad == other.pad
&& self.pad_edges == other.pad_edges
&& self.sizing == other.sizing
&& self.room_height == other.room_height
&& self.layout == other.layout
@@ -786,6 +804,7 @@ impl ContainerProps {
mount: Mount::Inline,
surface: None,
pad: Pad::None,
pad_edges: PadEdges::All,
sizing: Sizing::Content,
room_height: None,
layout: BodyLayout::Stack,
@@ -838,6 +857,12 @@ impl ContainerProps {
self
}
/// The edges the padding tier applies to.
pub const fn pad_edges(mut self, edges: PadEdges) -> Self {
self.pad_edges = edges;
self
}
/// How the size follows the content.
pub const fn sizing(mut self, sizing: Sizing) -> Self {
self.sizing = sizing;
@@ -931,19 +956,19 @@ impl ContainerProps {
self
}
/// Draws a divider along the inner edge of the edge pane the container sits in.
/// Draws a divider along the inner edge of a container mounted as an edge pane.
pub const fn edge_rule(mut self, on: bool) -> Self {
self.edge_rule = on;
self
}
/// A scope size for the body.
/// A scope size for the regions: header, body, end region and footer.
pub const fn child_size(mut self, size: ControlSize) -> Self {
self.child_size = Some(size);
self
}
/// A scope glyph role for the body: a rail's buttons show its icons at the rail's side and ink.
/// A scope glyph role for the regions: a rail's buttons show its icons at the rail's side and ink.
pub const fn child_glyphs(mut self, role: GlyphRole) -> Self {
self.child_glyphs = Some(role);
self
+8 -1
View File
@@ -6,7 +6,7 @@ use crate::contract::Component;
use crate::primitives::PartResult;
use crate::runtime::focus::{self};
use crate::style::{Ink, Mix, StateSet, Stateful};
use craft_behavior::PartRef;
use craft_behavior::{PartKey, PartRef};
use craft_theme::Flags;
/// The resolved look (chapter 4); every method reads step 12's output.
@@ -59,6 +59,13 @@ impl CxCore<'_> {
self.part_state_lit(part, false)
}
/// The state set of the scroll bar `bar` (`PartsCx::scroll`): its thumb's, hovered while the pointer is anywhere
/// on the bar or the bar's track is pressed, so the bar shows at its full thickness then.
pub fn scroll_bar_state(&self, bar: PartKey) -> StateSet {
let on_bar = self.part_if_declared(bar).is_some_and(|track| track.hovered || track.pressed());
self.part_state_lit(bar.at(super::THUMB), on_bar)
}
/// The state set of `part`, hovered as well when `lit`: a part the pointer is not over that a press at the pointer
/// would act on.
///
@@ -20,7 +20,7 @@ use crate::runtime::env::{Env, Label};
use crate::runtime::layout_memory;
use crate::runtime::memory::{MemoryStage, sub};
use crate::runtime::words::HeaderWords;
use crate::style::{ComponentStyle, ResizeLineLook, ScrollBarKind, StateSet, StyleColor, StyleCx, TypeRole, resize_line_look, scroll_bar_look};
use crate::style::{ComponentStyle, ResizeLineLook, StateSet, StyleColor, StyleCx, TypeRole, resize_line_look, scroll_bar_look};
use craft_behavior::grid::resolve_columns;
use craft_behavior::{
Axis, ColumnKey, ColumnWidth, CursorIcon, DropOperation, Flow, HitLevel, HitPriority, IconId, Insets, Intent, Metrics, NavMove, NavShape,
@@ -380,7 +380,7 @@ impl Header {
let area = pcx.content_rect;
let view = Rect::from_min_size(area.min, Vec2::new(area.width(), self.height));
self.view = Some(view);
let grip = scroll_bar_look(pcx.tokens, ScrollBarKind::Overlay).thickness;
let grip = scroll_bar_look(pcx.tokens).thickness;
let rtl = pcx.flow.is_rtl();
let widths = self.widths(area.width());
let wide = widths.iter().sum::<f32>().max(area.width());
@@ -21,7 +21,7 @@ use crate::runtime::env::WheelScope;
use crate::runtime::env::{AppValues, ArenaId, Env, ItemFacts};
use crate::runtime::memory::{MemoryStage, sub};
use crate::runtime::{focus, keys, layout_memory, lazy, overlay, wheel};
use crate::style::{ComponentStyle as _, ScrollBarKind, StyleCx, SurfaceKind, UiTokens, scroll_bar_look, surface_style};
use crate::style::{ComponentStyle as _, StyleCx, SurfaceKind, UiTokens, scroll_bar_look, surface_style};
use craft_behavior::{
Axis, CancelReason, EditEvent, Intent, ItemLayout, Mixed, Proposal, ScrollPos, ScrollSpan, SelectionModel, Sense, WheelRoom, WheelTaker,
};
@@ -279,7 +279,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
fn geometry(&mut self, _: &C, mcx: &crate::contract::MeasureCx<'_, C>, (_, content): (Rect, Rect), rtl: bool) -> Option<Rc<dyn std::any::Any>> {
let view = self.below_header(content);
let clear = self.clear_of_bar(view, scroll_bar_look(mcx.tokens, ScrollBarKind::Overlay).thickness, rtl);
let clear = self.clear_of_bar(view, scroll_bar_look(mcx.tokens).thickness, rtl);
let offset = ScrollPos { x: self.offset_x, y: self.offset.clamp(0.0, self.max_offset(view.height())) };
let mut layout = self.layout.take()?;
Arc::make_mut(&mut layout).set_view(view.size(), offset);
@@ -297,7 +297,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
return;
}
let view = self.below_header(pcx.content_rect);
let track = bar_track(view, scroll_bar_look(pcx.tokens, ScrollBarKind::Overlay).thickness, pcx.flow.is_rtl());
let track = bar_track(view, scroll_bar_look(pcx.tokens).thickness, pcx.flow.is_rtl());
let content = f64::from(self.content.y).max(f64::from(view.height()));
self.offset = self.offset.clamp(0.0, self.max_offset(view.height()));
let span = ScrollSpan::new(0.0..content, self.offset..self.offset + f64::from(view.height()));
@@ -753,7 +753,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
Env::restore(&ctx, installed);
}
if self.scrolls {
let look = scroll_bar_look(&env.tokens, ScrollBarKind::Overlay);
let look = scroll_bar_look(&env.tokens);
// The rows blend into the surface they sit on.
let background = surface_style(&env.tokens, SurfaceKind::under(own, env.surface)).fill;
let hidden = HiddenContent::new(self.content, rect.size(), Vec2::new(self.offset_x as f32, self.offset as f32), rtl);
@@ -762,9 +762,8 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
let track = bar_track(rect, look.thickness, rtl);
let content = f64::from(self.content.y);
let span = ScrollSpan::new(0.0..content, self.offset..self.offset + f64::from(rect.height()));
let result = cx.core.results.get(&(SCROLL, Some(crate::contract::cx::THUMB))).cloned().unwrap_or(crate::primitives::PartResult::IDLE);
let state = crate::contract::steps::part_state(&result, cx.core.looks_enabled(), None);
ui.painter().extend(ScrollBar::shapes(&look, track, Axis::Y, rtl, &span, &state, ui.ctx().pixels_per_point()));
let state = cx.core.scroll_bar_state(SCROLL);
ui.painter().extend(ScrollBar::shapes(&look, track, Axis::Y, rtl, &span, &state));
}
}
self.layout = Some(layout);
+1 -1
View File
@@ -62,7 +62,7 @@ pub use container::InBar;
pub use container::InMenu;
pub use container::{
BandFill, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion, LeastWidth,
Mount, Notch, POPUP_PAD, Pad, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth,
Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, ShellPane, Sizing, ThemeScope, WrapWidth,
};
pub use craft_ui_macros::{CommandSet, Component, Pattern, Props, register_contract};
#[doc(hidden)]
+3 -2
View File
@@ -406,7 +406,8 @@ impl<'a> Draw<'a> {
self.painter.extend(super::rule::Rule::edge(&look, rect, side, self.painter.pixels_per_point()));
}
/// Paints the scroll bar in `track` along `axis` for `span`, in `state` (`ScrollBar::shapes`).
/// Paints the scroll bar in `track` along `axis` for `span`, in the bar's `state` (`ScrollBar::shapes`;
/// `CxCore::scroll_bar_state` gives it).
pub fn scroll_bar(
&self,
look: &crate::style::ScrollBarLook,
@@ -416,7 +417,7 @@ impl<'a> Draw<'a> {
span: &craft_behavior::ScrollSpan,
state: &crate::style::StateSet,
) {
self.painter.extend(super::ScrollBar::shapes(look, track, axis, rtl, span, state, self.painter.pixels_per_point()));
self.painter.extend(super::ScrollBar::shapes(look, track, axis, rtl, span, state));
}
/// The width in points of the line `rule` paints for `kind`.
+13
View File
@@ -32,6 +32,19 @@ impl RectSide {
pub const fn end(rtl: bool) -> RectSide {
if rtl { RectSide::Left } else { RectSide::Right }
}
/// The side of a pane at `edge` that faces the window's centre, mirrored for a start or end pane under
/// right-to-left; none for the centre.
pub const fn toward_centre(edge: crate::contract::PaneEdge, rtl: bool) -> Option<RectSide> {
use crate::contract::PaneEdge;
match edge {
PaneEdge::Start => Some(RectSide::end(rtl)),
PaneEdge::End => Some(RectSide::start(rtl)),
PaneEdge::Top => Some(RectSide::Bottom),
PaneEdge::Bottom => Some(RectSide::Top),
PaneEdge::Center => None,
}
}
}
impl Rule {
+24 -24
View File
@@ -1,7 +1,7 @@
//! `ScrollBar`: the track and thumb of a scroll part, with state.
use super::rule::{RectSide, Rule};
use crate::style::{ScrollBarKind, ScrollBarLook, StateSet};
use super::rule::RectSide;
use crate::style::{ScrollBarLook, StateSet};
use craft_behavior::{Axis, ScrollSpan};
use egui::{Color32, CornerRadius, Direction, Rect, Shape, Vec2, pos2};
@@ -84,29 +84,29 @@ impl ScrollBar {
.collect()
}
/// The shapes of the bar in `track` along `axis` for `span`, in `state`: the track, a docked bar's rule along the
/// side facing the view (its top for a horizontal bar, its left for a vertical one), and the fully round thumb.
pub fn shapes(
look: &ScrollBarLook,
track: Rect,
axis: Axis,
rtl: bool,
span: &ScrollSpan,
state: &StateSet,
pixels_per_point: f32,
) -> Vec<Shape> {
let thumb = Self::thumb(look.min_thumb, track, axis, rtl, span).shrink(look.inset);
/// The shapes of the bar in `track` along `axis` for `span`, in `state` (the bar's: hovered while the pointer is
/// anywhere on it): the track and the fully round thumb. At rest the thumb is `look.rest` thick along the track's
/// outer edge (its bottom, or its end side in the reading direction) and the track is clear; hovered or pressed
/// the thumb fills the track's thickness.
pub fn shapes(look: &ScrollBarLook, track: Rect, axis: Axis, rtl: bool, span: &ScrollSpan, state: &StateSet) -> Vec<Shape> {
let full = Self::thumb(look.min_thumb, track, axis, rtl, span);
let lit = matches!(state.state, craft_theme::State::Hover | craft_theme::State::Pressed);
let thumb = if lit { full } else { Self::resting(full, look.rest, axis, rtl) };
let round = |rect: Rect| CornerRadius::from(rect.width().min(rect.height()) / 2.0);
let track_round = match look.kind {
ScrollBarKind::Overlay => round(thumb),
ScrollBarKind::Docked => CornerRadius::ZERO,
};
let mut shapes = vec![Shape::rect_filled(track, track_round, state.resolve(&look.track).egui())];
if let Some(edge) = &look.edge {
let side = if axis == Axis::X { RectSide::Top } else { RectSide::Left };
shapes.extend(Rule::edge(edge, track, side, pixels_per_point));
vec![
Shape::rect_filled(track, round(full), state.resolve(&look.track).egui()),
Shape::rect_filled(thumb, round(thumb), state.resolve(&look.thumb).egui()),
]
}
/// The resting thumb: `rest` thick along the outer edge of the full thumb `full`.
fn resting(full: Rect, rest: f32, axis: Axis, rtl: bool) -> Rect {
let side = if axis == Axis::X { RectSide::Bottom } else { RectSide::end(rtl) };
let rest = rest.min(if axis == Axis::X { full.height() } else { full.width() });
match side {
RectSide::Bottom => Rect::from_min_max(pos2(full.min.x, full.max.y - rest), full.max),
RectSide::Left => Rect::from_min_max(full.min, pos2(full.min.x + rest, full.max.y)),
_ => Rect::from_min_max(pos2(full.max.x - rest, full.min.y), full.max),
}
shapes.push(Shape::rect_filled(thumb, round(thumb), state.resolve(&look.thumb).egui()));
shapes
}
}
-4
View File
@@ -160,8 +160,6 @@ pub struct Scoped {
pub(crate) unbounded: (bool, bool),
/// The view of the innermost scroll area, for the children that run only in view (`contract::Lazy`).
pub(crate) lazy: Option<crate::runtime::lazy::View>,
/// The window edge of the innermost edge pane that encloses the scope (`Mount::Pane`).
pub(crate) pane_edge: Option<PaneEdge>,
/// The id of the collection item the scope shows: its root is not a Tab stop (17.3).
pub(crate) item: Option<Id>,
/// The roving group of the collection row the scope shows: the stops of its components and parts join it, so
@@ -349,7 +347,6 @@ impl Scoped {
self.wheel = WheelScope::Plain;
self.unbounded = (false, false);
self.lazy = None;
self.pane_edge = None;
self.glyphs = GlyphRole::Control;
self.item = None;
self.row = None;
@@ -501,7 +498,6 @@ impl Env {
scroll_owner: None,
unbounded: (false, false),
lazy: None,
pane_edge: None,
item: None,
row: None,
item_facts: None,
+4 -4
View File
@@ -3,7 +3,7 @@
use super::key::{EnvKey, Ink};
use super::look::{DataColor, FocusLook, StyleColor, SurfaceKind, SurfaceLook, TrackLook};
use super::paint::{
HandleLook, MarkerLook, ResetMarkLook, RuleKind, RuleLook, ScrollBarKind, ScrollBarLook, handle_look, marker_look, reset_mark_look, rule_look,
HandleLook, MarkerLook, ResetMarkLook, RuleKind, RuleLook, ScrollBarLook, handle_look, marker_look, reset_mark_look, rule_look,
scroll_bar_look,
};
use super::surface::{SurfaceStyle, surface_style};
@@ -429,9 +429,9 @@ impl<'a> StyleCx<'a> {
marker_look(self.tokens)
}
/// The look of a scroll bar of `kind`.
pub fn scroll_bar(&self, kind: ScrollBarKind) -> ScrollBarLook {
scroll_bar_look(self.tokens, kind)
/// The look of a scroll bar.
pub fn scroll_bar(&self) -> ScrollBarLook {
scroll_bar_look(self.tokens)
}
/// The state layer: the theme's hover and press fills, clear at rest and while disabled. A part declared
+1 -1
View File
@@ -26,7 +26,7 @@ pub use key::{EnvKey, Ink, StyleKey};
pub(crate) use look::StyleView;
pub use look::{ComponentStyle, Corners, DataColor, FocusLook, IconLook, StyleColor, SurfaceKind, SurfaceLook, TextLook, TrackLook};
pub use paint::{
HandleLook, MarkerLook, ResetMarkLook, ResizeLineLook, RuleKind, RuleLook, RuleWidth, ScrollBarKind, ScrollBarLook, resize_line_look,
HandleLook, MarkerLook, ResetMarkLook, ResizeLineLook, RuleKind, RuleLook, RuleWidth, ScrollBarLook, resize_line_look,
};
pub(crate) use paint::{min_thumb, scroll_bar_look};
pub use replacements::{DuplicateStyle, StyleReplacements};
+17 -28
View File
@@ -170,35 +170,22 @@ pub(crate) fn marker_look(tokens: &UiTokens) -> MarkerLook {
}
}
/// Where a scroll bar sits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ScrollBarKind {
/// Over the content at its end edge: a clear track that tints under the pointer, a thumb as thick as the track.
Overlay,
/// Beside the view along its bottom and right, as a document window's bars: a solid chrome track with an edge rule
/// on the side facing the view, and a thumb inset from the track's edges.
Docked,
}
/// A scroll bar's track and thumb.
/// A scroll bar's track and thumb: one floating indicator for every scroll area, over the content at its edge. At rest
/// the thumb is a thin dim line along the track's outer edge and the track is clear; under the pointer or while pressed
/// the thumb takes the track's whole thickness over a tinted track.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ScrollBarLook {
/// Where the bar sits.
pub kind: ScrollBarKind,
/// The track fill per state.
pub track: Stateful<StyleColor>,
/// The thumb fill per state.
pub thumb: Stateful<StyleColor>,
/// The bar's thickness.
/// The bar's thickness: its track, and its thumb under the pointer or while pressed.
pub thickness: f32,
/// The thumb's thickness at rest.
pub rest: f32,
/// The shortest the thumb gets along the bar.
pub min_thumb: f32,
/// Between the track's edges and the painted thumb.
pub inset: f32,
/// The rule along the side of the track that faces the view.
pub edge: Option<RuleLook>,
/// The length of the fade at an edge past which content is hidden.
pub fade: f32,
}
@@ -208,7 +195,7 @@ pub(crate) fn min_thumb(tokens: &UiTokens) -> f32 {
tokens.size.handle.md * 2.0
}
pub(crate) fn scroll_bar_look(tokens: &UiTokens, kind: ScrollBarKind) -> ScrollBarLook {
pub(crate) fn scroll_bar_look(tokens: &UiTokens) -> ScrollBarLook {
let c = &tokens.color;
let clear = style_color(Rgba::TRANSPARENT);
let thumb = Stateful::new(style_color(c.text.faint)).off(craft_theme::States::new(
@@ -217,14 +204,16 @@ pub(crate) fn scroll_bar_look(tokens: &UiTokens, kind: ScrollBarKind) -> ScrollB
style_color(c.text.normal),
style_color(c.state.disabled_fill),
));
let (track, inset, edge) = match kind {
ScrollBarKind::Overlay => {
let hover = style_color(c.state.hover);
(Stateful::new(clear).off(craft_theme::States::new(clear, hover, hover, clear)), 0.0, None)
}
ScrollBarKind::Docked => (Stateful::new(style_color(c.surface.chrome)), tokens.space.gap.tight, Some(rule_look(tokens, RuleKind::Edge))),
};
ScrollBarLook { kind, track, thumb, thickness: tokens.size.handle.sm, min_thumb: min_thumb(tokens), inset, edge, fade: tokens.size.scroll_fade }
let hover = style_color(c.state.hover);
let track = Stateful::new(clear).off(craft_theme::States::new(clear, hover, hover, clear));
ScrollBarLook {
track,
thumb,
thickness: tokens.size.handle.sm,
rest: tokens.stroke.thick,
min_thumb: min_thumb(tokens),
fade: tokens.size.scroll_fade,
}
}
/// The reset dot's colours and diameter.
+11 -6
View File
@@ -2,7 +2,9 @@
use crate::contract::PaneEdge;
use crate::layout::flow_room;
use crate::primitives::{RectSide, Rule};
use crate::runtime::env::Env;
use crate::style::{RuleKind, rule_look};
use egui::{Rect, Ui};
/// Allocates the stage of a story of a canvas control or a root that fills both axes, and returns its rect: the width
@@ -37,11 +39,14 @@ pub fn stage_width(ui: &Ui) -> f32 {
}
/// Runs `story` as the content of an edge pane at `edge`, as a rail or panel docked at that edge of an app window
/// shows: a container that draws a divider along its pane's inner edge (`ContainerProps::edge_rule`) draws it.
/// shows: with the divider the pane draws along its inner edge (`ContainerProps::edge_rule`), here along the edge of
/// what the story drew.
pub fn in_edge_pane<R>(ui: &mut Ui, edge: PaneEdge, story: impl FnOnce(&mut Ui) -> R) -> R {
let ctx = ui.ctx().clone();
let installed = Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.pane_edge = Some(edge)));
let out = story(ui);
Env::restore(&ctx, installed);
out
let shown = ui.scope(story);
let env = Env::of(ui);
if let Some(side) = RectSide::toward_centre(edge, env.direction.is_rtl()) {
let rule = rule_look(&env.tokens, RuleKind::Divider);
ui.painter().extend(Rule::edge(&rule, shown.response.rect, side, ui.ctx().pixels_per_point()));
}
shown.inner
}
@@ -184,3 +184,43 @@ fn ant_edges_are_whole_device_pixels_at_a_fractional_scale() {
assert!(lower.contains(&(s - width)), "the dash at {s} continues {width} pixels earlier one row down: {lower:?}");
}
}
/// Every scroll bar rests as a thin line along its track's outer edge and shows its thumb across the whole track under
/// the pointer, at the same place along the bar.
#[trial]
fn a_resting_scroll_bar_is_a_thin_line_at_its_outer_edge_that_widens_under_the_pointer() {
use craft_behavior::{Axis, ScrollSpan};
use craft_theme::{Contrast, ControlSize, Mode, Variant};
use craft_ui::primitives::ScrollBar;
use craft_ui::style::{Flags, State, StateMix, StateSet};
use egui::{Rect, Shape};
let tokens = craft_ui::testing::style::tokens(Mode::Dark, Contrast::Standard);
let look = craft_ui::testing::style::with_cx(&egui::Context::default(), &tokens, Variant::SECONDARY, ControlSize::Md, |cx| cx.scroll_bar());
let span = ScrollSpan::new(0.0..400.0, 100.0..300.0);
for (axis, rtl) in [(Axis::Y, false), (Axis::Y, true), (Axis::X, false)] {
let track = match axis {
Axis::X => Rect::from_min_max(pos2(0.0, 100.0), pos2(200.0, 100.0 + look.thickness)),
_ => Rect::from_min_max(pos2(100.0, 0.0), pos2(100.0 + look.thickness, 200.0)),
};
let thumb = |state: State| {
let shapes = ScrollBar::shapes(&look, track, axis, rtl, &span, &StateSet::new(state, Flags::empty(), StateMix::REST));
match shapes.last() {
Some(Shape::Rect(shape)) => shape.rect,
other => panic!("the thumb is a rect: {other:?}"),
}
};
let (rest, hover) = (thumb(State::Rest), thumb(State::Hover));
let across = |rect: Rect| if axis == Axis::X { rect.height() } else { rect.width() };
assert!(across(rest) < across(hover), "{axis:?}: the resting thumb is thinner: {rest:?} and {hover:?}");
assert!((across(hover) - across(track)).abs() < EPS, "{axis:?}: under the pointer the thumb fills the track");
let outer = match (axis, rtl) {
(Axis::X, _) => (rest.bottom() - track.bottom()).abs(),
(_, true) => (rest.left() - track.left()).abs(),
_ => (rest.right() - track.right()).abs(),
};
assert!(outer < EPS, "{axis:?} rtl {rtl}: the resting line lies along the outer edge: {rest:?} in {track:?}");
let along = |rect: Rect| if axis == Axis::X { rect.x_range() } else { rect.y_range() };
assert_eq!(along(rest), along(hover), "{axis:?}: the thumb keeps its place along the bar");
}
}
+1 -1
View File
@@ -82,7 +82,7 @@ impl<'a> EditorMock<'a> {
.screen_mode(screen_mode)
.title_bar_if(true, |ui, _, state: &mut MockState| title_bar(ui, state))
.options_bar(true, |ui, _, state: &mut MockState| options_bar(ui, state))
.tools(PaneEdge::Start, true, |ui, _, state: &mut MockState| tool_rail(ui, state))
.tools(PaneEdge::Start, 1, true, |ui, _, state: &mut MockState| tool_rail(ui, state))
.status(true, |ui, _, state: &mut MockState| status_bar(ui, state))
.body_label(label)
.body(|ui, cx, state: &mut MockState| body(ui, cx, state));
+3 -4
View File
@@ -61,8 +61,8 @@ impl<P: Value> Outcome for PanelRailOutput<P> {
type FooterFn<'a> = Box<dyn FnMut(&mut Ui) + 'a>;
/// The rail of icons that open panels, as a side panel at one edge of the window, with a rule along the edge that faces
/// the canvas (the inner edge of its pane). A panel is a toggle command: its
/// The rail of icons that open panels, as a side panel at one edge of the window; the pane it sits in draws the rule
/// along the edge that faces the canvas. A panel is a toggle command: its
/// label, icon, chord and enabled state come from the command, the icon shows the on look while the command is
/// checked (the panel is open), and the command's `marked` state and `hint` mark a closed panel that has content
/// to show. A click runs the command and reports the request that matches the panel's state. The icons are one
@@ -92,8 +92,7 @@ impl<'a, P: Value + 'static> PanelRail<'a, P> {
.child_glyphs(GlyphRole::PanelRail)
.roving(Roving::new(NavShape::Flat))
.scroll(Scroll::vertical())
.footer(FooterRegion::new())
.edge_rule(true);
.footer(FooterRegion::new());
PanelRail { common: Common::new(), props, panels, footer: None }.label(label)
}
@@ -110,3 +110,33 @@ fn the_rails_show_their_buttons_icons_in_their_glyph_roles() {
assert_eq!(panel.side, alone.side, "a panel rail icon keeps the control glyph");
assert!(panel.color.off.rest != alone.color.off.rest, "a panel rail icon rests quieter than a lone one");
}
/// A tool rail is as wide as its columns and centres its buttons across them, so no button reaches past the rail's
/// edge; its two header toggles share one line inside it.
#[trial]
fn a_tool_rail_centres_its_buttons_in_its_columns_and_keeps_its_toggles_on_one_line() {
use crate::rails::{LastUsed, ToolRail, ToolSlot};
use std::num::NonZeroU8;
for columns in [1_u8, 2] {
let mut fixture = Fixture::new(move |ui| {
let slots = vec![ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[1])), ToolSlot::new(2, tools(&[3]))];
ToolRail::new("Tools", &slots, &0, &LastUsed::default())
.columns(NonZeroU8::new(columns).unwrap_or(NonZeroU8::MIN))
.column_toggle("Toolbar")
.side_toggle("Move Toolbar")
.show_rail(ui, |_, _| {});
});
fixture.settle();
let rail = rect(&fixture, "Tools");
for label in ["Move", "Brush", "Eraser", "Toolbar", "Move Toolbar"] {
let shown = rect(&fixture, label);
assert!(rail.contains_rect(shown), "{columns} columns: {label} lies inside the rail: {shown:?} in {rail:?}");
}
let (first, last) = (rect(&fixture, "Move"), rect(&fixture, if columns == 1 { "Move" } else { "Brush" }));
let grid = first.union(last);
assert!((grid.center().x - rail.center().x).abs() < 0.5, "{columns} columns: the buttons are centred: {grid:?} in {rail:?}");
let (toggle, side) = (rect(&fixture, "Toolbar"), rect(&fixture, "Move Toolbar"));
assert!((toggle.center().y - side.center().y).abs() < 0.5, "the toggles share a line: {toggle:?} and {side:?}");
assert!(above(toggle, first), "the toggles are above the buttons");
}
}
+74 -58
View File
@@ -4,10 +4,11 @@ use super::flyout::{FlyoutButton, SlotEdit};
use super::words::RailWords;
use crate::buttons::IconButton;
use crate::contract::{
Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, HeaderRegion, NoValue, Outcome, Pad, PaneEdge, Props as _, Role,
Scroll, Show as _, ShowContainer as _, Sizing, WordSetCx as _, clicked,
Access, Common, Component, Container, ContainerProps, Cx, FooterRegion, Gap, HeaderRegion, LeastWidth, NoValue, Outcome, Pad, PadEdges, PaneEdge,
Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, WordSetCx as _, clicked,
};
use crate::contract::{BodyCx, BodyLayout};
use crate::layout::RowAlign;
use crate::layout_components::{Row, Stack};
use crate::runtime::access::Name;
use crate::runtime::commands::Commands as _;
@@ -104,10 +105,12 @@ type FooterFn<'a> = Box<dyn FnMut(&mut Ui, RailFooter) + 'a>;
/// The rail of tool slots, as a side panel at one edge of the window: one `FlyoutButton` per visible slot showing the
/// slot's shown tool, the slot with the current tool toggled on. A click selects the shown tool, a row of the flyout
/// selects that tool. With two columns the slots fill rows in reading order. A slot that ends a group leaves
/// `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The column toggle is the header and the
/// Edit Toolbar button follows the last slot; the host's footer stays in view under the slots, which scroll when the
/// window is short. The buttons are one roving group: arrow keys move between them by the grid. While the toolbar is
/// selects that tool. With two columns the slots fill rows in reading order. Each column is `size.rail.width` wide,
/// the width of the shell's tools slot per column, and the buttons sit centred across the columns with the control
/// padding above and below. A slot that ends a group leaves `space.gap.inline` after its row; slots within a group sit
/// `space.gap.tight` apart. The column toggle and the side toggle share the header's one line at the small control
/// size; the Edit Toolbar button follows the last slot; the host's footer stays in view under the slots, which scroll
/// when the window is short, and its buttons show the rail's glyphs. The buttons are one roving group: arrow keys move between them by the grid. While the toolbar is
/// edited the buttons are dragged and take drops, and report the drop in the output.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(container, probe(ToolRail<'static, u8>))]
@@ -154,9 +157,9 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> {
let props = ContainerProps::new()
.surface(SurfaceKind::Chrome)
.pad(Pad::Control)
.pad_edges(PadEdges::Block)
.sizing(Sizing::Content)
.layout(BodyLayout::stack())
.body_gap(Gap::Inline)
.child_size(ControlSize::Md)
.child_glyphs(GlyphRole::ToolRail)
.scroll(Scroll::vertical())
@@ -201,7 +204,8 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> {
/// when the window is short.
pub fn show_rail(mut self, ui: &mut Ui, footer: impl FnMut(&mut Ui, RailFooter) + 'a) -> ToolRailOutput<T> {
let columns = self.column_count();
self.props = self.props.roving(Roving::new(NavShape::wrapped_grid(columns)));
let wide = u8::try_from(columns).ok().and_then(NonZeroU8::new).unwrap_or(NonZeroU8::MIN);
self.props = self.props.roving(Roving::new(NavShape::wrapped_grid(columns))).least_width(LeastWidth::Rail(wide));
if self.column_toggle.is_some() || self.side_toggle.is_some() {
self.props = self.props.header(HeaderRegion::new());
}
@@ -217,50 +221,55 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> {
let cells = visible.len() + usize::from(edit_label.is_some());
let enabled = |tool: &RailTool<T>| cx.resolve_command(tool.command.clone()).is_some_and(|resolved| resolved.enabled);
let at: Vec<usize> = visible.iter().map(|(index, _)| *index).collect();
for group in row_groups(slots, &at, cells, columns) {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
for &first in &group {
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
for k in first..(first + columns).min(cells) {
match visible.get(k) {
Some((index, tools)) => {
let slot = &slots[*index];
let owned: Vec<RailTool<T>> = tools.iter().map(|tool| (*tool).clone()).collect();
let Some(shown) = shown_tool(current, slot.id, tools, last_used, enabled) else { continue };
let selected = tools.iter().any(|tool| tool.id == *current);
let mut button = FlyoutButton::new(&owned, &shown.id)
.id_salt(("slot", slot.id))
.selected(selected)
.enabled(tools.iter().any(|tool| enabled(tool)))
.opens(opens);
if editing {
button = button.edit(SlotEdit::new(slot.id, *index, slot.tools.len(), columns == 1));
}
let out = button.show(ui);
if out.select.is_some() {
collected.select = out.select;
}
if out.double_clicked {
collected.double_clicked = Some(shown.id.clone());
}
if out.opened {
collected.flyout = Some(slot.id);
}
if out.dropped.is_some() {
collected.dropped = out.dropped;
// The grid of buttons sits at the centre of the rail's columns.
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
Stack::new().gap(Gap::Inline).show(ui, |ui, _| {
for group in row_groups(slots, &at, cells, columns) {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
for &first in &group {
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
for k in first..(first + columns).min(cells) {
match visible.get(k) {
Some((index, tools)) => {
let slot = &slots[*index];
let owned: Vec<RailTool<T>> = tools.iter().map(|tool| (*tool).clone()).collect();
let Some(shown) = shown_tool(current, slot.id, tools, last_used, enabled) else { continue };
let selected = tools.iter().any(|tool| tool.id == *current);
let mut button = FlyoutButton::new(&owned, &shown.id)
.id_salt(("slot", slot.id))
.selected(selected)
.enabled(tools.iter().any(|tool| enabled(tool)))
.opens(opens);
if editing {
button = button.edit(SlotEdit::new(slot.id, *index, slot.tools.len(), columns == 1));
}
let out = button.show(ui);
if out.select.is_some() {
collected.select = out.select;
}
if out.double_clicked {
collected.double_clicked = Some(shown.id.clone());
}
if out.opened {
collected.flyout = Some(slot.id);
}
if out.dropped.is_some() {
collected.dropped = out.dropped;
}
}
None => {
let label = edit_label.clone().unwrap_or(Label::Empty);
let more = IconButton::new(IconId::new("more")).id_salt("edit-toolbar").label(label).show(ui);
collected.edit_toolbar = Some(more.response);
}
}
}
None => {
let label = edit_label.clone().unwrap_or(Label::Empty);
let more = IconButton::new(IconId::new("more")).id_salt("edit-toolbar").label(label).show(ui);
collected.edit_toolbar = Some(more.response);
}
}
});
}
});
}
});
}
});
});
ToolRailOutput {
select: collected.select,
@@ -313,21 +322,28 @@ impl<T: Value + 'static> Component for ToolRail<'_, T> {
}
impl<T: Value + 'static> Container for ToolRail<'_, T> {
/// The column toggle and the side toggle.
/// The column toggle and the side toggle, side by side on one line at the small control size with the control
/// glyph: two of them touch to fit one rail column.
fn header(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) {
let (columns, rtl) = (self.column_count(), Env::of(ui).direction.is_rtl());
let at_left = !self.at_end() != rtl;
if let Some(label) = self.column_toggle.clone() {
let icon = crate::collapse::chevrons(column_toggle_points_right(columns, at_left));
let toggle = IconButton::new(icon).id_salt("column-toggle").label(label).show(ui);
self.toggled |= clicked(&toggle);
}
if let Some(label) = self.side_toggle.clone() {
// The icon shows the edge the rail moves to.
let icon = IconId::new(if at_left { "panel_right" } else { "panel_left" });
let toggle = IconButton::new(icon).id_salt("side-toggle").label(label).show(ui);
self.side_toggled |= clicked(&toggle);
}
let (column_toggle, side_toggle) = (self.column_toggle.clone(), self.side_toggle.clone());
let (mut toggled, mut side_toggled) = (false, false);
Row::new().fill_width().align(RowAlign::Center).gap(Gap::None).show(ui, |ui, _| {
if let Some(label) = column_toggle.clone() {
let icon = crate::collapse::chevrons(column_toggle_points_right(columns, at_left));
let toggle = IconButton::new(icon).id_salt("column-toggle").label(label).size(ControlSize::Sm).glyphs(GlyphRole::Control).show(ui);
toggled |= clicked(&toggle);
}
if let Some(label) = side_toggle.clone() {
// The icon shows the edge the rail moves to.
let icon = IconId::new(if at_left { "panel_right" } else { "panel_left" });
let toggle = IconButton::new(icon).id_salt("side-toggle").label(label).size(ControlSize::Sm).glyphs(GlyphRole::Control).show(ui);
side_toggled |= clicked(&toggle);
}
});
self.toggled |= toggled;
self.side_toggled |= side_toggled;
}
/// The host's footer.
+26 -16
View File
@@ -98,11 +98,12 @@ pub struct ShellRegion {
}
impl ShellRegion {
/// The whole content of the window: its edges resize the window where the app draws the frame. It paints no
/// surface of its own: the parts the shell places paint theirs, and a gap between them (a dock's gutter) shows the
/// window's clear colour.
/// The whole content of the window: its edges resize the window where the app draws the frame. It paints the
/// background surface under everything the shell places, so a gap between parts (a dock's gutter, the room beside
/// the document tabs) shows the background, never the platform's clear colour.
pub fn window() -> Self {
let props = ContainerProps::new().mount(Mount::window(Resize::GRIPS)).command_scope(ScreenModeCommands::SCOPE);
let props =
ContainerProps::new().mount(Mount::window(Resize::GRIPS)).surface(SurfaceKind::Background).command_scope(ScreenModeCommands::SCOPE);
ShellRegion { common: Common::new(), props, shell: None, senses_surface: false }
}
@@ -125,6 +126,15 @@ impl ShellRegion {
let props = ContainerProps::new().mount(Mount::Pane(pane)).focus(FocusPolicy::PANE);
ShellRegion { common: Common::new(), props, shell: None, senses_surface: false }
}
/// A bar or rail pane at an edge of the window: it paints the chrome surface over the whole pane and a divider
/// along its inner edge. A bar or rail inside that is smaller than the pane leaves no band of the backdrop, and the
/// pane meets the body at the rule.
pub fn chrome(pane: ShellPane) -> Self {
let mut region = Self::pane(pane);
region.props = region.props.surface(SurfaceKind::Chrome).edge_rule(true);
region
}
}
impl Component for ShellRegion {
@@ -357,10 +367,11 @@ impl<'a, S> AppShell<'a, S> {
self
}
/// The tool rail, a slot keyed `"tools"` at `edge` (the reading start or end) that reveals in body-only mode. It
/// is the Tools region on either edge.
pub fn tools(mut self, edge: PaneEdge, visible: bool, add: impl FnMut(&mut Ui, &mut BodyCx<'_>, &mut S) + 'a) -> Self {
let slot = Slot::new(keys::TOOLS).visible(visible).reveal();
/// The tool rail, a slot keyed `"tools"` at `edge` (the reading start or end) that reveals in body-only mode, as
/// wide as the rail's `columns` (1 or 2, the count the host gives its `ToolRail`). It is the Tools region on either
/// edge.
pub fn tools(mut self, edge: PaneEdge, columns: usize, visible: bool, add: impl FnMut(&mut Ui, &mut BodyCx<'_>, &mut S) + 'a) -> Self {
let slot = Slot::new(keys::TOOLS).columns(columns).visible(visible).reveal();
self.slots.push(Placed { slot, edge, title: false, named: Some(|words| words.tools.clone()), add: Box::new(add) });
self
}
@@ -522,14 +533,13 @@ impl<'a, S> AppShell<'a, S> {
let extent = placed.extent(&tokens);
let Placed { slot, edge, named, add, title, .. } = placed;
let pane = ShellPane::new(slot.key()).edge(*edge).extent(extent).at(rect_of(slot.key()));
let mut region = ShellRegion::pane(pane).id_salt(("slot", slot.key()));
// A bar is as high as its content and the slot as high as its token, so the slot paints the bar's
// surface under it, and the bar sits at the slot's centre line: no band of the backdrop shows
// between the bar and the body.
// Every slot but the title is a chrome pane: it paints the surface under its bar or rail and
// the rule toward the body. The title bar paints its own.
let region = if *title { ShellRegion::pane(pane) } else { ShellRegion::chrome(pane) };
let mut region = region.id_salt(("slot", slot.key()));
// A bar is as high as its content and the slot as high as its token, so the bar sits at the
// slot's centre line.
let centred = !*title && matches!(edge, PaneEdge::Top | PaneEdge::Bottom);
if centred {
region = region.surface(SurfaceKind::Chrome);
}
if let Some(label) = slot.name().cloned().or_else(|| named.map(|name| name(&words))) {
region = region.label(label);
}
@@ -544,7 +554,7 @@ impl<'a, S> AppShell<'a, S> {
};
show_slots(ui, false, app);
// Only a body-only shell paints behind its body (the scrim). Otherwise the body paints what it shows, and the gaps
// between its parts (the dock's gutters) are the window's own clear colour.
// between its parts (the dock's gutters) show the window's background.
let pane = ShellPane::new("body");
let pane = if content_room.is_some() { pane.at_content_height(regions.body) } else { pane.at(regions.body) };
let mut center = ShellRegion::pane(pane).label(body_label.clone());
@@ -45,7 +45,7 @@ fn app_shell_canvas(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
.options_bar(true, |ui, _, _| {
Text::new("Options").show(ui);
})
.tools(PaneEdge::Start, true, |ui, _, _| {
.tools(PaneEdge::Start, 1, true, |ui, _, _| {
Text::new("Tools").show(ui);
})
.status(true, |ui, _, _| {
+4 -2
View File
@@ -26,7 +26,7 @@ use super::words::ShellWords;
use crate::contract::{BodyCx, NoValue, Outcome, PaneEdge, Props as _, ShellPane, ShowContainer as _};
use crate::primitives::{CheckerArea, paint_surround};
use crate::runtime::env::{BodyMode, Env, Label, ShellEntry};
use crate::style::SurroundLook;
use crate::style::{SurfaceKind, SurroundLook};
use egui::{CornerRadius, Rect, Response, Ui};
/// The slot keys of the preset.
@@ -118,12 +118,14 @@ impl<'a> CanvasPanel<'a> {
let mut rail_rect = None;
if let (Some((label, mut add)), true) = (rail, dock) {
let out =
ShellRegion::pane(ShellPane::new("panel_rail").edge(PaneEdge::End)).id_salt("panel_rail").label(label).show(ui, |ui, cx| add(ui, cx));
ShellRegion::chrome(ShellPane::new("panel_rail").edge(PaneEdge::End)).id_salt("panel_rail").label(label).show(ui, |ui, cx| add(ui, cx));
rail_rect = Some(out.response.rect);
}
let mut tabs_rect = None;
if let (Some(mut add), true) = (tabs.map(|RegionBody(add)| add), tabs_shown) {
// The document tabs sit on the window's background, as tab strips do.
let out = ShellRegion::pane(ShellPane::new("document_tabs").edge(PaneEdge::Top))
.surface(SurfaceKind::Background)
.id_salt("document_tabs")
.label(words.document_tabs.clone())
.show(ui, |ui, cx| add(ui, cx));
+2 -1
View File
@@ -45,7 +45,8 @@ impl SlotSize {
}
/// One bar or rail of the skeleton: its key, whether it shows, whether it shows in a reveal, its size and its AccessKit
/// name. The slot's body draws its own surface and edge.
/// name. The shell paints the chrome surface over the whole slot and a divider along its edge toward the body; the
/// title slot's bar paints its own.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Slot {
+25 -1
View File
@@ -15,7 +15,7 @@ fn the_tool_rail_at_the_end_edge_is_the_tools_region() {
frames.frame(vec![], |ui| {
let window = ui.max_rect();
let out = AppShell::new(WindowKey::main())
.tools(PaneEdge::End, true, |ui, _, _: &mut ()| {
.tools(PaneEdge::End, 1, true, |ui, _, _: &mut ()| {
Text::new("Rail").show(ui);
})
.body(|_, _, _| {})
@@ -29,3 +29,27 @@ fn the_tool_rail_at_the_end_edge_is_the_tools_region() {
let names: Vec<&str> = tree.with_role(Role::GROUP).into_iter().filter_map(|key| tree.name_of(key)).collect();
assert!(names.contains(&"Tools"), "the end-edge rail is the Tools region: {names:?}");
}
/// A two-column tool rail gets a slot two rail columns wide, so its second column is not cut off.
#[trial]
fn a_two_column_tool_rail_is_twice_as_wide_as_one_column() {
let width = |columns: usize| {
let mut frames = Frames::new();
let mut width = 0.0;
for _ in 0..2 {
frames.frame(vec![], |ui| {
let out = AppShell::new(WindowKey::main())
.tools(PaneEdge::Start, columns, true, |ui, _, _: &mut ()| {
Text::new("Rail").show(ui);
})
.body(|_, _, _| {})
.show(ui, &mut ());
width = out.regions.slots.first().map_or(0.0, |(_, rect)| rect.width());
});
}
width
};
let (one, two) = (width(1), width(2));
assert!(one > 0.0, "the rail shows");
assert!((two - 2.0 * one).abs() < 0.5, "two columns take two rail widths: {one} and {two}");
}
+1 -1
View File
@@ -24,7 +24,7 @@ fn shown(windows: &mut Frames, mode: &mut ScreenMode, events: Vec<Event>) -> (us
windows.frame(events, |ui| {
let out = AppShell::new(WindowKey::main())
.screen_mode(Bind::bound(&mut *mode))
.tools(PaneEdge::Start, true, |ui, _, _: &mut ()| {
.tools(PaneEdge::Start, 1, true, |ui, _, _: &mut ()| {
Text::new("Tools").show(ui);
})
.options_bar(false, |ui, _, _: &mut ()| {