diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index fad53f083..8d8a85a0e 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -40,7 +40,7 @@ use craft_ui::contract::{ use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, PaintShape, StrokeWidth}; use craft_ui::runtime::commands::ClipItem; use craft_ui::runtime::env::Label; -use craft_ui::runtime::focus::KeyUse; +use craft_ui::runtime::focus::{FocusPolicy, KeyUse}; use craft_ui::runtime::pending::Pending; use craft_ui::style::{ComponentStyle, StyleColor, StyleCx}; use egui::{Pos2, Rect, Response, Vec2}; @@ -461,6 +461,8 @@ impl Component for TextEditor<'_> { const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Editor; /// Escape always ends the session, so the editor keeps it from its row and from the shortcuts while focused. const KEYS: KeyUse = KeyUse::CODE.with_claims(&[ESCAPE]); + /// When the session ends, focus goes back to the stop it came from (the canvas), not to the stop before the editor. + const FOCUS_SCOPE: FocusPolicy = FocusPolicy::TAB_LAYER; type Style = TextEditorStyle; type Output = TextEditorOutput; diff --git a/crates/text/tests/it/editor.rs b/crates/text/tests/it/editor.rs index f23eb21f1..7abc5e213 100644 --- a/crates/text/tests/it/editor.rs +++ b/crates/text/tests/it/editor.rs @@ -346,3 +346,51 @@ fn formatting_keys_follow_the_flow_and_fall_back_to_caret_moves() { assert!(!plain.host.borrow().styles.is_empty(), "the host was asked for the leading step"); assert_eq!(plain.selection.borrow().caret, before.saturating_sub(LINE), "the step the host did not take moved the caret a line up"); } + +/// #15555: a session the app ends (Cmd+Enter, then the editor is not shown) on a canvas with rulers hands the focus back +/// to the canvas it came from, not to the stop before the editor (the rulers' corner, whose arrows move the zero point), +/// and the view stays where it was. Without rulers the canvas is that stop anyway. +#[trial] +fn an_ended_session_returns_the_focus_to_the_canvas_and_the_view_stays() { + const EDITOR: craft_behavior::DocKey = craft_behavior::DocKey::new("trial.type-editor"); + use craft_ui::canvas::Rulers; + use craft_ui::contract::Props as _; + use craft_ui::runtime::focus::{FocusTarget, request}; + use craft_ui::testing::access::{focused_key, name}; + + for rulers in [true, false] { + let editing = Rc::new(Cell::new(false)); + let view = Rc::new(Cell::new(None::)); + let (shown_editing, shown_view) = (Rc::clone(&editing), Rc::clone(&view)); + let mut host = Host { text: "abc".to_owned(), ..Host::default() }; + let mut selection = TextSelection::caret_at(3); + let mut zero = Point::ZERO; + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let given = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(100.0, 100.0), 1.0)); + let strips = rulers.then(|| Rulers::new("Rulers", Bind::bound(&mut zero))); + let canvas = Canvas::new("Document").view(given).with_rulers(strips).show(ui, |ui, body| { + if shown_editing.get() { + let bounds = Rect::from_min_size(body.rect.min + vec2(40.0, 40.0), vec2(200.0, 20.0)); + drop(TextEditor::new("Text", &mut host, Bind::bound(&mut selection)).doc_key(EDITOR).show_at(ui, bounds)); + } + }); + shown_view.set(Some(canvas.output.view.unwrap_or(given))); + }); + fixture.room(vec2(600.0, 400.0)).settle(); + let focused = |fixture: &Fixture| name(fixture.tree(), focused_key(fixture.tree())).map(str::to_owned); + // A press on the canvas focuses it, and the session that press starts asks for the editor's focus. + fixture.click_at(pos2(400.0, 300.0)).settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the press focused the canvas"); + editing.set(true); + fixture.settle(); + request(fixture.ctx(), FocusTarget::Doc(EDITOR)); + fixture.settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Text"), "rulers {rulers}: the editor took the focus"); + let before = view.get(); + editing.set(false); + fixture.settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the focus went back to the canvas"); + assert_eq!(view.get(), before, "rulers {rulers}: the view stays"); + } +} diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index adb4267ef..59df6659e 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1806,10 +1806,10 @@ impl BodyHooks<'_> { fn measure_room(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Result { let props = &self.props; // A mount outside the flow takes no room in a parent's sizing pass, so its regions run only when it is - // measured itself. A pane as tall as its content takes its height in the flow. + // measured itself. A pane as large as its content takes its extent in the flow. let flows = match &props.mount { Mount::Inline => true, - Mount::Pane(pane) => pane.content_height, + Mount::Pane(pane) => pane.content_extent, _ => false, }; if !flows && at.ui.is_sizing_pass() { diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 1cb5f02c7..6111db511 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -5,7 +5,7 @@ use super::placement::overlay_of; use super::regions::{RegionSizes, end_full_height, footer_in_body, footer_in_end}; use super::scroll::scroll_of; use crate::contract::run::ShowAt; -use crate::contract::{ContainerProps, Mount, PadEdges, ShellPane, Sizing}; +use crate::contract::{ContainerProps, Mount, PadEdges, PaneEdge, ShellPane, Sizing}; use crate::runtime::egui::areas; use crate::runtime::env::Env; use crate::runtime::layout_memory; @@ -103,7 +103,8 @@ impl<'b> BodyHooks<'b> { /// from its content until the user sizes it; an inline container follows its props. pub(super) fn sizing(&self, props: &ContainerProps) -> Sizing { match &props.mount { - Mount::Pane(pane) if pane.content_height => Sizing::FillWidth, + Mount::Pane(pane) if pane.content_extent && matches!(pane.edge, PaneEdge::Start | PaneEdge::End) => Sizing::FillHeight, + Mount::Pane(pane) if pane.content_extent => Sizing::FillWidth, Mount::Pane(_) | Mount::Window { .. } => Sizing::Fill, Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow if self.fixed => Sizing::Fill, Mount::Layer(_) | Mount::Viewport { .. } => Sizing::Content, @@ -327,9 +328,9 @@ impl<'b> BodyHooks<'b> { None => room, } } - // A pane as tall as its content runs in the rect its caller laid out. + // A pane as large as its content runs in the rect its caller laid out. _ => match (&props.mount, at) { - (Mount::Pane(ShellPane { at: Some(rect), content_height: true, .. }), _) => rect.size(), + (Mount::Pane(ShellPane { at: Some(rect), content_extent: true, .. }), _) => rect.size(), (_, ShowAt::Rect(rect)) => rect.size(), (_, ShowAt::Flow) => { let room = crate::layout::flow_room(ui); diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index af7a6e1d8..046ce0324 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -72,8 +72,10 @@ impl Mount { /// its siblings (so a pane can overlay another) and ignores the extent. Otherwise an edge pane takes /// [`extent`](Self::extent) along its edge from the room left, or, without an extent, the size it first took, which it /// keeps in pane memory until the user resizes it. The central pane fills what the edge panes leave. A pane at a rect -/// that is as tall as its content (a content-sized embedded shell's body) takes the rect's width, its content's height -/// from the rect's top, and that room in the flow of its parent. +/// that is as large as its content along its edge (a content-sized embedded shell's body, a slot sized by its content) +/// takes the rect's cross extent, its content's extent from the rect's outer edge, and that room in the flow of its +/// parent: a top or central pane its height from the rect's top, a bottom pane its height from the rect's bottom, a +/// start or end pane its width from that side. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct ShellPane { @@ -85,14 +87,14 @@ pub struct ShellPane { pub extent: Option, /// The rect the caller laid the pane out in. pub at: Option, - /// The pane at `at` is as tall as its content. - pub(crate) content_height: bool, + /// The pane at `at` is as large as its content along its edge. + pub(crate) content_extent: bool, } impl ShellPane { /// The central pane named `name`. pub const fn new(name: &'static str) -> Self { - ShellPane { name, edge: PaneEdge::Center, extent: None, at: None, content_height: false } + ShellPane { name, edge: PaneEdge::Center, extent: None, at: None, content_extent: false } } /// The pane at `edge`. @@ -113,11 +115,12 @@ impl ShellPane { self } - /// The pane at `rect`, as tall as its content from the rect's top, taking that room in its parent's flow. + /// The pane in `rect`, as large as its content along its edge from the rect's outer edge, taking that room in its + /// parent's flow. `rect` is the room the content may take. #[doc(hidden)] - pub const fn at_content_height(mut self, rect: Rect) -> Self { + pub const fn at_content_extent(mut self, rect: Rect) -> Self { self.at = Some(rect); - self.content_height = true; + self.content_extent = true; self } } diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index af0d72a91..023098a3b 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -270,7 +270,14 @@ impl Cx<'_, C> { /// participate. A control that uses this must sense both clicks and drags. pub fn swept_toggle(&self, on: Option) -> Option { let group = self.pointer_group?; - crate::runtime::toggle_sweep::value(self, group, on) + let target = crate::runtime::toggle_sweep::ToggleTarget { + id: self.id, + layer: self.response.layer_id, + visible: self.visible, + enabled: self.resolved.enabled && !self.resolved.read_only, + press: self.press().phase, + }; + crate::runtime::toggle_sweep::value(&self.ctx, target, group, on) } } diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 2a4423329..9b3647b60 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -356,6 +356,12 @@ pub trait Component: Meta + Sized { /// Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except /// for the roving group of a body the shape declares. const STOPS: bool = true; + /// The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its + /// parts lie inside it, and `FocusPolicy::NONE` (the default) opens none. A scope that restores + /// (`FocusPolicy::TAB_LAYER`) makes the stop focus came from its opener, so focus goes back there when the leaf + /// goes away with focus inside (a canvas text editor hands it back to the canvas). Containers and collections take + /// their scope from their props, not from this. + const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy = crate::runtime::focus::FocusPolicy::NONE; /// Keys the focused component keeps from egui and the shortcut dispatcher. const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(Self::INPUT); /// The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 34137bf9a..fc2e44b89 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -143,11 +143,20 @@ pub(super) fn pane_grip_id(id: Id) -> Id { impl Host for PaneHost { fn run(&mut self, id: Id, parent: &mut Ui, env: &Env, pass: &mut HostPass<'_>) { - // A pane the caller laid out shows in its rect and leaves the room of its siblings alone; one as tall as its - // content flows from the rect's top and takes its height in the parent's flow. + // A pane the caller laid out shows in its rect and leaves the room of its siblings alone; one as large as its + // content flows from the rect's outer edge and takes its extent in the parent's flow. if let Some(rect) = self.0.at { - if self.0.content_height { + if self.0.content_extent { + let rtl = env.direction.is_rtl(); let builder = egui::UiBuilder::new().max_rect(rect); + let builder = match self.0.edge { + PaneEdge::Bottom => builder.layout(egui::Layout::bottom_up(egui::Align::Min)), + PaneEdge::Start | PaneEdge::End if (self.0.edge == PaneEdge::Start) == rtl => { + builder.layout(egui::Layout::right_to_left(egui::Align::Min)) + } + PaneEdge::Start | PaneEdge::End => builder.layout(egui::Layout::left_to_right(egui::Align::Min)), + _ => builder, + }; let mut ui = crate::runtime::egui::alloc::child(parent, builder); pass(&mut ui, Some(ShowAt::Flow), None); crate::runtime::egui::alloc::advance_past(parent, ui.min_rect()); diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 8b993ae88..b57669e22 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -322,6 +322,10 @@ impl ShapeHooks for LeafHooks { self.scope } + fn focus(&self, _: &C) -> Option { + (C::FOCUS_SCOPE != crate::runtime::focus::FocusPolicy::NONE).then_some(C::FOCUS_SCOPE) + } + fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { use craft_behavior::Axis; let room = crate::layout::leaf_fill_room(ui); diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index cc3afde1f..3fe97a269 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -785,7 +785,8 @@ pub(crate) enum FocusOrigin { /// it counts as an arrival by key, and a text part selects its whole text so typing replaces it. Open, /// The focused stop went away and handed focus to its neighbour: neither the keyboard nor a request chose it, so - /// it is no arrival by key (a deleted guide selects no other guide). + /// it is no arrival by key (a deleted guide selects no other guide) and no scroll owner reveals it (a closed canvas + /// text editor does not pan the canvas to the stop before it). Removal, } diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index c8a60dd78..32e9b9dcf 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -168,11 +168,14 @@ impl State { self.focus_stop_from(rec, FocusOrigin::Request) } - /// [`focus_stop`](Self::focus_stop) with what moved focus there. + /// [`focus_stop`](Self::focus_stop) with what moved focus there. A stop that inherits the focus from a removed one + /// is not revealed: nothing chose to show it. fn focus_stop_from(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { let key = rec.stop.key(); let acts = self.enter_stop(rec, origin); - self.revealed = Some(key); + if origin != FocusOrigin::Removal { + self.revealed = Some(key); + } acts } diff --git a/crates/ui-contract/src/runtime/toggle_sweep.rs b/crates/ui-contract/src/runtime/toggle_sweep.rs index 644d7b9ea..4c151ffb6 100644 --- a/crates/ui-contract/src/runtime/toggle_sweep.rs +++ b/crates/ui-contract/src/runtime/toggle_sweep.rs @@ -3,9 +3,8 @@ use std::sync::Arc; use craft_behavior::{PointerButton, PointerEvent, PressPhase, PressStart}; -use egui::{Context, Id, IdSet, LayerId, Pos2, Rect}; +use egui::{Context, Id, IdSet, Pos2, Rect}; -use crate::contract::{CxCore, Pointer as _}; use crate::runtime::egui::{areas, pass}; use crate::runtime::frame::{PerViewport, Stored}; use crate::runtime::pointer::{self, PassPointer}; @@ -143,50 +142,56 @@ impl Record { } } -pub(crate) fn value(cx: &CxCore<'_>, group: Id, on: Option) -> Option { - let ctx = &cx.ctx; +pub(crate) struct ToggleTarget { + pub id: Id, + pub layer: areas::Layer, + pub visible: Rect, + pub enabled: bool, + pub press: PressPhase, +} + +pub(crate) fn value(ctx: &Context, target: ToggleTarget, group: Id, on: Option) -> Option { + let ToggleTarget { id, layer, visible, enabled, press } = target; let viewport = pass::current_viewport(ctx); let pass = pointer::pass_of(ctx); let input = pointer::pass_pointer(ctx); let cancelled = pointer::cancel_of_pass(ctx).is_some(); - let layer = cx.response.layer_id; - let enabled = cx.resolved.enabled && !cx.resolved.read_only; let eligible = |sweep: &Sweep| enabled && sweep.group == group && sweep.travel.dragging; let completed = PerViewport::::with(ctx, viewport, |record| { record.advance(pass, &input, cancelled); let finished = record.completed.as_ref().filter(|finished| eligible(&finished.sweep))?; let sweep = &finished.sweep; - if sweep.owner == cx.id { + if sweep.owner == id { return Some((sweep.on, None)); } - (!sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&finished.path)))) + (!sweep.visited.contains(&id)).then(|| (sweep.on, Some(Arc::clone(&finished.path)))) }) .and_then(|(on, path)| { if let Some(path) = path { - if !crosses_visible(ctx, layer, cx.visible, &path) { + if !crosses_visible(ctx, layer, visible, &path) { return None; } PerViewport::::with(ctx, viewport, |record| { if let Some(finished) = &mut record.completed { - finished.sweep.visited.insert(cx.id); + finished.sweep.visited.insert(id); } }); } Some(on) }); let ready = PerViewport::::with(ctx, viewport, |record| { - match cx.press().phase { + match press { PressPhase::Down { start, .. } if start.button == PointerButton::Primary && enabled => { - record.start(cx.id, group, start, !completed.or(on).unwrap_or(false), &input); + record.start(id, group, start, !completed.or(on).unwrap_or(false), &input); } - PressPhase::Cancel { .. } if record.sweep.as_ref().is_some_and(|sweep| sweep.owner == cx.id) => record.sweep = None, + PressPhase::Cancel { .. } if record.sweep.as_ref().is_some_and(|sweep| sweep.owner == id) => record.sweep = None, _ => {} } let sweep = record.sweep.as_ref().filter(|sweep| eligible(sweep))?; - if sweep.owner == cx.id { + if sweep.owner == id { return Some((sweep.on, None, record.replay_first_path)); } - (!record.path.is_empty() && !sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&record.path)), false)) + (!record.path.is_empty() && !sweep.visited.contains(&id)).then(|| (sweep.on, Some(Arc::clone(&record.path)), false)) }); let Some(ready) = ready else { return completed }; let (on, path, replay) = ready; @@ -194,12 +199,12 @@ pub(crate) fn value(cx: &CxCore<'_>, group: Id, on: Option) -> Option::with(ctx, viewport, |record| { if let Some(sweep) = &mut record.sweep { - sweep.visited.insert(cx.id); + sweep.visited.insert(id); } }); } @@ -227,7 +232,7 @@ fn clipped((from, to): Segment, rect: Rect) -> Option { (start <= end).then(|| (from + delta * start, from + delta * end)) } -pub(crate) fn crosses_visible(ctx: &Context, layer: LayerId, rect: Rect, path: &[Segment]) -> bool { +pub(crate) fn crosses_visible(ctx: &Context, layer: areas::Layer, rect: Rect, path: &[Segment]) -> bool { let map = areas::layer_map(ctx, layer); let rect = map.map_or(rect, |map| Rect::from_min_max(map.to_screen(rect.min), map.to_screen(rect.max))); path.iter().copied().filter_map(|segment| clipped(segment, rect)).any(|(from, to)| areas::layer_between(ctx, layer, from, to)) diff --git a/crates/ui-contract/tests/it/runtime/focus.rs b/crates/ui-contract/tests/it/runtime/focus.rs new file mode 100644 index 000000000..760df0268 --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/focus.rs @@ -0,0 +1,48 @@ +//! Focus after the focused stop goes away. + +use craft_ui::contract::{ContainerProps, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft_ui::runtime::focus::{FocusTarget, request}; +use craft_ui::testing::layout::{Block, in_region}; +use craft_ui::testing::{Frames, trial}; +use craft_ui_test_kit::body::Slab; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::{Cell, RefCell}; + +const ORIGIN: Pos2 = Pos2::new(10.0, 10.0); +const VIEW: Vec2 = Vec2::new(200.0, 100.0); + +/// The focused stop goes away and hands the focus to the next stop in its scope, far below a scrolling body's view: +/// the stop takes the focus and the body stays where it is. A neighbour that inherits the focus was not shown by +/// anyone, so nothing reveals it (#15555: the rulers' corner panned the canvas when a closed text editor handed it the +/// focus). +#[trial] +fn a_stop_that_inherits_the_focus_from_a_removed_one_is_not_revealed() { + let (first, next) = (RefCell::new(Seen::default()), RefCell::new(Seen::default())); + let shown = Cell::new(true); + let top = Cell::new(0.0f32); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + Slab::new(ContainerProps::new().scroll(Scroll::vertical())).id_salt("panel").show(ui, |ui, _| { + top.set(ui.next_widget_position().y); + if shown.get() { + Probe::new(&first).label("First").id_salt("first").show(ui); + } + Block::new(Vec2::new(VIEW.x, VIEW.y * 4.0)).show(ui); + Probe::new(&next).label("Next").id_salt("next").show(ui); + }); + }); + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + let first_id = first.borrow().id.expect("the first stop ran"); + request(&frames.ctx, FocusTarget::Id(first_id)); + frames.idle(3, &mut show); + assert_eq!(craft_ui::testing::focus::egui_focused(&frames.ctx), Some(first_id), "the first stop took the focus"); + let start = top.get(); + shown.set(false); + frames.idle(6, &mut show); + let next_id = next.borrow().id.expect("the next stop ran"); + assert_eq!(craft_ui::testing::focus::egui_focused(&frames.ctx), Some(next_id), "the next stop inherits the focus"); + assert!((top.get() - start).abs() < 0.5, "the body keeps its offset: content top {} from {start}", top.get()); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 735ab1c7a..64d0f989a 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -8,6 +8,7 @@ pub(crate) mod derived; pub(crate) mod elapsed; pub(crate) mod env; pub(crate) mod fingers; +pub(crate) mod focus; pub(crate) mod frame; pub(crate) mod latch; pub(crate) mod memory; diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index bf6bdb195..aa368fa9b 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -5,8 +5,8 @@ use super::hide::{self, PruneKey}; use crate::contract::Revision; use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ - Bind, BindMut, BodyCx, Cx, Entry, MemoKey, NoValue, Outcome, Pad, Pointer as _, Props as _, Show as _, ShowContainer as _, Sizing, Tracked, - WordSetCx as _, + Bind, BindMut, BodyCx, Cx, Entry, MemoKey, MemoProps, MemoView, NoValue, Outbox, Outcome, Pad, Pointer as _, Props as _, Show as _, + ShowContainer as _, Sizing, Tracked, WordSetCx as _, }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; @@ -934,17 +934,25 @@ impl Pass<'_, P> { } /// The grip strip on top of a tool rail the host shows itself: the dock's grip marks over a band that drags the - /// group, which floats at `size`, the group's size. + /// group, which floats at `size`, the group's size. A memoized view ([`rail_grip`]) held to the strip, so a frame + /// whose input is elsewhere replays it, as the column bars and the groups' tab rows replay. fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) { let scene = self.scene; let label = Label::from(scene.spec(shown).label.as_str().to_owned()); - let held = GroupGrip::new(DragUnit::Group(anchor.clone()), PanelKey::of(shown)) - .ticks(true) - .movable(scene.permissions(shown).movable) - .ghost(label.clone()) - .label(label) - .show_at(ui, strip); - if held.drag_started { + let mut sent = Vec::new(); + ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| { + let props = RailGrip { + unit: DragUnit::Group(anchor.clone()), + active: PanelKey::of(shown), + movable: scene.permissions(shown).movable, + label, + sent: Outbox::new(&mut sent), + }; + // Keyed by the rail's group: unique among the rails a dock area shows. + let _ = MemoView::new(("rail grip", PanelKey::of(anchor)), props, rail_grip::

).show(ui); + }); + // The group's size goes on the drag here, outside the view, whose measuring runs see no size. + if !sent.is_empty() { drag::amend::>(ui.ctx(), |drag| drag.source = Some(size)); } } @@ -1580,3 +1588,30 @@ fn window_edit( fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) { panels.borrow_mut().body(panel, ui, body); } + +/// The props of a tool rail's grip strip: the group it drags, its name, and the outbox the drag's start goes to. +#[derive(MemoProps)] +struct RailGrip<'a, P> { + #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] + unit: DragUnit

, + active: PanelKey, + movable: bool, + label: Label, + sent: Outbox<'a, ()>, +} + +/// A tool rail's grip strip: the dock's grip marks over the view's room, which a drag moves the rail's group by. +fn rail_grip(props: &mut RailGrip<'_, P>, ui: &mut Ui) { + let strip = ui.max_rect(); + let held = GroupGrip::new(props.unit.clone(), props.active) + .ticks(true) + .movable(props.movable) + .ghost(props.label.clone()) + .label(props.label.clone()) + .show_at(ui, strip); + if held.drag_started { + props.sent.send(()); + } + // The grip takes no room in flow; the run covers the strip, so the pointer over it runs it again. + ui.expand_to_include_rect(strip); +} diff --git a/crates/ui-patterns/tests/it/docking/group_view.rs b/crates/ui-patterns/tests/it/docking/group_view.rs index 616e18b57..048a81508 100644 --- a/crates/ui-patterns/tests/it/docking/group_view.rs +++ b/crates/ui-patterns/tests/it/docking/group_view.rs @@ -7,7 +7,7 @@ use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, DockSizes, DragUnit, GroupAt, GroupDrag, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::{Fixture, last_pass_runs, pointer, trial}; use egui::{Rect, Shape, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -144,3 +144,24 @@ fn a_tool_rail_shown_by_its_host_has_a_grip_strip_that_drags_it() { assert_eq!(unit, Some(DragUnit::Group(RAIL)), "a drag on the grip moves the rail's group"); fixture.release_at(strip.center() + Vec2::new(200.0, 0.0)).settle(); } + +/// The rail's grip strip is a memoized view: a pointer moving elsewhere in the window replays it, as it replays the +/// column bars and the tab rows, and runs no grip (photocraft#16333). +#[trial] +fn a_tool_rails_grip_strip_replays_while_the_pointer_moves_elsewhere() { + let seen = Rc::new(Cell::new(None)); + let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![RAIL], 0)]).with_steps(1)]); + let root = Node::split(Axis::X, SplitSize::FixedFirst(120.0), dock, Node::tabs(vec![1], 0)); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let (mut panels, specs) = (RailPanels { seen: seen.clone() }, Tracked::new(RailSpecs)); + let mut fixture = Fixture::new(move |ui| { + let _ = DockArea::new("Rail dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(800.0, 600.0)).settle(); + let grips = + |fixture: &Fixture| last_pass_runs(fixture.ctx()).into_iter().filter(|(ty, _)| ty.contains("GroupGrip<")).map(|(_, runs)| runs).sum::(); + for step in 1..=3 { + fixture.frame(vec![pointer::moved(egui::pos2(500.0 + step as f32, 300.0))]); + assert_eq!(grips(&fixture), 0, "pointer step {step}: the rail's grip replays its last run"); + } +} diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index 5b341b4eb..8761a0b51 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -743,6 +743,15 @@ impl<'a, S> AppShell<'a, S> { let mut floated: Vec<(RevealEdge, Rect)> = Vec::new(); let rect_of = |key| regions.slots.iter().find(|(shown, _)| *shown == key).map_or(Rect::ZERO, |(_, rect)| *rect); + // The room a content slot can grow into: from its outer edge to the far edge of what the slots before it + // leave. Its content runs there, so it measures at its own extent, never at the extent it was laid out at. + let window_rect = cx.rect; + let grow_room = |key: SlotKey| { + let Some(at) = claims.iter().position(|claim| claim.key == key) else { return Rect::ZERO }; + let mut claimed = claims[..=at].to_vec(); + claimed[at].extent = f32::INFINITY; + layout(window_rect, &claimed, rtl).slots.get(at).map_or(Rect::ZERO, |(_, rect)| *rect) + }; // The extents the content slots were laid out at, and what their content took in this pass. let measured_before = kept.measured.clone(); let mut measured_now: Vec<(SlotKey, f32)> = Vec::new(); @@ -757,7 +766,7 @@ impl<'a, S> AppShell<'a, S> { } if let Some((scope, SlotBody(page))) = page.as_mut() { let pane = ShellPane::new("page"); - let pane = if content_room.is_some() { pane.at_content_height(regions.body) } else { pane.at(regions.body) }; + let pane = if content_room.is_some() { pane.at_content_extent(regions.body) } else { pane.at(regions.body) }; let mut region = ShellRegion::pane(pane).label(body_label.clone()); region.props = region.props.command_scope(*scope); let shown = region.show(ui, |ui, bcx| page(ui, bcx, app)); @@ -778,9 +787,9 @@ impl<'a, S> AppShell<'a, S> { if !*shown || if floats { !covering } else { covers(&placed.slot, only) != covering } { continue; } - let extent = placed.extent(&tokens, &measured_before); let by_content = placed.sized_by_content(); let along_x = placed.along_x(); + let extent = placed.extent(&tokens, &measured_before); let Placed { slot, edge, named, add, .. } = placed; let label = slot.name().cloned().or_else(|| named.map(|name| name(&words))); if floats { @@ -790,8 +799,10 @@ impl<'a, S> AppShell<'a, S> { floated.extend(edge.reveal_edge().map(|edge| (edge, layer.output.response.rect))); continue; } - let at = rect_of(slot.key()); - let pane = ShellPane::new(slot.key()).edge(*edge).extent(extent).at(at); + // A slot sized by its content is as large as its content from its outer edge, in the room it + // can grow into; any other slot takes its extent and fills its rect. + let pane = ShellPane::new(slot.key()).edge(*edge); + let pane = if by_content { pane.at_content_extent(grow_room(slot.key())) } else { pane.extent(extent).at(rect_of(slot.key())) }; // Every slot is a chrome pane: it paints the surface under its bar or rail and the rule toward // the body. let mut region = ShellRegion::chrome(pane).id_salt(("slot", slot.key())); @@ -809,28 +820,19 @@ impl<'a, S> AppShell<'a, S> { region.show(ui, |ui, bcx| add(ui, bcx, app)); continue; } - // The slot's extent along its edge: what its content allocated, plus what the pane keeps + // The slot's extent along its edge is the pane's: its content's, with what the pane keeps // around its body (its rule). A top or bottom slot's content fills its width and is as tall - // as it is; a rail's is as wide as it is. The content is read from the `Ui` it allocated in, - // never from the stack's response: a response rect is clipped to the pane (`sense_root`), so - // it can never report more than the extent the slot was laid out at. - let took = region - .show(ui, |ui, bcx| { - let room = ui.max_rect(); - let inset = (if along_x { at.width() - room.width() } else { at.height() - room.height() }).max(0.0); - let stack = if along_x { Stack::new() } else { Stack::new().fill_width() }; - stack - .show(ui, |ui, _| { - add(ui, bcx, app); - let content = ui.min_rect(); - if along_x { content.width() } else { content.height() } - }) - .inner - .map(|content| content + if inset.is_finite() { inset } else { 0.0 }) - }) - .inner - .flatten(); - if let Some(took) = took.filter(|took| took.is_finite() && *took > 0.0) { + // as it is; a rail's is as wide as it is. Only the slot's own real run records it: a run in a + // sizing pass (the scope's measuring run, which alone runs for a shell out of sight) is not + // what shows. + let shown = region.show(ui, |ui, bcx| { + let stack = if along_x { Stack::new() } else { Stack::new().fill_width() }; + stack.show(ui, |ui, _| add(ui, bcx, app)); + !ui.is_sizing_pass() + }); + let pane = shown.output.response.rect; + let took = if along_x { pane.width() } else { pane.height() }; + if shown.inner == Some(true) && took.is_finite() && took > 0.0 { measured_now.push((key, took)); } } @@ -840,7 +842,7 @@ impl<'a, S> AppShell<'a, S> { // mode's surround (Focus's black). Otherwise the body paints what it shows, and the gaps between its parts // (the dock's gutters) show the window's background; Immersive's body fills the room with its own canvas. let pane = ShellPane::new("body"); - let pane = if content_room.is_some() { pane.at_content_height(regions.body) } else { pane.at(regions.body) }; + let pane = if content_room.is_some() { pane.at_content_extent(regions.body) } else { pane.at(regions.body) }; let mut center = ShellRegion::pane(pane).label(body_label.clone()); let surround = if only && !host_only { Some(SurfaceKind::Scrim) } else { mode.surround() }; if let Some(surface) = surround { diff --git a/crates/ui-shell/src/shell/regions.rs b/crates/ui-shell/src/shell/regions.rs index 332644a37..150a55d64 100644 --- a/crates/ui-shell/src/shell/regions.rs +++ b/crates/ui-shell/src/shell/regions.rs @@ -22,10 +22,17 @@ pub enum SlotSize { OptionsBarNarrow, /// `size.rail.width`: the default extent of a start or end slot. RailWidth, - /// As tall (a top or bottom slot) or as wide (a start or end slot) as its content: the extent the content took the - /// last time the slot showed, and the edge's default until it first shows. The slot stacks its content from its - /// outer edge instead of centring one line in it, so content of more than one line (a ribbon: a tab strip over a - /// group row) gets its own height and the slot's full width. Outside a shell it resolves to `size.bar.options`. + /// As tall (a top or bottom slot) or as wide (a start or end slot) as its content. The window is laid out at the + /// extent the content took the last time the slot showed (the edge's default until it first shows), while the + /// content runs in the room the slot can grow into, from its outer edge to the far edge of what the slots before it + /// leave: it measures at its own extent, and when that differs the shell lays the window out again in the same + /// frame. The slot stacks its content from its outer edge instead of centring one line in it, so content of more + /// than one line (a ribbon: a tab strip over a group row) gets its own height and the slot's full width. + /// + /// The slot never takes more than the room the window leaves it: content larger than that, unless it scrolls, + /// is cut at the window's edge. Raw egui content allocates its own extent along the slot's edge; content that takes whatever room it is + /// offered (`ui.available_size()`) takes the whole room the slot can grow into. Outside a shell it resolves to + /// `size.bar.options`. Content, } diff --git a/crates/ui-shell/tests/it/dialog/contained.rs b/crates/ui-shell/tests/it/dialog/contained.rs index e049c8daa..70a82595e 100644 --- a/crates/ui-shell/tests/it/dialog/contained.rs +++ b/crates/ui-shell/tests/it/dialog/contained.rs @@ -6,7 +6,7 @@ use craft_ui::dialog::Dialog; use craft_ui::layout_components::Stack; use craft_ui::runtime::env::WindowKey; use craft_ui::sections::{DialogRole, FooterButton}; -use craft_ui::shell::AppShell; +use craft_ui::shell::{AppShell, Slot, SlotSize}; use craft_ui::testing::contract::clicked; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Ui}; @@ -87,16 +87,24 @@ fn a_dialog_in_an_embedded_region_is_placed_in_it_and_blocks_only_it() { } /// An embedded shell scrolled out of sight with its dialog open shows nothing and does not fail: its region has no -/// room, so neither its body nor its dialog runs in that pass. +/// room, so neither its body, its dialog nor a slot sized by its content runs in that pass. #[trial] fn an_embedded_shell_out_of_sight_shows_nothing() { - let mut fixture = Fixture::new(|ui| { + let real = Rc::new(Cell::new(0_u32)); + let count = Rc::clone(&real); + let mut fixture = Fixture::new(move |ui| { Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { let _ = Button::new("Top").show(ui); let view = ui.clip_rect(); let below = Rect::from_min_size(egui::pos2(view.min.x, view.max.y + view.height()), egui::vec2(view.width(), view.height())); let mut open = true; AppShell::embedded(WindowKey::new("out-of-sight")) + .top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| { + if !ui.is_sizing_pass() { + count.set(count.get() + 1); + } + let _ = Button::new("Slot").show(ui); + }) .body(|ui, _, _| { let _ = Button::new("Hidden").show(ui); Dialog::new("Out of sight").opened(Bind::bound(&mut open)).show(ui, |_, _| {}); @@ -108,4 +116,5 @@ fn an_embedded_shell_out_of_sight_shows_nothing() { assert!(fixture.by_label("Top").is_some(), "the visible part is shown"); assert!(fixture.by_role(Role::DIALOG).is_empty(), "the dialog of a shell out of sight is not shown"); assert!(fixture.by_label("Hidden").is_none(), "the body of a shell out of sight does not run"); + assert!(fixture.by_label("Slot").is_none() && real.get() == 0, "the content slot of a shell out of sight does not run"); } diff --git a/crates/ui-shell/tests/it/shell/app_shell.rs b/crates/ui-shell/tests/it/shell/app_shell.rs index 182a4acd4..2f751c089 100644 --- a/crates/ui-shell/tests/it/shell/app_shell.rs +++ b/crates/ui-shell/tests/it/shell/app_shell.rs @@ -3,10 +3,13 @@ //! body, and its band keeps the window's ends and moves the window. What the body opens stops above the bottom slots. use craft_host::target::{Os, ShellInfo}; +use craft_theme::Size; use craft_ui::bars::{Bar, BarKind}; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, CommandSet, Entry, MemoProps, MemoView, Props as _, Role, Scroll, Show as _, ShowContainer as _, Trigger}; +use craft_ui::contract::{ + Bind, CommandSet, Entry, MemoProps, MemoView, Props as _, Role, Scroll, Show as _, ShowContainer as _, Sizing, Trigger, +}; use craft_ui::dialog::Dialog; use craft_ui::display::Text; use craft_ui::layout_components::{Row, Stack}; @@ -141,6 +144,198 @@ fn a_top_slot_sized_by_its_content_stacks_it_and_takes_its_height() { assert!(body.min.y >= row.max.y - SLACK, "the body {body:?} starts under the row {row:?}"); } +/// The labels of a column of buttons taller than a slot's default extent. +const TALL: [&str; 6] = ["Paste", "Cut", "Copy", "Format Painter", "Clipboard", "Styles"]; + +/// The rect of the fill-height column a content slot holds and of each of its buttons, from the last run. +type Column = Rc)>>; + +fn column() -> Column { + Rc::new(RefCell::new((Rect::NOTHING, Vec::new()))) +} + +/// A column of `labels` that fills its height, as a ribbon group does, recording its rects in `seen`. +fn fill_column(ui: &mut Ui, labels: &[&'static str], seen: &Column) { + let mut buttons = Vec::new(); + let column = Stack::new() + .sizing(Sizing::FillHeight) + .show(ui, |ui, _| { + for label in labels { + buttons.push(Button::new(*label).show(ui).rect); + } + }) + .output + .rect; + *seen.borrow_mut() = (column, buttons); +} + +/// A content slot whose content fills its height grows to that content, at the top and at the bottom edge: its +/// content runs in the room the slot can grow into, not in the extent it was first laid out at, so the column takes +/// its buttons' height and the slot takes the column's. +#[trial] +fn a_slot_sized_by_its_content_grows_to_a_child_that_fills_its_height() { + let (top, bottom) = (column(), column()); + let regions = Rc::new(RefCell::new(None)); + let (top_seen, bottom_seen, out) = (Rc::clone(&top), Rc::clone(&bottom), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| fill_column(ui, &TALL, &top_seen)) + .bottom(Slot::new("findBar").size(SlotSize::Content), |ui, _, _: &mut ()| fill_column(ui, &TALL, &bottom_seen)) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.room(Vec2::new(600.0, 700.0)).settle(); + let regions = regions.borrow().clone().expect("the shell shows"); + const SLACK: f32 = 1.0; + for (key, seen) in [("ribbon", &top), ("findBar", &bottom)] { + let slot = regions.slots.iter().find(|(shown, _)| *shown == key).map(|(_, rect)| *rect).expect("the slot shows"); + let (column, buttons) = seen.borrow().clone(); + assert_eq!(buttons.len(), TALL.len(), "{key}: every button shows"); + for button in &buttons { + assert!(column.expand(SLACK).contains_rect(*button), "{key}: the button {button:?} lies in its column {column:?}"); + } + assert!(slot.expand(SLACK).contains_rect(column), "{key}: the slot {slot:?} holds its column {column:?}"); + } + let (top_slot, bottom_slot) = (regions.slots[0].1, regions.slots[1].1); + assert!( + regions.body.min.y >= top_slot.max.y - SLACK && regions.body.max.y <= bottom_slot.min.y + SLACK, + "the body {:?} lies between the slots", + regions.body + ); + assert!((bottom_slot.max.y - 700.0).abs() <= SLACK, "the bottom slot {bottom_slot:?} stands on the window's bottom edge"); +} + +/// A settled frame runs a content slot's content once, in one pass: its measure is reused while its inputs are +/// unchanged. A frame where the content grows (a roomier density makes every button taller) lays the window out again +/// at most once, shows the new extent in that frame and leaves the next frame settled. +#[trial] +fn a_content_slot_runs_its_content_once_per_settled_frame_and_grows_in_one_frame() { + let runs = Rc::new(Cell::new(0_u32)); + let seen = column(); + let regions = Rc::new(RefCell::new(None)); + let (count, column, out) = (Rc::clone(&runs), Rc::clone(&seen), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| { + count.set(count.get() + 1); + fill_column(ui, &TALL, &column); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.room(Vec2::new(600.0, 700.0)).density(Size::Compact).settle(); + let before = seen.borrow().0; + runs.set(0); + fixture.frame(Vec::new()); + assert_eq!(fixture.passes(), 1, "a settled frame runs one pass"); + assert_eq!(runs.get(), 1, "a settled frame runs the slot's content once"); + fixture.density(Size::Comfortable).frame(Vec::new()); + assert!(fixture.passes() <= 2, "the frame the content grows in lays the window out again at most once: {} passes", fixture.passes()); + let slot = regions.borrow().as_ref().and_then(|regions| regions.slots.first().map(|(_, rect)| *rect)).expect("the slot shows"); + let grown = seen.borrow().0; + assert!(grown.height() > before.height() + 1.0, "the roomier density makes the column taller: {before:?} to {grown:?}"); + assert!(slot.expand(1.0).contains_rect(grown), "in the frame it grows in, the slot {slot:?} holds the grown column {grown:?}"); + runs.set(0); + fixture.frame(Vec::new()); + assert_eq!(fixture.passes(), 1, "the frame after the grow is settled: one pass"); + assert_eq!(runs.get(), 1, "the frame after the grow runs the slot's content once"); +} + +/// Content rails sit at their own sides in either reading direction, each as wide as the column it holds, and a +/// settled frame runs one pass with each rail's content once: the start rail at the reading start, the end rail at the +/// reading end, the body between them. +#[trial] +fn content_rails_sit_at_their_sides_and_settle_in_one_pass() { + const RAIL: [&str; 3] = ["Move", "Brush", "Eraser"]; + for rtl in [false, true] { + let direction = if rtl { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr }; + let (start, end) = (column(), column()); + let (start_runs, end_runs) = (Rc::new(Cell::new(0_u32)), Rc::new(Cell::new(0_u32))); + let regions = Rc::new(RefCell::new(None)); + let (start_seen, end_seen, start_count, end_count, out) = + (Rc::clone(&start), Rc::clone(&end), Rc::clone(&start_runs), Rc::clone(&end_runs), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .start(Slot::new("tools").size(SlotSize::Content), |ui, _, _: &mut ()| { + start_count.set(start_count.get() + 1); + fill_column(ui, &RAIL, &start_seen); + }) + .end(Slot::new("inspector").size(SlotSize::Content), |ui, _, _: &mut ()| { + end_count.set(end_count.get() + 1); + fill_column(ui, &RAIL, &end_seen); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.direction(direction).room(Vec2::new(600.0, 400.0)).settle(); + let regions = regions.borrow().clone().expect("the shell shows"); + const SLACK: f32 = 1.0; + let rect_of = |key| regions.slots.iter().find(|(shown, _)| *shown == key).map(|(_, rect)| *rect).expect("the rail shows"); + let (start_rail, end_rail) = (rect_of("tools"), rect_of("inspector")); + for (key, rail, seen) in [("tools", start_rail, &start), ("inspector", end_rail, &end)] { + let (column, buttons) = seen.borrow().clone(); + assert_eq!(buttons.len(), RAIL.len(), "RTL {rtl}, {key}: every button shows"); + for button in &buttons { + assert!(column.expand(SLACK).contains_rect(*button), "RTL {rtl}, {key}: the button {button:?} lies in its column {column:?}"); + } + assert!(rail.expand(SLACK).contains_rect(column), "RTL {rtl}, {key}: the rail {rail:?} holds its column {column:?}"); + } + let body = regions.body; + let (left, right) = if rtl { (end_rail, start_rail) } else { (start_rail, end_rail) }; + assert!(left.max.x <= body.min.x + SLACK, "RTL {rtl}: the rail {left:?} lies left of the body {body:?}"); + assert!(right.min.x >= body.max.x - SLACK, "RTL {rtl}: the rail {right:?} lies right of the body {body:?}"); + start_runs.set(0); + end_runs.set(0); + fixture.frame(Vec::new()); + assert_eq!(fixture.passes(), 1, "RTL {rtl}: a settled frame runs one pass"); + assert_eq!((start_runs.get(), end_runs.get()), (1, 1), "RTL {rtl}: a settled frame runs each rail's content once"); + } +} + +/// A content slot holding a list that scrolls along its height is as tall as the list's rows, whether the list sizes +/// from its content or fills its height: the slot offers its content no bound along its edge, so the list shows all +/// of its rows instead of taking the window's height, and the body keeps the rest of the window. +#[trial] +fn a_content_slot_holding_a_scrolling_list_takes_the_list_height() { + for sizing in [Sizing::Content, Sizing::FillHeight, Sizing::Fill] { + let rows = Rc::new(RefCell::new(Vec::new())); + let regions = Rc::new(RefCell::new(None)); + let (seen, out) = (Rc::clone(&rows), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .top(Slot::new("findBar").size(SlotSize::Content), |ui, _, _: &mut ()| { + let mut buttons = Vec::new(); + Stack::new().sizing(sizing).scroll(Scroll::vertical()).show(ui, |ui, _| { + for label in ["First", "Second", "Third"] { + buttons.push(Button::new(label).show(ui).rect); + } + }); + *seen.borrow_mut() = buttons; + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.room(Vec2::new(600.0, 700.0)).settle(); + let regions = regions.borrow().clone().expect("the shell shows"); + let slot = regions.slots.iter().find(|(key, _)| *key == "findBar").map(|(_, rect)| *rect).expect("the slot shows"); + let rows = rows.borrow().iter().fold(Rect::NOTHING, |all, row| all.union(*row)); + const SLACK: f32 = 1.0; + // The rule toward the body, the stack's padding and rounding. + const AROUND: f32 = 24.0; + assert!(slot.expand(SLACK).contains_rect(rows), "{sizing:?}: the slot {slot:?} holds the list's rows {rows:?}"); + assert!(slot.height() <= rows.height() + AROUND, "{sizing:?}: the slot {slot:?} is as tall as the list's rows {rows:?}, not the window"); + let body = regions.body; + assert!( + body.min.y >= slot.max.y - SLACK && (body.max.y - 700.0).abs() <= SLACK, + "{sizing:?}: the body {body:?} keeps the window under the slot {slot:?}" + ); + } +} + /// A check box with its label after it sits on the options slot's middle, as a button beside it does: the slot is /// shorter than the bar asks for, and the bar centres its members in it. #[trial] diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index e89caad5b..171f917fb 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -329,7 +329,6 @@ impl Row { /// The row's line is at least `points` high, as a child of more than one line that high would make it: the /// children that fill the line's height take at least it. A row of command groups keeps the height of its /// rows of controls while its groups are shorter. Ignored by a row that wraps. - // design: allow[props/point-size](the least line of a row is the caller's measured extent (three control rows of a look and a title line), not a chosen size) pub fn least_height(mut self, points: f32) -> Self { self.props = self.props.least_height(points); self diff --git a/design/exceptions/craft-ui-widgets/display.toml b/design/exceptions/craft-ui-widgets/display.toml index 3669a55bf..88f56e78b 100644 --- a/design/exceptions/craft-ui-widgets/display.toml +++ b/design/exceptions/craft-ui-widgets/display.toml @@ -1,9 +1 @@ config_version = 1 - -[[exception]] -name = "divider-length-content-extent" -kind = "marker" -rule = "props/point-size" -path = "crates/ui-widgets/src/display/divider.rs" -reason = "The length is the measured extent of the owner's content (a group as tall as its content and title), not a chosen size." -count = 1 diff --git a/docs/contract-api.md b/docs/contract-api.md index 49b52c58c..a5d810da1 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1837,6 +1837,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `const OVERLAYS: bool`. Whether the component hosts popups: `false` skips the overlay bookkeeping of steps 9, 10, 12, 15 and 16. - `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 - `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