From e287056dc3d1eb5ff05a66ac4720e2341bc651d0 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 01:40:49 +0100 Subject: [PATCH 01/37] A click on a mixed slider sets the value under it While the value was mixed the slider placed its grab at the middle of the track, so a click there grabbed a thumb that was not drawn and changed nothing. A mixed value now has no thumb to grab: any press jumps to the pointer, and a click sets that value. --- crates/ui-widgets/src/value_drag/slider.rs | 18 +++++++++++------- crates/ui-widgets/tests/it/value_drag.rs | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/ui-widgets/src/value_drag/slider.rs b/crates/ui-widgets/src/value_drag/slider.rs index fac7f09da3..593e570027 100644 --- a/crates/ui-widgets/src/value_drag/slider.rs +++ b/crates/ui-widgets/src/value_drag/slider.rs @@ -1,8 +1,8 @@ //! `Slider`: a thumb on a track over an `f64` range. A press on the thumb grabs it and a drag moves it by the pointer's -//! travel; a press on the track jumps the thumb there; arrows, the wheel and AccessKit step the value; a double click -//! or the reset intent restores the binding's reset value. The vertical wheel steps it while it is focused or armed, so -//! a panel scrolls over it; inside a `WheelScope::Free` scope (an adjustment dialog) without focus too. The track maps -//! positions to values through a [`SliderScale`], linear by default. +//! travel; a press on the track, or any press while the value is mixed, jumps the thumb there; arrows, the wheel and +//! AccessKit step the value; a double click or the reset intent restores the binding's reset value. The vertical wheel +//! steps it while it is focused or armed, so a panel scrolls over it; inside a `WheelScope::Free` scope (an adjustment +//! dialog) without focus too. The track maps positions to values through a [`SliderScale`], linear by default. use super::track::{self, Along, Fill, MarkInk, MarkSpace, Marks, Press, Scale, SliderScale, ThumbRing, TrackFace, Travel}; use crate::contract::{ @@ -258,7 +258,11 @@ impl Component for Slider<'_> { let marks = &self.marks; let at = |position: f64| marks.snapped(&scale, length, position).unwrap_or_else(|| scale.snap(scale.at_position(position))); let current = |cx: &Cx<'_, Self>| cx.value().copied().unwrap_or_else(|| scale.middle()); - let press_at = |cx: &Cx<'_, Self>, x: f32| pick.press(&[along.x(scale.position(current(cx)))], x); + // A mixed value has no thumb to grab, so a press anywhere jumps it to the pointer: a click sets that value. + let press_at = |cx: &Cx<'_, Self>, x: f32| match cx.value() { + Some(value) => pick.press(&[along.x(scale.position(*value))], x), + None => Some(Press::Jump(0)), + }; for key in [Self::THUMB, TRACK] { let press = cx.part(key).press; match press.phase { @@ -285,8 +289,8 @@ impl Component for Slider<'_> { && let Some(jump @ Press::Jump(_)) = press_at(&*cx, start.origin.x) && let Some(next) = travel.value(jump, 0.0, &press, false) { - // A press on the track jumps to the pointer; a click on the thumb changes nothing. A second - // click is the reset, which the pipeline applies. + // A press on the track, or on a mixed slider, jumps to the pointer; a click on the thumb + // changes nothing. A second click is the reset, which the pipeline applies. cx.set(at(next)); } } diff --git a/crates/ui-widgets/tests/it/value_drag.rs b/crates/ui-widgets/tests/it/value_drag.rs index 507caf2eb9..df49fa344a 100644 --- a/crates/ui-widgets/tests/it/value_drag.rs +++ b/crates/ui-widgets/tests/it/value_drag.rs @@ -98,6 +98,20 @@ fn a_grabbed_slider_thumb_moves_by_the_pointer_travel_and_a_click_on_it_changes_ assert_eq!(slide.value(), START, "a click on the thumb leaves the value"); } +/// A mixed slider has no thumb to grab: a click where a single value's thumb would sit, the middle step, sets that step. +#[trial] +fn a_click_on_a_mixed_slider_sets_the_step_under_it() { + use craft_behavior::Mixed; + let value = Rc::new(RefCell::new(Mixed::::Mixed)); + let shown = value.clone(); + let mut fixture = Fixture::new(move |ui| { + Slider::new(Bind::bound_mixed(&mut *shown.borrow_mut()), 0.0..=10.0).step(1.0).label("Hyphenation Weight").show_at(ui, FIELD); + }); + fixture.motion(MotionMode::Off).settle(); + fixture.click_at(FIELD.center()).settle(); + assert_eq!(*value.borrow(), Mixed::Same(5.0), "the click set the middle step"); +} + /// A trimmed span's ends are drawn across the track, not stops: a drag that ends beside one lands where the drag /// puts it. #[trial] From 706226f571a22a6addda423ecbc45b30809d75f0 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 01:45:26 +0100 Subject: [PATCH 02/37] Let a secondary press outside a menu reach the part below A menu absorbed a press of any button outside it, so a right-click on another control or the canvas closed the menu and was lost. The input hook's doc said only primary presses are absorbed; now every outside press still closes the menu, but only a primary one is removed, so a right-click elsewhere closes the menu and opens the menu there, as in native apps. Adds a trial: with a control's context menu open, a right-click on the canvas closes it and the canvas asks for its own menu at that point. --- crates/ui-canvas/tests/it/canvas/tool.rs | 48 +++++++++++++++++++ .../src/contract/overlay/dismissal.rs | 3 +- .../ui-contract/src/contract/overlay/props.rs | 5 +- crates/ui-contract/src/runtime/frame.rs | 2 +- crates/ui-contract/src/runtime/overlay.rs | 17 +++---- crates/ui-contract/src/runtime/pointer.rs | 2 +- crates/ui-widgets/src/menu/popup.rs | 4 +- docs/contract-api.md | 4 +- docs/craft-framework.md | 2 +- 9 files changed, 69 insertions(+), 18 deletions(-) diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index 37df9547e4..c6a8819b2d 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -5,6 +5,7 @@ use craft_behavior::geometry::{SnapKind, SnapLine, SnapOptions, SnapTarget, Snap use craft_behavior::kurbo::{Point, Size}; use craft_behavior::{Axis, CancelReason, CanvasView, Cursor, CursorIcon, GesturePhase, PointerButton, PointerSample}; use craft_keymap::Mods; +use craft_ui::buttons::Button; use craft_ui::canvas::{ Autoscroll, Canvas, CanvasScrollbars, CanvasTool, ContextRequest, CropOverlay, HandTool, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, Snap, StandInKey, ToolAction, ToolClaims, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer, ToolRegion, @@ -14,6 +15,7 @@ use craft_ui::contract::tooltip::DELAY; use craft_ui::contract::{Bind, MemoProps, MemoView, Sampler as _, Show as _, ShowContainer as _}; use craft_ui::dialog::Dialog; use craft_ui::display::Text; +use craft_ui::menu::{Menu, MenuItem}; use craft_ui::primitives::Draw; use craft_ui::runtime::access::Role; use craft_ui::runtime::commands::{CommandGate, CommandSet as _}; @@ -1492,6 +1494,52 @@ fn menu_canvas(momentary: bool, bars: bool) -> MenuRig { (fixture, contexts, view, rect) } +/// A right-click on the canvas while another control's context menu is open closes that menu and reaches the canvas, +/// which asks for its own menu where the button came up, as a second right-click does in a native app: only a primary +/// press outside a menu goes no further. +#[trial] +fn a_right_click_on_the_canvas_closes_another_context_menu_and_asks_for_the_canvas_menu() { + const OPENER: Rect = Rect { min: Pos2::new(8.0, 8.0), max: Pos2::new(120.0, 32.0) }; + let (contexts, rect) = (Rc::new(RefCell::new(Vec::new())), Rc::new(Cell::new(Rect::NOTHING))); + let (shown_contexts, shown_rect, shown_view) = (Rc::clone(&contexts), Rc::clone(&rect), Cell::new(None::)); + let mut hand = HandTool::new(NavigationOptions::default()); + let mut fixture = Fixture::new(move |ui| { + let layers = Button::new("Layers").show_at(ui, OPENER); + Menu::context("Layers menu", &layers).show(ui, |ui, _| { + MenuItem::new("Duplicate layer").show(ui); + }); + // The canvas fills the right half of the window, clear of the opener and of the menu it opens. + let room = ui.max_rect(); + let room = Rect::from_min_max(Pos2::new(room.center().x, room.min.y), room.max); + let current = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(600.0, 450.0), 4.0)); + shown_rect.set(room); + let mut reply = None; + let shown = Canvas::new("Document").document(DOCUMENT).view(current).show_at(ui, room, |ui, body| { + if let Some(pass) = tool_pass(&body.env) { + reply = Some(ToolHost::new().run(ui, &pass, &mut hand)); + } + }); + let reply = reply.unwrap_or_default(); + shown_contexts.borrow_mut().extend(reply.context); + shown_view.set(Some(reply.view.or(shown.output.view).unwrap_or(current))); + }); + fixture.settle(); + let right_click = |fixture: &mut Fixture, at: Pos2| { + fixture.frame(vec![pointer::moved(at)]).frame(vec![pointer::secondary(at, true)]).frame(vec![pointer::secondary(at, false)]); + fixture.settle(); + }; + let opener = fixture.by_label("Layers").expect("the opener has a node").center(); + right_click(&mut fixture, opener); + let menu = fixture.by_role(Role::MENU).first().map(|menu| menu.rect).expect("the right-click on Layers opens its menu"); + let at = rect.get().center(); + assert!(!menu.contains(at), "the canvas point lies outside the menu: {menu:?} {at:?}"); + assert!(contexts.borrow().is_empty(), "the canvas was not asked yet: {:?}", contexts.borrow()); + right_click(&mut fixture, at); + assert!(fixture.by_label("Duplicate layer").is_none(), "the right-click on the canvas closed the Layers menu"); + let asked = contexts.borrow().iter().map(|request| request.at).collect::>(); + assert_eq!(asked, [at], "the secondary press reached the canvas, which asks for its menu where it came up"); +} + #[trial] fn a_drag_past_the_canvas_edge_scrolls_the_view_and_a_turned_view_scrolls_on_the_clipped_axis() { for (rotation, upright) in [(0.0, true), (90.0, false)] { diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index e2c8379e34..26fcc1d073 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -33,7 +33,8 @@ pub(super) fn dismissal( if dismiss.anchor_gone && layer.overlay.opener.as_ref().is_some_and(|first| !first.active(ctx, None).0.enabled) { return Some(CloseReason::AnchorGone); } - // The input hook removed the press and recorded it; presses inside the family and its anchors never get here. + // The input hook recorded the press (and removed a primary one); presses inside the family and its anchors never + // get here. if dismiss.outside == Outside::Absorb { if overlay::absorbed_press(ctx).is_some() { return Some(CloseReason::Outside); diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 780671b60d..9dda859138 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -22,7 +22,8 @@ pub enum Outside { Close, /// Nothing. Keep, - /// Closes the layer and the press reaches nothing below. + /// Closes the layer. A primary press reaches nothing below; a secondary or middle press goes on to the widget + /// below, so a right-click elsewhere closes a menu and opens the menu there. Absorb, } @@ -226,7 +227,7 @@ impl Overlay { overlay } - /// A menu: a popup the arrow keys move through. A press outside closes it and goes no further. + /// A menu: a popup the arrow keys move through. A press outside closes it, and a primary one goes no further. pub fn menu() -> Overlay { let mut overlay = Overlay::base(Rank::Popup, Overlay::below(), OverlayFit::Content, OwnerClass::Menu, FocusPolicy::MENU); overlay.dismiss = Dismiss::new().outside(Outside::Absorb); diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index bf59ec4053..768aec8334 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -668,7 +668,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) { PerViewport::::with(ctx, viewport, |record| record.held.hold_ahead(later)); } Arrived::into_input(events, input); - // H3b: a press outside the top menu family goes no further than the menu's dismissal. + // H3b: a press outside the top menu family closes the menu; a primary one goes no further than its dismissal. let absorbed = overlay::absorb_presses(ctx, input); // H4: release after an OS resize. let released = windows::input_hook(ctx, input); diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index a3af205bb7..5d413153a9 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -148,7 +148,7 @@ pub struct OpenEntry { pub(crate) cover: Option, /// The layer has a focus scope. pub(crate) scoped: bool, - /// A press outside its family closes it and goes no further. + /// A press outside its family closes it, and a primary one goes no further. pub(crate) absorbs: bool, /// The entry is an OS window of the integration: it takes its place in the stack's order and facts, and no egui /// layer is shown for it. @@ -275,7 +275,7 @@ pub(crate) struct Persist { /// The screen rects a press may land in without closing the top menu family: the family and its anchors. `None` /// when the top layer does not absorb outside presses. absorb_zone: Option>, - /// An outside press the input hook removed for the running pass. + /// An outside press the input hook recorded for the running pass (and removed, for a primary one). outside_press: Option, /// The top live modal layer of the last finished pass in this viewport. top_modal: Option, @@ -664,18 +664,19 @@ pub(crate) fn closed_by_activation(ctx: &Context, id: Id) -> bool { with_pass(ctx, |pass| pass.activated.iter().any(|(component, closes)| closes.contains(&id) && !pass.claimed.contains(component))) } -/// The input hook: removes the primary presses that land outside the top menu family, its anchors and its parents, -/// so nothing below the menu sees them (`Outside::Absorb`), and keeps the first one for the layers' dismissal. -/// Returns whether it removed one. +/// The input hook: keeps the first press of any button that lands outside the top menu family, its anchors and its +/// parents for the layers' dismissal, and removes the primary ones, so nothing below the menu sees them +/// (`Outside::Absorb`). A secondary or middle press goes on to what it lands on: a right-click on another part closes +/// the menu and opens that part's menu. Returns whether it removed one. pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::input::RawInput) -> bool { let zone = with_persist(ctx, input.viewport_id, |persist| persist.absorb_zone.clone()); let Some(zone) = zone else { return false }; let before = input.events.len(); let mut first = None; input.events.retain(|event| match event { - egui::Event::PointerButton { pos, pressed: true, .. } if !zone.iter().any(|rect| rect.contains(*pos)) => { + egui::Event::PointerButton { pos, button, pressed: true, .. } if !zone.iter().any(|rect| rect.contains(*pos)) => { first.get_or_insert(*pos); - false + *button != egui::PointerButton::Primary } _ => true, }); @@ -685,7 +686,7 @@ pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::in input.events.len() != before } -/// The outside press the input hook removed for the running pass. A tracked input (`Input::Press`). +/// The outside press the input hook recorded for the running pass. A tracked input (`Input::Press`). pub(crate) fn absorbed_press(ctx: &Context) -> Option { crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); absorbed_press_raw(ctx) diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index bf403901ea..6938d0fcb1 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -244,7 +244,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { if events { inputs::bump(ctx, Input::Pointer); } - // A press or release, or an outside press the layer stack's input hook took before egui saw it. + // A press or release, or an outside press the layer stack's input hook recorded (and took, for a primary one). if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() { inputs::bump(ctx, Input::Press); } diff --git a/crates/ui-widgets/src/menu/popup.rs b/crates/ui-widgets/src/menu/popup.rs index 3e27879c35..5eedf03e3c 100644 --- a/crates/ui-widgets/src/menu/popup.rs +++ b/crates/ui-widgets/src/menu/popup.rs @@ -85,8 +85,8 @@ impl Outcome for MenuPick { } } -/// The layer of a menu, or of a submenu: a press outside closes it and reaches nothing below, and running a row -/// closes the chain. +/// The layer of a menu, or of a submenu: a press outside closes it, a primary one reaches nothing below, and running a +/// row closes the chain. #[doc(hidden)] pub fn layer(submenu: bool) -> Overlay { let base = if submenu { Overlay::submenu() } else { Overlay::menu() }; diff --git a/docs/contract-api.md b/docs/contract-api.md index 34609bca38..4c32fc33f8 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2361,7 +2361,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. + - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it, and a primary one goes no further. - `pub fn submenu() -> Overlay`. A submenu: beside its parent entry, opening upward from a low entry when it fits there and not below. - `pub fn tooltip() -> Overlay`. A tooltip: below the control, no focus, never takes input. - `pub fn dialog() -> Overlay`. A dialog: modal with no backdrop (the window behind stays at true contrast), floating, movable and resizable. @@ -2675,7 +2675,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. + - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it, and a primary one goes no further. - `pub fn submenu() -> Overlay`. A submenu: beside its parent entry, opening upward from a low entry when it fits there and not below. - `pub fn tooltip() -> Overlay`. A tooltip: below the control, no focus, never takes input. - `pub fn dialog() -> Overlay`. A dialog: modal with no backdrop (the window behind stays at true contrast), floating, movable and resizable. diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 95238f40c4..85623c5748 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -164,7 +164,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. ` | Zoom keys | egui's keyboard zoom is off. The interface scale is `RootEnv::scale`. | | Quit shortcuts | egui's quit shortcuts are cleared. Quit goes through the close path. | | Close path | The runtime's window host owns the root window's close request. `embed::logic` asks the app through its closure, then hands the close to the platform quit where there is one (macOS). | -| Input pacing | One press per pass: extra presses in one frame wait for the next passes. A press outside an open framework menu closes the menu and goes no further. After an OS resize of the window, the held pointer is released. | +| Input pacing | One press per pass: extra presses in one frame wait for the next passes. A press outside an open framework menu closes the menu; a primary press goes no further, and a secondary or middle press reaches what it lands on. After an OS resize of the window, the held pointer is released. | The window's keys are the ones the runtime routes to no component: an Escape or a plain Enter while no framework stop is focused, and the arrows' nudge. `with_window_intents` offers them to its closure while nothing has framework focus. The closure takes what it handles (`Intents::take(Intent::Cancel)`; `Intent` and the other types `Intents` reads are in `ui::runtime::keys`) and returns whether it took anything; the rest stays for later readers. A framework scope that ran earlier in the pass takes them first (an open dialog takes the Escape that closes it), so the app reads them last in its UI to see what no component took. App code that read `Key::Escape`, `Key::Tab`, F6 or F10 from egui while none of its own widgets had focus reads these intents and `FrameOutput::chrome_toggles` instead; its own focused widgets and popups keep reading Tab and Escape from egui. From cb414bef729171d9e854d94dc21d31d9bf96b33a Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 15:42:43 +0100 Subject: [PATCH 03/37] AppCatalog::shown_only: chords the app dispatches itself An app whose own keymap dispatches some of its catalog commands' keys (a tool rail's tools) had to clear their default chords before handing them to the board, so the rail's buttons and tooltips showed no shortcut. shown_only(ids) keeps the chords in the board's keymap, so surfaces resolve and show them, while the key stage, runs_now and the declined/dimmed report pass over those commands as if unbound: the press fires nothing on the board and stays in egui's input for the app. Trial: a_shown_only_chord_shows_on_its_button_and_its_press_stays_in_the_input_unfired. --- .../ui-contract/src/runtime/commands/board.rs | 27 ++++++++++++---- .../ui-contract/src/runtime/commands/mod.rs | 26 +++++++++++++-- .../ui-shell/tests/it/commands/app_catalog.rs | 32 +++++++++++++++++++ docs/contract-api.md | 1 + 4 files changed, 78 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index c06b9a8686..bb65aa40bb 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -666,6 +666,12 @@ impl Board { self.instances.get(id).is_some_and(|i| self.live(ctx, i)) } + /// Whether the app dispatches the keys of `command` itself ([`AppCatalog::shown_only`]): the board shows its chord + /// but passes over its bindings when it matches a key. Only a command the linked sets do not define. + fn leaves_key(&self, command: &CommandRef) -> bool { + self.app.as_ref().is_some_and(|app| app.is_shown_only(command)) && self.registry.get(&command.id).is_none() + } + /// The definition of `command`: the linked sets' by id, else the frame's app catalog's. fn def(&self, command: &CommandRef) -> Option<&CommandDef> { self.registry.get(&command.id).or_else(|| self.app.as_ref()?.get(command)) @@ -1289,7 +1295,7 @@ pub(crate) fn runs_now(ctx: &Context, viewport: ViewportId, chord: &Chord) -> bo board.key_scopes(&chain) }); let Some(keys) = keys else { return false }; - let enabled = |command: &CommandRef| resolve_from(ctx, command, None).0.enabled; + let enabled = |command: &CommandRef| !with(ctx, |board| board.leaves_key(command)) && resolve_from(ctx, command, None).0.enabled; keys.matching(false, |active, outer| !matches!(keys.keymap.lookup_where(chord, false, active, outer, &enabled), craft_keymap::Lookup::None)) } @@ -2208,8 +2214,14 @@ pub(crate) fn begin(ctx: &Context) { }; // A binding whose command is disabled where the press lands (a window command with no floating window, a canvas's // view command it does not offer) is passed over: the press runs the next binding of its chord, in an outer scope, - // or of its next chord candidate, as if the disabled one were unbound. + // or of its next chord candidate, as if the disabled one were unbound. So is a binding of a command whose keys the + // app dispatches itself (`AppCatalog::shown_only`), whatever its state. + let leaves_key = |command: &CommandRef| with(ctx, |board| board.leaves_key(command)); + let board_runs = |hit: &Hit| !leaves_key(&hit.command); let enabled = |command: &CommandRef| { + if leaves_key(command) { + return false; + } let (_, instance) = with(ctx, |board| board.target_of(ctx, command, &board.here)); resolve_in(ctx, command, instance, Reach::Focus, None, Reads::default()).0.enabled }; @@ -2247,7 +2259,9 @@ pub(crate) fn begin(ctx: &Context) { // completes no double press and settles no wait, and the key a momentary or tool command holds stays // held by its press. The key of a wait or of a hold binding repeats nothing. let typing = typing_at(shortcut); - if wait.as_ref().is_some_and(|wait| Some(wait.key) == key) || keys.hold(&shortcuts.layout, &shortcut.input, typing).is_some() { + if wait.as_ref().is_some_and(|wait| Some(wait.key) == key) + || keys.hold(&shortcuts.layout, &shortcut.input, typing).is_some_and(|hold| board_runs(&hold)) + { continue; } let tap = keys.press(&shortcuts.layout, &shortcut.input, typing, Some((&mut matcher, time, true, &enabled))); @@ -2260,15 +2274,16 @@ pub(crate) fn begin(ctx: &Context) { let typing = typing_at(shortcut); let hold = key .filter(|_| !typing && !modal_at_start) - .and_then(|key| keys.hold(&shortcuts.layout, &shortcut.input, typing).map(|hold| (key, hold))); + .and_then(|key| keys.hold(&shortcuts.layout, &shortcut.input, typing).filter(board_runs).map(|hold| (key, hold))); let tap = keys.press(&shortcuts.layout, &shortcut.input, typing, Some((&mut matcher, time, false, &enabled))); match (hold, tap) { (Some((key, hold)), tap) => wait = Some(HoldWait { key, hold, since: time, delay, tap, viewport }), (None, Some(tap)) => fired.extend(press(tap, key, time, Some(shortcut.place))), // A chord that binds only disabled commands runs nothing; the app hears of the first one, to say - // why it did not run as a menu row's hint does, and may receive it as declined. + // why it did not run as a menu row's hint does, and may receive it as declined. A chord the app + // dispatches itself is the app's: it hears nothing of it here. (None, None) => { - if let Some(hit) = keys.press(&shortcuts.layout, &shortcut.input, typing, None) { + if let Some(hit) = keys.press(&shortcuts.layout, &shortcut.input, typing, None).filter(board_runs) { let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here)); let resolved = resolve_once(ctx, &hit.command, instance, Reach::Focus, None); decline(ctx, hit.clone(), app, &resolved, time); diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 419f64f0eb..86fcf2666f 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -56,7 +56,7 @@ use craft_behavior::edit_history::Step; use craft_keymap::{Chord, Overrides}; use egui::{Context, Id, ViewportId}; use std::borrow::Cow; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; /// Commands an app defines at run time (plug-ins, its tool list), all in the app scope ([`Scope::app`]). They join @@ -71,6 +71,8 @@ pub struct AppCatalog { replaced: Arc<[(String, Vec)]>, /// Which chords fire while a text component has the keyboard (`typing_rule`); `None` keeps the keymap's default. typing: Option, + /// The ids of the catalog's commands whose keys the app dispatches itself (`shown_only`). + shown_only: Arc>, } impl AppCatalog { @@ -84,7 +86,7 @@ impl AppCatalog { } registry::index_id(&mut index, &def.command.key_text(), at)?; } - Ok(AppCatalog { defs: defs.into(), index: Arc::new(index), generation, replaced: Arc::from([]), typing: None }) + Ok(AppCatalog { defs: defs.into(), index: Arc::new(index), generation, replaced: Arc::from([]), typing: None, shown_only: Arc::default() }) } /// Gives the linked set's command `id` the default chords `bindings` in place of the set's own; an empty list drops @@ -111,6 +113,26 @@ impl AppCatalog { self } + /// Makes the chords of the catalog's commands `ids` shown only: the app dispatches their keys with a keymap of its + /// own. Menu rows, tooltips and buttons still show each command's chord (its bindings, under the overrides, as + /// [`ResolvedCommand::chord`] reads them), but the board passes over the command when it matches a key, as if the + /// command had no binding, so the press fires nothing on the board and stays in egui's input for the app. The + /// command still fires from a menu row, a button, the palette or automation. Later calls add to the earlier ones. + /// An id the linked sets define stays theirs and is ignored here. The board reads the ids every frame, so a change + /// needs no new [`generation`](Self::generation). + #[must_use] + pub fn shown_only>(mut self, ids: impl IntoIterator) -> Self { + let mut shown_only = (*self.shown_only).clone(); + shown_only.extend(ids.into_iter().map(Into::into)); + self.shown_only = Arc::new(shown_only); + self + } + + /// Whether the app dispatches the keys of `command` itself ([`shown_only`](Self::shown_only)). + pub(crate) fn is_shown_only(&self, command: &CommandRef) -> bool { + self.shown_only.contains(command.id.as_str()) + } + /// The default chords the app gives the linked set's command `id`, when it replaced them. pub(crate) fn replaced_defaults(&self, id: &str) -> Option<&[Binding]> { self.replaced.iter().find(|(at, _)| at == id).map(|(_, bindings)| bindings.as_slice()) diff --git a/crates/ui-shell/tests/it/commands/app_catalog.rs b/crates/ui-shell/tests/it/commands/app_catalog.rs index 8b4b271b4c..47055fb799 100644 --- a/crates/ui-shell/tests/it/commands/app_catalog.rs +++ b/crates/ui-shell/tests/it/commands/app_catalog.rs @@ -2,6 +2,7 @@ //! rules every app command follows, and a frame builds a keymap only for a catalog generation it has not built. // The catalog is given through `Frames::commands`, which keeps it for every later frame. +use craft_ui::buttons::{Button, ButtonChord}; use craft_ui::contract::{Bind, Props as _, Show as _, Tracked}; use craft_ui::runtime::commands::{ AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, CommandStates, EditCommands, FirePhase, Scope, @@ -99,6 +100,37 @@ fn an_app_catalog_command_fires_by_its_chord_and_a_focused_text_field_keeps_a_ty assert_eq!(*name.borrow(), "q", "the focused field types the letter"); } +/// A catalog command whose chord is shown only (`AppCatalog::shown_only`), as a tool whose key the app's own keymap +/// dispatches: a button bound to it shows the chord, and a press of the chord fires nothing on the board and stays in +/// egui's input, where the app reads it. +#[trial] +fn a_shown_only_chord_shows_on_its_button_and_its_press_stays_in_the_input_unfired() { + let key_in_input = Cell::new(false); + let mut show = |ui: &mut Ui| { + AppShell::new(WindowKey::main()) + .body(|ui, _, _| { + let _ = Button::command(CommandRef::new(BRUSH)).chord(ButtonChord::Trailing).show(ui); + if ui.input(|input| input.key_pressed(Key::J)) { + key_in_input.set(true); + } + }) + .show(ui, &mut ()); + }; + let brush = def(BRUSH, "Brush", "J").with_kind(CommandKind::Tool { group: None }); + let mut frames = Frames::new(); + frames.commands(CommandInput::new().catalog(AppCatalog::new(vec![brush], 1).expect("the trial's catalog is valid").shown_only([BRUSH]))); + frames.idle(3, &mut show); + let painted: String = frames.texts().iter().map(|text| text.text.as_str()).collect(); + let (label, chord) = (painted.find("Brush"), painted.rfind('J')); + assert!(label.is_some() && label < chord, "the button shows the shown-only chord after its label: {painted:?}"); + + let _ = fired(&frames); + frames.frame(vec![key_press(Key::J, Modifiers::NONE)], &mut show); + assert!(key_in_input.get(), "the press stays in egui's input for the app's keymap"); + frames.frame(vec![key_release(Key::J, Modifiers::NONE)], &mut show); + assert!(fired(&frames).is_empty(), "the board fires nothing for a shown-only chord"); +} + /// A key's press and its release fire with the input times they arrived at, whichever frame runs them: a hold is /// read from the key's own times. Keys behind a pointer press wait for the next frame (one press per pass) and keep /// the time they arrived at. diff --git a/docs/contract-api.md b/docs/contract-api.md index 30983c458b..eb535c504b 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -3521,6 +3521,7 @@ The command board: the registry and typed sets, per-frame state, the queue, firi - `pub fn new(defs: Vec, generation: u64) -> Result`. A catalog of `defs`; `generation` changes when the app's rows do. Refuses two defs with one id (`Duplicate`) and a - `pub fn replace_defaults(mut self, id: impl Into, bindings: Vec) -> Self`. Gives the linked set's command `id` the default chords `bindings` in place of the set's own; an empty list drops - `pub fn typing_rule(mut self, rule: TypingRule) -> Self`. Sets which chords fire while a text component has the keyboard. The keymap's default, + - `pub fn shown_only>(mut self, ids: impl IntoIterator) -> Self`. Makes the chords of the catalog's commands `ids` shown only: the app dispatches their keys with a keymap of its - `pub fn generation(&self) -> u64`. The app's version of the catalog. The board rebuilds the keymap when it differs from the last frame's, and never - `craft_ui::runtime::commands::CommandGate`: `pub struct CommandGate`. The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an - `pub fn new(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self`. A gate that lets through the commands `allows` accepts under `props`. From 9a301153dc76ae84bd569f25b558b1dbdf52a778 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 15:55:34 +0100 Subject: [PATCH 04/37] ui-contract: a pointer activation carries the modifiers of the release that clicked (PointerFrame::pick_mods), not the ones held at the end of the pass, so an Alt-click whose Alt goes up in the same frame is still an Alt-click and a flyout button steps its tool. A collection's release-time picks, thumbnail clicks and command clicks read the same modifiers. Trials in latch and rails --- crates/ui-contract/src/contract/cx/context.rs | 3 ++- .../ui-contract/src/contract/items/press.rs | 15 +++++++++------ crates/ui-contract/src/contract/run.rs | 6 ++++-- crates/ui-contract/tests/it/runtime/latch.rs | 17 +++++++++++++++++ crates/ui-panels/tests/it/rails/mod.rs | 19 +++++++++++++++++++ 5 files changed, 51 insertions(+), 9 deletions(-) diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 4446f4c658..2226b50f91 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -27,7 +27,8 @@ use std::sync::Arc; pub struct Activation { /// By `Intent::Activate` (Enter, Space or an AccessKit click) rather than a primary click. pub by_key: bool, - /// The modifiers held at the activation: with the click for a pointer activation, in the pass for a key or AccessKit one. + /// The modifiers held at the activation: those of the click's release, latched ones included, for a pointer + /// activation; those held in the pass for a key or AccessKit one. pub mods: craft_keymap::Mods, } diff --git a/crates/ui-contract/src/contract/items/press.rs b/crates/ui-contract/src/contract/items/press.rs index cf6819543d..e8df83a151 100644 --- a/crates/ui-contract/src/contract/items/press.rs +++ b/crates/ui-contract/src/contract/items/press.rs @@ -58,6 +58,9 @@ impl ItemsHooks<'_, '_, C> { if layout.mirrors() && rtl { flow.to_physical(Rect::from_min_size(at, Vec2::ZERO)).min } else { at } }; let mods_now = crate::runtime::pointer::frame_raw(&ctx).mods; + // What a click decides and reports reads the modifiers of its release, which a quick click can let go of in the + // same frame. + let click_mods = crate::runtime::pointer::frame_raw(&ctx).pick_mods; // A click on a row the collection does not take (a caption, a disabled row) is no pick: the layers around the // collection (a dropdown's list) stay open. if cx.core.activation.as_ref().is_some_and(|activation| !activation.by_key) @@ -218,7 +221,7 @@ impl ItemsHooks<'_, '_, C> { && let Some(at) = layout.hit(local(start.origin), offset).filter(|&at| self.source.enabled(at) && layout.shown(at)) { // A modified click is a command on the thumbnail (load as selection, and so on), not a pick. - let mods = crate::runtime::pointer::frame_raw(&ctx).mods; + let mods = click_mods; if !(mods.shift || mods.cmd || mods.alt) { if !self.keeps_pick(at, start.clicks) { self.click_pick(comp, at, false, false, mods); @@ -233,7 +236,7 @@ impl ItemsHooks<'_, '_, C> { && click && let Some(at) = self.index_of(&key) { - self.click_pick(comp, at, false, false, mods_now); + self.click_pick(comp, at, false, false, click_mods); } if click && props.menu_on_click @@ -261,7 +264,7 @@ impl ItemsHooks<'_, '_, C> { && click && self.index_of(&key).is_some() { - self.events.push(CollectionEvent::CommandClick { key, mods: mods_now }); + self.events.push(CollectionEvent::CommandClick { key, mods: click_mods }); } // The press machine makes a middle release a click only for a collection that senses `MIDDLE_CLICK`. if click @@ -284,9 +287,9 @@ impl ItemsHooks<'_, '_, C> { && let Some(at) = self.index_of(&key) { if Self::select_mode(comp) == SelectMode::Single { - self.change_by(SelectionChange::Clear, PickBy::Pointer(mods_now)); + self.change_by(SelectionChange::Clear, PickBy::Pointer(click_mods)); } else { - self.click_pick(comp, at, false, false, mods_now); + self.click_pick(comp, at, false, false, click_mods); } } } @@ -328,7 +331,7 @@ impl ItemsHooks<'_, '_, C> { let column = if Self::selects_cells(comp) { layout.column_at(local(pos), offset) } else { None }; match column { Some(column) => self.cell_press(comp, layout, at, column, false, false), - None => self.pick_by(comp, at, false, false, PickBy::Pointer(released.mods)), + None => self.pick_by(comp, at, false, false, PickBy::Pointer(released.pick_mods)), } } self.move_lead(at, LeadSource::Pointer); diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index c87b86cf68..f62b081ec5 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -783,7 +783,9 @@ fn declared_with(parts: &PartsStep, has: impl Fn(&super::cx::PartExtras) -> bool } /// The activation this pass: none for a component that takes none; a key or AccessKit activation of a member -/// (`keyed`); else the click, or the release of a press that opened a popup and ended over this row. +/// (`keyed`); else the click, or the release of a press that opened a popup and ended over this row. A pointer +/// activation carries the modifiers of the release that made it (`PointerFrame::pick_mods`), not the ones still held +/// when the pass runs: an Alt-click whose Alt goes up in the same frame is an Alt-click. fn activation_of(ctx: &Context, ui: &Ui, rect: Rect, resolved: &Resolved<'_>, keyed: bool, root_sense: Sense, clicked: bool) -> Option { if !steps::takes_activation(resolved) { return None; @@ -799,7 +801,7 @@ fn activation_of(ctx: &Context, ui: &Ui, rect: Rect, resolved: &Resolved<'_>, ke ); (clicked || released).then(|| Activation { by_key: false, - mods: crate::runtime::pointer::with_frame(ctx, |frame, _| frame.map_or(craft_keymap::Mods::NONE, |frame| frame.mods)), + mods: crate::runtime::pointer::with_frame(ctx, |frame, _| frame.map_or(craft_keymap::Mods::NONE, |frame| frame.pick_mods)), }) } diff --git a/crates/ui-contract/tests/it/runtime/latch.rs b/crates/ui-contract/tests/it/runtime/latch.rs index 978a8723b8..d7fcec91df 100644 --- a/crates/ui-contract/tests/it/runtime/latch.rs +++ b/crates/ui-contract/tests/it/runtime/latch.rs @@ -156,3 +156,20 @@ fn a_latch_change_adds_no_pass() { assert_eq!(held, steady); assert_eq!(released, steady, "releasing runs no extra pass"); } + +#[trial] +fn a_click_reads_the_modifiers_of_its_release() { + let rig = Rig::new(); + let mut frames = Frames::new(); + frames.idle(3, |ui| rig.show(ui)); + let at = rig.at(); + frames.frame(vec![moved(at)], |ui| rig.show(ui)); + rig.clear(); + // A quick Alt-click: the press and the release carry Alt, which is up again when the frame runs. + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::ALT }; + frames.frame(vec![button(true), button(false)], |ui| rig.show(ui)); + frames.idle(1, |ui| rig.show(ui)); + let log = rig.log.borrow(); + assert_eq!(log.activations, [Mods::ALT], "the activation carries the release's Alt, not the frame's held modifiers"); + assert!(log.pointer.iter().all(|mods| !mods.alt), "nothing is held when the frames run: {:?}", log.pointer); +} diff --git a/crates/ui-panels/tests/it/rails/mod.rs b/crates/ui-panels/tests/it/rails/mod.rs index 24d4dcca32..a912f0c625 100644 --- a/crates/ui-panels/tests/it/rails/mod.rs +++ b/crates/ui-panels/tests/it/rails/mod.rs @@ -224,6 +224,25 @@ fn alt_click_steps_a_slot_and_a_modified_click_is_never_a_double_click() { assert_eq!(rig.doubles.get(), 1, "two plain clicks are a double click"); } +/// The primary button going down or up at `pos` with `modifiers` in the event itself. +fn primary_with(pos: Pos2, pressed: bool, modifiers: Modifiers) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } +} + +/// A quick Alt-click whose Alt is up again before the frame ends still steps the slot: the click reads the modifiers +/// of its release, not the ones held when the frame runs. +#[trial] +fn an_alt_click_whose_alt_goes_up_in_the_same_frame_steps_the_slot() { + let mut rig = rig(true); + let at = button(&rig).center(); + // Nothing is held when the frame runs; the press and the release carry Alt. + rig.fixture.hold(Modifiers::NONE); + rig.fixture.frame(vec![moved(at), primary_with(at, true, Modifiers::ALT), primary_with(at, false, Modifiers::ALT)]); + rig.fixture.idle(2); + assert_eq!(*rig.selected.borrow(), [REDO], "the Alt-click picks the next tool, not the shown one"); + assert!(rig.fixture.by_role(Role::MENU).is_empty(), "an Alt-click opens no flyout"); +} + /// The name of the flyout's tear-off bar. const TEAR_OFF: &str = "Tear Off Group"; From 91c5789e7d8022e9b423f62da37fff51fca4eddd Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 21:45:21 +0100 Subject: [PATCH 05/37] Scroll a list row into view on AccessKit Scroll Into View A collection took a Scroll Into View aimed at a row's node and dropped it, and a part's request reached no scroll owner, so a screen reader could not bring a row or a part into view. The collection now reveals the row as a lead move does, without moving the lead or focus, and passes the row's visible piece on to the scroll owner around it; a part's request reveals the part's rect in its component's scroll owner, as focus on the part does. --- crates/ui-contract/src/contract/items.rs | 4 ++ .../ui-contract/src/contract/items/access.rs | 10 ++++- .../ui-contract/src/contract/items/hooks.rs | 3 ++ .../src/contract/steps/scroll_owner.rs | 28 +++++++++++--- .../tests/it/access/scroll_into_view.rs | 38 ++++++++++++++++++- 5 files changed, 74 insertions(+), 9 deletions(-) diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index 8ce1170bda..559b891a24 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -267,6 +267,9 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { page_reveal: Option, /// The row this pass scrolls into view, placed before the rows are built (`place_reveal`). revealing: Option, + /// The row an AccessKit Scroll Into View brings into the collection's own view this pass: once placed, its visible + /// piece goes to the scroll owner around the collection (`content`), as a scroll body passes a reveal on. + reveal_around: Option, /// The row the collection's own press is held on this pass, and where on it. pressed: Option<(usize, crate::contract::collection::RowPressed)>, /// The rows above and below the edge-press band declared this pass. @@ -331,6 +334,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { drags: Drags::default(), page_reveal: None, revealing: None, + reveal_around: None, lead_at_read: None, renaming_at_read: None, pressed: None, diff --git a/crates/ui-contract/src/contract/items/access.rs b/crates/ui-contract/src/contract/items/access.rs index ea461da220..adcaea3132 100644 --- a/crates/ui-contract/src/contract/items/access.rs +++ b/crates/ui-contract/src/contract/items/access.rs @@ -75,7 +75,9 @@ impl ItemsHooks<'_, '_, C> { /// AccessKit requests on an item row's node or on a section row's collection node (`report_section_node`): Focus /// moves the lead to the row and key focus to the collection; Click also picks an item and activates it when the - /// collection activates on click, or activates a section; Expand and Collapse open and close rows with children. + /// collection activates on click, or activates a section; Expand and Collapse open and close rows with children; + /// Scroll Into View brings the row into view as a lead move does, moving neither the lead nor focus, and in a + /// collection with its own scroll the scroll owner around the collection then shows the row's visible piece. pub(super) fn node_by_access( &mut self, comp: &C, @@ -123,6 +125,12 @@ impl ItemsHooks<'_, '_, C> { } } } + AccessAction::ScrollIntoView => { + self.reveal_with(layout, at); + if self.scrolls { + self.reveal_around = Some(at); + } + } AccessAction::Expand | AccessAction::Collapse => { let open = request.action == AccessAction::Expand; if self.source.has_children(at) && self.source.open(at) != open { diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index f4166d548c..f05249aeee 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -379,6 +379,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { crate::runtime::egui::repaint::request(&ctx); } let offset = ScrollPos { x: self.offset_x, y: self.offset }; + if let Some(at) = self.reveal_around.take().filter(|&at| layout.shown(at)) { + cx.core.reveal = Some(self.screen(&layout, rect, at, offset, rtl).intersect(rect)); + } Arc::make_mut(&mut layout).set_view(rect.size(), offset); if self.scrolls { note_scroll_regions(ui, rect, self.content, offset, rtl, self.header.view()); diff --git a/crates/ui-contract/src/contract/steps/scroll_owner.rs b/crates/ui-contract/src/contract/steps/scroll_owner.rs index edd8dfe9fb..c652de460d 100644 --- a/crates/ui-contract/src/contract/steps/scroll_owner.rs +++ b/crates/ui-contract/src/contract/steps/scroll_owner.rs @@ -7,8 +7,9 @@ use craft_behavior::{MoveMods, NavMove}; use egui::{Context, Id, Rect, Vec2}; /// What the component left untaken that a scroll region serves: page and end moves go to the innermost scroll -/// owner around the component, and an AccessKit request to show the component reveals its rect there. Both are -/// applied at the owner's step 4 of the next pass. +/// owner around the component, and an AccessKit request to show the component, or one of its parts, reveals the +/// component's rect, or the part's, there, as focus on it does. Both are applied at the owner's step 4 of the next +/// pass. pub(super) fn route_to_scroll_owner(core: &mut CxCore<'_>) { let scrolls = |mv: NavMove, _| matches!(mv, NavMove::PageUp | NavMove::PageDown | NavMove::Start | NavMove::End); let mut moves = Vec::new(); @@ -24,14 +25,29 @@ pub(super) fn route_to_scroll_owner(core: &mut CxCore<'_>) { while let Some(mv) = core.intents.take_move_where(scrolls) { moves.push(mv); } - let reveal = core.intents.take_scroll_access(true).is_some(); - if moves.is_empty() && !reveal { + let reveal = match core.intents.take_scroll_access(true) { + Some(_) => Some(core.rect), + None => { + // A part's Scroll Into View: a part the component declared this pass shows its own rect. + let results = &core.results; + let shows_part = |request: &craft_behavior::AccessRequest| { + request.action == craft_behavior::AccessAction::ScrollIntoView + && request.target.is_some_and(|part| results.contains_key(&(part.key, part.index))) + }; + core.intents + .take_access_where(shows_part) + .and_then(|request| request.target) + .and_then(|part| results.get(&(part.key, part.index))) + .map(|result| result.rect) + } + }; + if moves.is_empty() && reveal.is_none() { return; } let Some(owner) = core.env.scroll_owner() else { return }; pass_state::with::(&core.ctx, |queue| queue.0.extend(moves.into_iter().map(|(mv, mods)| (owner, mv, mods, false)))); - if reveal { - pass_state::with::(&core.ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(core.rect) })); + if let Some(rect) = reveal { + pass_state::with::(&core.ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(rect) })); } repaint::request(&core.ctx); } diff --git a/crates/ui-widgets/tests/it/access/scroll_into_view.rs b/crates/ui-widgets/tests/it/access/scroll_into_view.rs index d55b6c2092..07052a5623 100644 --- a/crates/ui-widgets/tests/it/access/scroll_into_view.rs +++ b/crates/ui-widgets/tests/it/access/scroll_into_view.rs @@ -1,10 +1,12 @@ //! A screen reader's Scroll Into View shows its node and leaves keyboard focus where it was; a Focus request moves it. +use craft_behavior::{Selection, keyed}; use craft_ui::buttons::Button; -use craft_ui::contract::Show as _; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowCollection as _}; +use craft_ui::list::{List, ListRow}; use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::{Fixture, trial}; -use egui::{Key, Modifiers}; +use egui::{Id, Key, Modifiers, Rect, Vec2}; #[trial] fn scroll_into_view_moves_no_focus() { @@ -22,3 +24,35 @@ fn scroll_into_view_moves_no_focus() { fixture.access(AccessActionKind::Focus, &second).settle(); assert_ne!(fixture.focused_stop(), focused, "a Focus request moves it"); } + +/// Whether `view` shows all of `row`: a row out of view may report bounds cut to nothing at the view's edge. +fn shows(view: Rect, row: Rect) -> bool { + row.height() > 1.0 && view.expand(0.5).contains_rect(row) +} + +/// A screen reader's Scroll Into View on a list row scrolls the list's own body until the row shows, as the old egui +/// list's scroll area did for any widget in it; on a row already in view it moves nothing. Row 150 is the selection's +/// anchor, so the list builds it, and reports its node, while it is scrolled out. +#[trial] +fn scroll_into_view_on_a_list_row_scrolls_the_list_to_it() { + let list_id = Id::new("rows"); + let mut fixture = Fixture::new(move |ui| { + let keys: Vec = (0..200).collect(); + let source = keyed(&keys, |key: &usize| *key); + let list = List::new("Rows").id(list_id).selection(Bind::given(Selection::single(150_usize))); + list.show_items(ui, &source, &mut |key, _| ListRow::new(format!("Row {key}"))); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + let view = fixture.node_of(list_id).expect("the list's node").rect; + let row = fixture.by_label("Row 150").expect("row 150's node, kept as the anchor"); + assert!(!shows(view, row.rect), "row 150 starts out of view: {:?} in {view:?}", row.rect); + fixture.access(AccessActionKind::ScrollIntoView, &row).settle(); + let shown = fixture.by_label("Row 150").expect("row 150's node").rect; + assert!(shows(view, shown), "Scroll Into View brought row 150 into the list's view: {shown:?} in {view:?}"); + let near = fixture.by_label("Row 148").expect("row 148, in view beside row 150"); + assert!(shows(view, near.rect), "row 148 shows: {:?} in {view:?}", near.rect); + fixture.access(AccessActionKind::ScrollIntoView, &near).settle(); + let after = fixture.by_label("Row 150").expect("row 150's node").rect; + assert!((after.min - shown.min).length() <= 0.5, "Scroll Into View on a row in view moved nothing: {after:?}, was {shown:?}"); +} From bfd3d037c2b3b49e637a04ba28a48061dc6a8bfa Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 21:48:39 +0100 Subject: [PATCH 06/37] Name a face's sub-node by the name its access declares paint_face named a part's sub-node by the face's label (the full text when elided) and dropped the name the face's own access declared. A Kbd built with Kbd::command has an empty label, so its label becomes the bound command's: a menu row's shortcut part and the command-search opener's chord part were named by the command's label, and no node carried the chord text. A face that declares Name::Text or Name::Joined now names its part's sub-node with that text, as it would name its own node; a face that declares none keeps the label. Name::own_text gives the text both paths read. --- crates/ui-contract/src/contract/run/typed.rs | 8 ++++++- crates/ui-contract/src/primitives/record.rs | 3 ++- crates/ui-contract/src/runtime/access.rs | 12 ++++++++++ crates/ui-contract/src/runtime/access/emit.rs | 3 +-- crates/ui-widgets/tests/it/buttons.rs | 21 +++++++++++++++++- crates/ui-widgets/tests/it/menu/rows.rs | 22 ++++++++++++++++++- 6 files changed, 63 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index c3e9e325e1..904acb4390 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -772,12 +772,18 @@ pub(crate) fn paint_face( if !source.reported { return (baseline, None); } - let name = cx.core.paint.borrow().elided.clone().unwrap_or_else(|| step1.label.as_str().to_owned()); // The face's own `access` adds its facts; the composite's step 16 fills the part's sub-node from the record. let mut access = Access::default(); #[cfg(feature = "testing")] crate::runtime::measure::count_access_build(&ctx); face.access(&mut access, &cx); + // A face that names itself (a `Kbd` by its chord spoken) names its part's sub-node so, as it would its own node; + // a face that declares no text is named by its label, the full text when elided. + let name = access + .name + .own_text() + .filter(|text| !text.is_empty()) + .unwrap_or_else(|| cx.core.paint.borrow().elided.clone().unwrap_or_else(|| step1.label.as_str().to_owned())); let record = FaceRecord { part, name, diff --git a/crates/ui-contract/src/primitives/record.rs b/crates/ui-contract/src/primitives/record.rs index dbba9becea..2a1042e20a 100644 --- a/crates/ui-contract/src/primitives/record.rs +++ b/crates/ui-contract/src/primitives/record.rs @@ -54,7 +54,8 @@ impl std::fmt::Debug for Adopted { pub struct FaceRecord { /// The part the face looks for. pub part: PartRef, - /// The instance's resolved label, the full text when elided. + /// The text the face's `access` named it with (`Name::Text` or `Name::Joined`), else the instance's resolved + /// label, the full text when elided. pub name: String, /// The face's value flags. pub flags: crate::style::Flags, diff --git a/crates/ui-contract/src/runtime/access.rs b/crates/ui-contract/src/runtime/access.rs index 3875e52017..8e19305884 100644 --- a/crates/ui-contract/src/runtime/access.rs +++ b/crates/ui-contract/src/runtime/access.rs @@ -119,6 +119,18 @@ pub enum Name { Decorative, } +impl Name { + /// The text the name gives itself: a `Text`'s, or a `Joined`'s texts joined with a comma. `None` for a name taken + /// from a label or another node, and for no name. + pub(crate) fn own_text(&self) -> Option { + match self { + Name::Text(text) => Some(text.clone()), + Name::Joined(parts) => Some(parts.join(", ")), + Name::FromLabel | Name::LabelledBy(_) | Name::Decorative => None, + } + } +} + /// A numeric value. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index 74bccc7196..bb406f9092 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -108,8 +108,7 @@ struct Named { fn named(name: &Name, label: &str, fallbacks: &[Option<&str>]) -> Named { let (text, labelled_by, hidden) = match name { Name::FromLabel => (label.to_owned(), Vec::new(), false), - Name::Text(text) => (text.clone(), Vec::new(), false), - Name::Joined(parts) => (parts.join(", "), Vec::new(), false), + Name::Text(_) | Name::Joined(_) => (name.own_text().unwrap_or_default(), Vec::new(), false), Name::LabelledBy(id) => (String::new(), vec![*id], false), Name::Decorative => (String::new(), Vec::new(), true), }; diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index 144252af84..d989132514 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -4,10 +4,11 @@ //! icon's place. use craft_behavior::{IconId, PartKey}; +use craft_host::target::Os; use craft_theme::ControlSize; use craft_theme::Variant; use craft_ui::buttons::{ - Arrangement, Button, ButtonChord, ControlPlace, GroupLevel, IconButton, PushButtonLook, SplitButton, SplitMenu, ToggleButton, + Arrangement, Button, ButtonChord, CommandSearch, ControlPlace, GroupLevel, IconButton, PushButtonLook, SplitButton, SplitMenu, ToggleButton, }; use craft_ui::contract::tooltip::DELAY; use craft_ui::contract::{Bind, CommandSet, Entry, Hover, PopupKind, Props as _, Role, Show as _, ShowContainer as _, Trigger}; @@ -841,6 +842,24 @@ fn a_command_button_shows_its_chord_until_the_room_is_short() { assert_eq!(plain_chord, plain_hidden, "a command with no chord shows none"); } +/// The command-search opener's chord part is named by the chord spoken, the name its `Kbd` face gives itself, not by +/// the command's label. +#[trial] +fn a_command_search_chord_part_is_named_by_its_chord_spoken() { + let find = CommandDef::new(CommandRef::new("demo.find"), "Find", Scope::app()) + .with_default(Binding::parse("Cmd+Alt+F9").expect("the trial's chord parses")); + let catalog = AppCatalog::new(vec![find], 1).expect("the trial's catalog is valid"); + let mut fixture = Fixture::new(|ui| { + CommandSearch::new(CommandRef::new("demo.find"), "Search commands").show(ui); + }); + fixture.os(Os::Linux).commands(CommandInput::new().catalog(catalog)); + fixture.settle(); + let opener = fixture.by_label("Search commands").expect("the opener is named by its placeholder"); + let chord = fixture.by_label("Ctrl+Alt+F9").expect("a node is named by the opener's chord spoken"); + assert!(opener.rect.contains(chord.rect.center()), "the chord's node is the opener's chord part: {:?} in {:?}", chord.rect, opener.rect); + assert!(fixture.by_label("Find").is_none(), "no node is named by the command's label"); +} + /// A toggle button says whether it is pressed both ways: on is pressed and off is not pressed, bound to a value or /// given a shared one (a mode of several objects), where a button with no toggle has no pressed state. Guards against /// an off toggle reading as a plain button. diff --git a/crates/ui-widgets/tests/it/menu/rows.rs b/crates/ui-widgets/tests/it/menu/rows.rs index b411d063fa..c315ad342c 100644 --- a/crates/ui-widgets/tests/it/menu/rows.rs +++ b/crates/ui-widgets/tests/it/menu/rows.rs @@ -9,7 +9,7 @@ use craft_ui::contract::{CommandSet, Props as _, Show as _, ShowContainer as _, use craft_ui::list::{CommandHighlight, ThumbAspect}; use craft_ui::menu::{Menu, MenuItem}; use craft_ui::primitives::FacePaint; -use craft_ui::runtime::commands::CommandState; +use craft_ui::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandRef, CommandState, Scope}; use craft_ui::runtime::env::{Scale, with_env}; use craft_ui::testing::{Fixture, Room, pointer, trial}; use egui::Rect; @@ -141,6 +141,26 @@ fn a_caller_shortcut_wins_over_the_bound_commands_chord_and_hide_shortcut_shows_ assert_eq!(listed(&fixture, "Plain"), None, "and lists none"); } +/// A command row's shortcut part is named by its chord spoken, the name its `Kbd` face gives itself, not by the row's +/// command label. +#[trial] +fn a_command_rows_shortcut_part_is_named_by_its_chord_spoken() { + let save = + CommandDef::new(CommandRef::new("demo.save"), "Save", Scope::app()).with_default(Binding::parse("Cmd+S").expect("the trial's chord parses")); + let catalog = AppCatalog::new(vec![save], 1).expect("the trial's catalog is valid"); + let mut fixture = Fixture::new(|ui| { + Menu::inline("m").show(ui, |ui, _| { + MenuItem::command(CommandRef::new("demo.save")).show(ui); + }); + }); + fixture.os(Os::Linux).commands(CommandInput::new().catalog(catalog)); + fixture.settle(); + let row = fixture.by_label("Save").expect("the row is named by its command"); + let shortcut = fixture.by_label("Ctrl+S").expect("a node is named by the row's chord spoken"); + assert!(row.rect.contains(shortcut.rect.center()), "the chord's node is the row's shortcut part: {:?} in {:?}", shortcut.rect, row.rect); + assert_ne!(shortcut.node, row.node, "the chord names the shortcut part's sub-node, not the row"); +} + #[trial] fn a_detail_shows_as_a_second_line_under_the_label() { let mut fixture = Fixture::new(|ui| { From 5dc24081b95defc7f744dbd212a007cad0a7ab0a Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 22:33:17 +0100 Subject: [PATCH 07/37] Cover Scroll Into View on a button below a scrolling stack's view A screen reader's Scroll Into View on a component that a scrolling stack holds out of its view should scroll the stack until the component shows, as Tab to it does. The trial shows a button below a 300-point block in a stack that scrolls, inside a host whose room_height gives it 100 points: room_height caps the room a container offers its children, so the host holds the room and the stack scrolls in it. --- .../tests/it/access/scroll_into_view.rs | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/ui-widgets/tests/it/access/scroll_into_view.rs b/crates/ui-widgets/tests/it/access/scroll_into_view.rs index 07052a5623..84e09d3827 100644 --- a/crates/ui-widgets/tests/it/access/scroll_into_view.rs +++ b/crates/ui-widgets/tests/it/access/scroll_into_view.rs @@ -2,11 +2,15 @@ use craft_behavior::{Selection, keyed}; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, Props as _, Show as _, ShowCollection as _}; +use craft_ui::contract::{Bind, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; +use craft_ui::layout_components::Stack; use craft_ui::list::{List, ListRow}; use craft_ui::testing::focus::AccessActionKind; +use craft_ui::testing::layout::Block; use craft_ui::testing::{Fixture, trial}; use egui::{Id, Key, Modifiers, Rect, Vec2}; +use std::cell::Cell; +use std::rc::Rc; #[trial] fn scroll_into_view_moves_no_focus() { @@ -56,3 +60,32 @@ fn scroll_into_view_on_a_list_row_scrolls_the_list_to_it() { let after = fixture.by_label("Row 150").expect("row 150's node").rect; assert!((after.min - shown.min).length() <= 0.5, "Scroll Into View on a row in view moved nothing: {after:?}, was {shown:?}"); } + +/// A screen reader's Scroll Into View on a button below a scrolling stack's view scrolls the stack until the button +/// shows, as Tab to it does. `room_height` caps the room a container offers its children, not the container itself, so +/// the 100 points go on a host around the scrolling stack: the stack takes at most that room and scrolls the 300-point +/// block and the button under it, as a small window's dialog column does. +#[trial] +fn scroll_into_view_on_a_button_below_a_stacks_view_scrolls_the_stack_to_it() { + let view = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&view); + let mut fixture = Fixture::new(move |ui| { + Stack::new().fill_width().room_height(100.0).show(ui, |ui, _| { + Stack::new().fill_width().scroll(Scroll::vertical()).show(ui, |ui, cx| { + if !ui.is_sizing_pass() { + seen.set(cx.rect); + } + Block::new(Vec2::new(100.0, 300.0)).show(ui); + Button::new("Far").show(ui); + }); + }); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + let button = fixture.by_label("Far").expect("the button's node"); + assert!(view.get().height() <= 100.5, "the stack takes at most its host's room: {:?}", view.get()); + assert!(!shows(view.get(), button.rect), "the button starts out of view: {:?} in {:?}", button.rect, view.get()); + fixture.access(AccessActionKind::ScrollIntoView, &button).settle(); + let shown = fixture.by_label("Far").expect("the button's node").rect; + assert!(shows(view.get(), shown), "Scroll Into View brought the button into the stack's view: {shown:?} in {:?}", view.get()); +} From 82b2dc6508f7a37b81ddcc4df20261db3af1ba12 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 22:47:39 +0100 Subject: [PATCH 08/37] Let the wheel over a focused text field scroll its container A value control that senses no wheel axis registered a gated vertical wheel taker with no room. A focused single-line text field therefore took the vertical wheel while the pointer was over it and did nothing with it, so the scrolling region around it never moved. Dialogs that focus their first field hit this at once. A text field that does not step by the wheel now registers no fallback taker. A multi-line text part whose text overflows still registers its own scroll taker with room, and number fields keep the focused-field rule. --- .../ui-contract/src/contract/steps/sense.rs | 22 ++++--- crates/ui-widgets/tests/it/text/text_field.rs | 62 +++++++++++++++++-- 2 files changed, 70 insertions(+), 14 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/sense.rs b/crates/ui-contract/src/contract/steps/sense.rs index 84fb52ff8e..d14deec4be 100644 --- a/crates/ui-contract/src/contract/steps/sense.rs +++ b/crates/ui-contract/src/contract/steps/sense.rs @@ -7,15 +7,17 @@ use craft_theme::{State, StateMix}; use egui::{Context, Id, Rect}; /// Registers a wheel taker for next pass's split (8.6): `sensed`, the taker the wheel bits of the component's sense -/// make (`WheelTaker::for_sense`). Every value control is a `WheelTaker::value` taker, in any scope: a wheel gesture it -/// owns ends with a `WheelPhase::End` share. A value control with a text part that steps by the wheel (it senses a -/// wheel axis: a number field) is a field (`WheelTaker::field`), which takes the plain wheel while focused wherever the -/// pointer is; a text field that does not step leaves the wheel over the rest of the window to what is there. A value -/// control takes the wheel only while focused or armed, on the axes it senses (the vertical one when it senses none); -/// inside a `WheelScope::Free` scope one that senses the wheel takes it without focus. A value control that steps by -/// the wheel declares the axis it steps in its sense, so a free scope frees it; one that does not step keeps the -/// fallback and stays gated. Inside a `WheelScope::Gated` scope every taker waits for focus or arming. A zoom zone that -/// takes no axis itself waits only for a gated scope: its wheel goes to the view around it. +/// make (`WheelTaker::for_sense`). Every value control that takes the wheel is a `WheelTaker::value` taker, in any +/// scope: a wheel gesture it owns ends with a `WheelPhase::End` share. A value control with a text part that steps by +/// the wheel (it senses a wheel axis: a number field) is a field (`WheelTaker::field`), which takes the plain wheel +/// while focused wherever the pointer is. A text field that does not step takes no wheel at all, focused or not: the +/// wheel over it scrolls the region around it, as native fields do, and a multi-line text part whose text overflows +/// registers its own scroll taker (`text_adapter`), which passes the wheel on at its ends. Any other value control +/// takes the wheel only while focused or armed, on the axes it senses (the vertical one when it senses none); inside a +/// `WheelScope::Free` scope one that senses the wheel takes it without focus. A value control that steps by the wheel +/// declares the axis it steps in its sense, so a free scope frees it; one that does not keeps the fallback and stays +/// gated. Inside a `WheelScope::Gated` scope every taker waits for focus or arming. A zoom zone that takes no axis +/// itself waits only for a gated scope: its wheel goes to the view around it. pub(crate) fn register_wheel( ctx: &Context, id: Id, @@ -27,7 +29,7 @@ pub(crate) fn register_wheel( ) { let free = sensed.is_some() && scope == WheelScope::Free; let zone = sensed.is_some_and(|taker| taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom)); - let taker = sensed.or_else(|| value_control.then(|| craft_behavior::WheelTaker::new(id, rect).vertical(true))); + let taker = sensed.or_else(|| (value_control && !text).then(|| craft_behavior::WheelTaker::new(id, rect).vertical(true))); if let Some(taker) = taker { wheel::register( ctx, diff --git a/crates/ui-widgets/tests/it/text/text_field.rs b/crates/ui-widgets/tests/it/text/text_field.rs index 06588fb22b..313ebff3b1 100644 --- a/crates/ui-widgets/tests/it/text/text_field.rs +++ b/crates/ui-widgets/tests/it/text/text_field.rs @@ -1,12 +1,13 @@ //! `TextField`: the search form's clear part empties the text; a multi-line field grows to `max_lines` or fills its -//! room and scrolls its text inside; a bound caret goes both ways. +//! room and scrolls its text inside; a bound caret goes both ways; the wheel over a focused field scrolls the form +//! around it. use craft_behavior::PartKey; -use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft_ui::layout_components::Stack; use craft_ui::testing::{Fixture, pointer, trial}; -use craft_ui::text::TextField; -use egui::{Id, Key, Modifiers, Rect, Vec2}; +use craft_ui::text::{NumberField, TextField}; +use egui::{Id, Key, Modifiers, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -297,3 +298,56 @@ fn the_clear_part_empties_the_field_in_the_pass_of_its_click() { assert_eq!(text.borrow().as_str(), "", "the click emptied the text"); assert_eq!(fixture.tree().value(id.get()), Some(""), "the field reads empty in the pass of the click"); } + +/// A 200 × 120 form: `first`, then twenty text fields, in a scrolling stack a 100-point room caps, so the fields +/// overflow it. +fn scrolling_form(mut first: impl FnMut(&mut Ui) + 'static) -> Fixture { + let texts = Rc::new(RefCell::new(vec![String::new(); 20])); + let mut fixture = Fixture::new(move |ui| { + Stack::new().fill_width().room_height(100.0).show(ui, |ui, _| { + Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { + first(ui); + for (row, text) in texts.borrow_mut().iter_mut().enumerate() { + TextField::new(format!("Field {row}"), Bind::bound(text)).id_salt(row).show(ui); + } + }); + }); + }); + fixture.room(Vec2::new(200.0, 120.0)).settle(); + fixture +} + +/// The wheel over a focused single-line text field, which has nothing to scroll or step, scrolls the form around it, +/// as native fields do; a focused number field under the pointer still steps by the wheel and keeps the form still. +#[trial] +fn the_wheel_over_a_focused_text_field_scrolls_the_form_around_it() { + let name = Rc::new(RefCell::new(String::new())); + let shown = Rc::clone(&name); + let mut fixture = scrolling_form(move |ui| { + TextField::new("Name", Bind::bound(&mut *shown.borrow_mut())).id_salt("name").show(ui); + }); + let field = fixture.by_label("Name").expect("the Name field"); + fixture.click(&field).settle(); + assert!(fixture.focused_stop().is_some(), "the click focuses the Name field"); + fixture.frame(vec![pointer::moved(field.center())]); + fixture.frame(vec![pointer::wheel(-40.0)]); + fixture.idle(3); + let moved = fixture.by_label("Name").expect("the Name field").rect; + assert!(moved.top() < field.rect.top() - 1.0, "the wheel scrolls the form, moving the Name field up: {:?} to {moved:?}", field.rect); + + let value = Rc::new(Cell::new(Some(10.0))); + let held = Rc::clone(&value); + let mut fixture = scrolling_form(move |ui| { + let mut current = held.get(); + NumberField::new("Size", Bind::bound(&mut current)).id_salt("size").range(0.0..=100.0).show(ui); + held.set(current); + }); + let field = fixture.by_label("Size").expect("the Size field"); + fixture.click(&field).settle(); + fixture.frame(vec![pointer::moved(field.center())]); + fixture.frame(vec![pointer::wheel_lines(1.0)]); + fixture.idle(3); + assert_ne!(value.get(), Some(10.0), "the wheel steps the focused number field"); + let still = fixture.by_label("Size").expect("the Size field").rect; + assert!((still.top() - field.rect.top()).abs() <= SNAP, "and the form stays put: {:?} to {still:?}", field.rect); +} From 45d06de7f5b5bdf51dcfbc7be7d0391fddc649d0 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 22:53:16 +0100 Subject: [PATCH 09/37] Take the wheel only for controls that sense it A bound control that sensed no wheel bit still got a gated vertical wheel taker. A focused check box, switch or other value control that never reads the wheel therefore took the wheel while the pointer was over it and dropped it, so the form around it did not scroll. Controls now take the wheel only through their sense. The new Sense::WHEEL_Y_FOCUSED bit takes the vertical share only while focused or armed, in any wheel scope. RangeSlider and ThumbRow, the two value controls that read the wheel without sensing it, declare it, and the fallback taker is gone. --- crates/behavior/src/sense.rs | 12 ++++- crates/behavior/src/wheel.rs | 9 ++-- .../ui-contract/src/contract/items/hooks.rs | 2 +- crates/ui-contract/src/contract/run.rs | 2 +- .../ui-contract/src/contract/steps/sense.rs | 52 +++++++------------ .../ui-widgets/src/value_drag/range_slider.rs | 6 +-- crates/ui-widgets/src/value_drag/thumb_row.rs | 6 +-- crates/ui-widgets/tests/it/text/text_field.rs | 52 ++++++++++++++++++- docs/glossary.md | 1 + 9 files changed, 95 insertions(+), 47 deletions(-) diff --git a/crates/behavior/src/sense.rs b/crates/behavior/src/sense.rs index c64efa2fbd..99281664b3 100644 --- a/crates/behavior/src/sense.rs +++ b/crates/behavior/src/sense.rs @@ -55,6 +55,11 @@ bitflags! { /// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`, /// without `DRAG`. const PASSES_DRAG = 131072; + /// The vertical wheel share, taken only while the component holds key focus or a press armed it, in any wheel + /// scope: a control whose wheel steps what focus picks rather than what the pointer is over (the focused thumb + /// of a range). Every other wheel bit the shape senses waits for focus with it. A control that senses no wheel + /// bit takes no wheel at all, so the wheel over it scrolls the region around it. + const WHEEL_Y_FOCUSED = 262144; } } @@ -63,7 +68,12 @@ impl Sense { pub const PRESS: Sense = Sense::CLICK.union(Sense::DRAG); /// The bits that make a shape register a wheel taker. - pub const WHEELS: Sense = Sense::WHEEL.union(Sense::WHEEL_X).union(Sense::WHEEL_Y).union(Sense::WHEEL_ZOOM).union(Sense::WHEEL_ZOOMS_VIEW); + pub const WHEELS: Sense = Sense::WHEEL + .union(Sense::WHEEL_X) + .union(Sense::WHEEL_Y) + .union(Sense::WHEEL_ZOOM) + .union(Sense::WHEEL_ZOOMS_VIEW) + .union(Sense::WHEEL_Y_FOCUSED); /// Whether a press can start on a shape with this sense. pub const fn takes_press(self) -> bool { diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 1985e4bf9c..7b0bb69c2b 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -423,14 +423,17 @@ impl WheelTaker { /// The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll /// axes and zoom; `WHEEL_X`, `WHEEL_Y` and `WHEEL_ZOOM` take one share each and combine; `WHEEL_ZOOMS_VIEW` - /// makes a zoom zone. + /// makes a zoom zone; `WHEEL_Y_FOCUSED` takes the vertical share and makes the taker gated, so every axis it takes + /// waits for focus or arming. pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option { let all = sense.contains(Sense::WHEEL); + let focused = sense.contains(Sense::WHEEL_Y_FOCUSED); let taker = WheelTaker::new(owner, rect) .horizontal(all || sense.contains(Sense::WHEEL_X)) - .vertical(all || sense.contains(Sense::WHEEL_Y)) + .vertical(all || focused || sense.contains(Sense::WHEEL_Y)) .zoom(all || sense.contains(Sense::WHEEL_ZOOM)) - .zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW)); + .zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW)) + .gated(focused); (taker.horizontal || taker.vertical || taker.zoom || taker.zooms_view).then_some(taker) } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index f4166d548c..d43e01f522 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -238,7 +238,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { if cx.core.resolved.enabled && let Some(taker) = WheelTaker::for_sense(cx.core.id, cx.core.rect, crate::contract::Component::sense(comp)) { - wheel::register(&cx.core.ctx, taker.notch(self.notch).gated(cx.core.env.wheel() == WheelScope::Gated)); + wheel::register(&cx.core.ctx, taker.notch(self.notch).gated(taker.gated || cx.core.env.wheel() == WheelScope::Gated)); } } else if self.scrolls { // The taker covers the whole collection, header row and frame included: the wheel over the header scrolls diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index c87b86cf68..e06d776cc2 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1021,7 +1021,7 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, e }; if !inert && registers { let sensed = craft_behavior::WheelTaker::for_sense(id, rect, own).map(|taker| taker.notch(e.wheel_notch())); - steps::register_wheel(&ctx, id, rect, sensed, e.bound().0 && !facts.binds_view, facts.text(), env.wheel); + steps::register_wheel(&ctx, sensed, e.bound().0 && !facts.binds_view, facts.text(), env.wheel); } // 8 sense p.trace.mark(Step::Sense); diff --git a/crates/ui-contract/src/contract/steps/sense.rs b/crates/ui-contract/src/contract/steps/sense.rs index d14deec4be..aa69b0aa3a 100644 --- a/crates/ui-contract/src/contract/steps/sense.rs +++ b/crates/ui-contract/src/contract/steps/sense.rs @@ -4,41 +4,27 @@ use crate::runtime::env::WheelScope; use crate::runtime::wheel; use crate::style::{Flags, StateSet}; use craft_theme::{State, StateMix}; -use egui::{Context, Id, Rect}; +use egui::{Context, Id}; /// Registers a wheel taker for next pass's split (8.6): `sensed`, the taker the wheel bits of the component's sense -/// make (`WheelTaker::for_sense`). Every value control that takes the wheel is a `WheelTaker::value` taker, in any -/// scope: a wheel gesture it owns ends with a `WheelPhase::End` share. A value control with a text part that steps by -/// the wheel (it senses a wheel axis: a number field) is a field (`WheelTaker::field`), which takes the plain wheel -/// while focused wherever the pointer is. A text field that does not step takes no wheel at all, focused or not: the -/// wheel over it scrolls the region around it, as native fields do, and a multi-line text part whose text overflows -/// registers its own scroll taker (`text_adapter`), which passes the wheel on at its ends. Any other value control -/// takes the wheel only while focused or armed, on the axes it senses (the vertical one when it senses none); inside a -/// `WheelScope::Free` scope one that senses the wheel takes it without focus. A value control that steps by the wheel -/// declares the axis it steps in its sense, so a free scope frees it; one that does not keeps the fallback and stays -/// gated. Inside a `WheelScope::Gated` scope every taker waits for focus or arming. A zoom zone that takes no axis -/// itself waits only for a gated scope: its wheel goes to the view around it. -pub(crate) fn register_wheel( - ctx: &Context, - id: Id, - rect: Rect, - sensed: Option>, - value_control: bool, - text: bool, - scope: WheelScope, -) { - let free = sensed.is_some() && scope == WheelScope::Free; - let zone = sensed.is_some_and(|taker| taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom)); - let taker = sensed.or_else(|| (value_control && !text).then(|| craft_behavior::WheelTaker::new(id, rect).vertical(true))); - if let Some(taker) = taker { - wheel::register( - ctx, - taker - .value(value_control) - .field(value_control && text && sensed.is_some()) - .gated(scope == WheelScope::Gated || (value_control && !free && !zone)), - ); - } +/// make (`WheelTaker::for_sense`). A component that senses no wheel bit takes no wheel, value control or not: the wheel +/// over a focused check box or text field scrolls the region around it, as native controls do, and a multi-line text +/// part whose text overflows registers its own scroll taker (`text_adapter`), which passes the wheel on at its ends. +/// Every value control that takes the wheel is a `WheelTaker::value` taker, in any scope: a wheel gesture it owns ends +/// with a `WheelPhase::End` share. A value control with a text part that steps by the wheel (a number field) is a field +/// (`WheelTaker::field`), which takes the plain wheel while focused wherever the pointer is. A value control takes the +/// wheel only while focused or armed, on the axes it senses; inside a `WheelScope::Free` scope one that senses the +/// wheel takes it without focus, unless it senses `Sense::WHEEL_Y_FOCUSED`, which no scope frees (a range whose wheel +/// steps its focused thumb). Inside a `WheelScope::Gated` scope every taker waits for focus or arming. A zoom zone that +/// takes no axis itself waits only for a gated scope: its wheel goes to the view around it. +pub(crate) fn register_wheel(ctx: &Context, sensed: Option>, value_control: bool, text: bool, scope: WheelScope) { + let Some(taker) = sensed else { return }; + let free = !taker.gated && scope == WheelScope::Free; + let zone = taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom); + wheel::register( + ctx, + taker.value(value_control).field(value_control && text).gated(taker.gated || scope == WheelScope::Gated || (value_control && !free && !zone)), + ); } /// The part states: each part's press and hover from the sensing core, with its own flags. diff --git a/crates/ui-widgets/src/value_drag/range_slider.rs b/crates/ui-widgets/src/value_drag/range_slider.rs index 00fd5547af..1b8c294015 100644 --- a/crates/ui-widgets/src/value_drag/range_slider.rs +++ b/crates/ui-widgets/src/value_drag/range_slider.rs @@ -195,10 +195,10 @@ impl Component for RangeSlider<'_> { Vec2::new(cx.style.length, cx.icon() + self.marks.below(&cx.style.track)) } - /// No wheel bits: as a value control the row takes the vertical wheel only while focused or armed, and no scope - /// frees it, since a wheel over the track has no one thumb to step. + /// The vertical wheel only while focused or armed (`Sense::WHEEL_Y_FOCUSED`), which no scope frees, since a wheel + /// over the track has no one thumb to step: it steps the focused one. fn sense(&self) -> Sense { - Sense::empty() + Sense::WHEEL_Y_FOCUSED } /// The track, and a thumb each that is its own Tab stop and takes the arrow keys. diff --git a/crates/ui-widgets/src/value_drag/thumb_row.rs b/crates/ui-widgets/src/value_drag/thumb_row.rs index bf2ba60e86..1c69504daf 100644 --- a/crates/ui-widgets/src/value_drag/thumb_row.rs +++ b/crates/ui-widgets/src/value_drag/thumb_row.rs @@ -977,10 +977,10 @@ impl Component for ThumbRow<'_, N> { Some(craft_behavior::Axis::X) } - /// No wheel bits: as a value control the row takes the vertical wheel only while focused or armed, and no scope - /// frees it, since a wheel over the track has no one thumb to step. + /// The vertical wheel only while focused or armed (`Sense::WHEEL_Y_FOCUSED`), which no scope frees, since a wheel + /// over the track has no one thumb to step: it steps the focused one. fn sense(&self) -> Sense { - Sense::empty() + Sense::WHEEL_Y_FOCUSED } fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { diff --git a/crates/ui-widgets/tests/it/text/text_field.rs b/crates/ui-widgets/tests/it/text/text_field.rs index 313ebff3b1..69a89387d9 100644 --- a/crates/ui-widgets/tests/it/text/text_field.rs +++ b/crates/ui-widgets/tests/it/text/text_field.rs @@ -1,6 +1,6 @@ //! `TextField`: the search form's clear part empties the text; a multi-line field grows to `max_lines` or fills its -//! room and scrolls its text inside; a bound caret goes both ways; the wheel over a focused field scrolls the form -//! around it. +//! room and scrolls its text inside; a bound caret goes both ways; the wheel over a focused field or check box scrolls +//! the form around it, and a focused number field or range still takes it. use craft_behavior::PartKey; use craft_ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; @@ -351,3 +351,51 @@ fn the_wheel_over_a_focused_text_field_scrolls_the_form_around_it() { let still = fixture.by_label("Size").expect("the Size field").rect; assert!((still.top() - field.rect.top()).abs() <= SNAP, "and the form stays put: {:?} to {still:?}", field.rect); } + +/// The wheel over a focused check box, which neither senses nor reads the wheel, scrolls the form around it; a range +/// slider, which senses the wheel only while focused (`Sense::WHEEL_Y_FOCUSED`), still steps its focused thumb and +/// keeps the form still. +#[trial] +fn the_wheel_over_a_focused_check_box_scrolls_the_form_and_a_focused_range_steps() { + use craft_behavior::Mixed; + use craft_ui::choice::Checkbox; + use craft_ui::testing::focus::AccessActionKind; + use craft_ui::value_drag::RangeSlider; + + let agreed = Rc::new(Cell::new(false)); + let shown = Rc::clone(&agreed); + let mut fixture = scrolling_form(move |ui| { + let mut on = shown.get(); + Checkbox::new(Bind::bound(&mut on)).label("Agree").id_salt("agree").show(ui); + shown.set(on); + }); + let check = fixture.by_label("Agree").expect("the Agree check box"); + fixture.access(AccessActionKind::Focus, &check).settle(); + assert!(fixture.focused_stop().is_some(), "the check box holds focus"); + fixture.frame(vec![pointer::moved(check.center())]); + fixture.frame(vec![pointer::wheel(-40.0)]); + fixture.idle(3); + let moved = fixture.by_label("Agree").expect("the Agree check box").rect; + assert!(moved.top() < check.rect.top() - 1.0, "the wheel scrolls the form, moving the check box up: {:?} to {moved:?}", check.rect); + assert!(!agreed.get(), "the wheel leaves the check box's value alone"); + + let start = (Mixed::Same(20.0), Mixed::Same(80.0)); + let range = Rc::new(Cell::new(start)); + let rect = Rc::new(Cell::new(Rect::NOTHING)); + let (held, seen) = (Rc::clone(&range), Rc::clone(&rect)); + let mut fixture = scrolling_form(move |ui| { + let mut pair = held.get(); + seen.set(RangeSlider::new(Bind::bound(&mut pair), 0.0..=100.0).label("Hue").id_salt("hue").show(ui).response.rect); + held.set(pair); + }); + let slider = rect.get(); + // A click on the span between the thumbs focuses the nearer one and moves neither. + fixture.click_at(slider.center()).settle(); + assert!(fixture.focused_stop().is_some_and(|(_, part)| part.is_some()), "the click focuses a thumb"); + assert_eq!(range.get(), start, "the click moves neither thumb"); + fixture.frame(vec![pointer::moved(slider.center())]); + fixture.frame(vec![pointer::wheel_lines(1.0)]); + fixture.idle(3); + assert_ne!(range.get(), start, "the wheel steps the focused thumb"); + assert!((rect.get().top() - slider.top()).abs() <= SNAP, "and the form stays put: {slider:?} to {:?}", rect.get()); +} diff --git a/docs/glossary.md b/docs/glossary.md index 317b2a8587..332c43a084 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -250,6 +250,7 @@ One row per name in the author table (Overview) and per `pub` item a component a | `Sense` | The library's sense set for a root or part | craft-behavior | 1.1 | | `Sense::TAKE_FOCUS` | A sense bit: a press this shape wins moves key focus to its component | craft-behavior | 1.1, 8.3 | | `Sense::WHEEL_X` | A sense bit: takes the horizontal wheel share without focus or arming | craft-behavior | 1.1, 8.6 | +| `Sense::WHEEL_Y_FOCUSED` | A sense bit: takes the vertical wheel share only while focused or armed, in any wheel scope | craft-behavior | 1.1, 8.6 | | `SetPosition` | An item's index, set size and level for AccessKit | `craft_ui::runtime::access` | 12.1 | | Settle | Step 15 | `craft_ui::contract` | 1.6 | | `ShellInfo` | OS, runtime, backend, capabilities, menu placement and window info | craft-host (`target`) | 21.1 | From e52d09ef6cdbee247dc0d62a6829532ee7a5658c Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 25 Nov 2026 04:35:36 +0100 Subject: [PATCH 10/37] docs: regenerate contract-api.md --- docs/contract-api.md | 351 +++++++++++++++++++++++++++++++++---------- 1 file changed, 273 insertions(+), 78 deletions(-) diff --git a/docs/contract-api.md b/docs/contract-api.md index 71e9ab4c8e..35ccc0c01f 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -57,6 +57,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::ColumnWidth`: re-export of `craft_behavior::columns::ColumnWidth`. - `craft_behavior::CommandFlags`: re-export of `craft_behavior::command::CommandFlags`. - `craft_behavior::ControlMetrics`: re-export of `craft_behavior::sizing::ControlMetrics`. +- `craft_behavior::CopyKeys`: re-export of `craft_behavior::keys::CopyKeys`. - `craft_behavior::CountMark`: re-export of `craft_behavior::cursor::CountMark`. - `craft_behavior::Cursor`: re-export of `craft_behavior::cursor::Cursor`. - `craft_behavior::CursorBadge`: re-export of `craft_behavior::cursor::CursorBadge`. @@ -79,6 +80,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::Ended`: re-export of `craft_behavior::typing::Ended`. - `craft_behavior::EscapeRule`: re-export of `craft_behavior::typing::EscapeRule`. - `craft_behavior::Escaped`: re-export of `craft_behavior::typing::Escaped`. +- `craft_behavior::FRAME_STEP_MAX`: re-export of `craft_behavior::frame_step::FRAME_STEP_MAX`. - `craft_behavior::Flow`: re-export of `craft_behavior::flow::Flow`. - `craft_behavior::FreeLayout`: re-export of `craft_behavior::item_layout::FreeLayout`. - `craft_behavior::GESTURE_GAP`: re-export of `craft_behavior::wheel::GESTURE_GAP`. @@ -112,6 +114,8 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::MarqueeMode`: re-export of `craft_behavior::item_marquee::MarqueeMode`. - `craft_behavior::MarqueeSelect`: re-export of `craft_behavior::item_marquee::MarqueeSelect`. - `craft_behavior::Metrics`: re-export of `craft_behavior::sizing::Metrics`. +- `craft_behavior::MiddleButton`: re-export of `craft_behavior::middle_scroll::MiddleButton`. +- `craft_behavior::MiddleScroll`: re-export of `craft_behavior::middle_scroll::MiddleScroll`. - `craft_behavior::Mixed`: re-export of `craft_behavior::value::Mixed`. - `craft_behavior::Monitor`: re-export of `craft_behavior::monitor::Monitor`. - `craft_behavior::MonitorKey`: re-export of `craft_behavior::monitor::MonitorKey`. @@ -169,16 +173,19 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::PointerSample`: re-export of `craft_behavior::press::PointerSample`. - `craft_behavior::Positions`: `pub struct Positions`. The display order of a grid whose row keys are their positions (a sheet, a document table): `key(at) == at`, and - `pub const fn new(rows: u32) -> Self`. The order of `rows` rows. +- `craft_behavior::PressAside`: re-export of `craft_behavior::press::PressAside`. - `craft_behavior::PressCancel`: re-export of `craft_behavior::press::PressCancel`. - `craft_behavior::PressFocus`: re-export of `craft_behavior::focus::PressFocus`. - `craft_behavior::PressMachine`: re-export of `craft_behavior::press::PressMachine`. - `craft_behavior::PressPhase`: re-export of `craft_behavior::press::PressPhase`. +- `craft_behavior::PressPick`: re-export of `craft_behavior::press::PressPick`. - `craft_behavior::PressStart`: re-export of `craft_behavior::press::PressStart`. - `craft_behavior::PressState`: re-export of `craft_behavior::press::PressState`. - `craft_behavior::PressStep`: re-export of `craft_behavior::press::PressStep`. - `craft_behavior::Preview`: re-export of `craft_behavior::value::Preview`. - `craft_behavior::Proposal`: re-export of `craft_behavior::sizing::Proposal`. - `craft_behavior::Reader`: re-export of `craft_behavior::quantity::Reader`. +- `craft_behavior::ReorderKeys`: re-export of `craft_behavior::keys::ReorderKeys`. - `craft_behavior::ResolveFor`: re-export of `craft_behavior::hit::ResolveFor`. - `craft_behavior::RoleRule`: re-export of `craft_behavior::role_rule::RoleRule`. - `craft_behavior::Roving`: `pub struct Roving { pub shape: NavShape, pub wrap: bool, pub home_end: bool, pub page: Option, pub letters: Letters, pub arrows: Arrows, pub first_column: Option, pub hands_back: bool, pub no_lead: bool, pub keeps_lead_moves: bool }`. A roving group's rules: one Tab stop whose members take moves. @@ -195,13 +202,14 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `pub const fn state(&self, lead: Option) -> NavState`. The state a step over this group starts from, at `lead`, or from no lead when the group has none. - `pub const fn takes(&self, mv: NavMove, mods: MoveMods) -> bool`. Whether the group handles `mv` with `mods`: Page moves only with a page size and without `lead` (on a document - `craft_behavior::RowAt`: re-export of `craft_behavior::selection::RowAt`. -- `craft_behavior::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks }`. The ruler unit of one document axis: its size and its ticks. Rulers label their ticks with it; guides use it for - - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`. +- `craft_behavior::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; + - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. + - `pub const fn with_labels(mut self, labels: TickLabels) -> Self`. The units with their ticks written as `labels`. - `pub const fn pixels() -> Self`. Whole document pixels. - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` - `pub fn distance(&self, position: f64, zero: f64) -> f64`. The distance of `position` (document units) from `zero`, in ruler units. - - `pub fn label_decimals(&self, step: f64) -> usize`. The decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; a step of at + - `pub fn label_decimals(&self, step: f64) -> RangeInclusive`. The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; - `pub fn label_value(&self, value: f64, step: f64) -> f64`. The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: - `craft_behavior::SHEET_ZOOM`: re-export of `craft_behavior::item_layout::SHEET_ZOOM`. - `craft_behavior::ScopeKind`: re-export of `craft_behavior::focus::ScopeKind`. @@ -218,6 +226,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::SpanLayout`: re-export of `craft_behavior::item_layout::SpanLayout`. - `craft_behavior::SurroundingUnit`: re-export of `craft_behavior::editor::SurroundingUnit`. - `craft_behavior::TextPos`: re-export of `craft_behavior::intent::TextPos`. +- `craft_behavior::TickLabels`: `pub enum TickLabels { Distance, Signed }`. How a ruler writes the number at a labelled tick. - `craft_behavior::Ticks`: `pub enum Ticks { Decimal { whole: bool }, Custom(fn(f64) -> (f64, u32)) }`. How a ruler divides its unit at a zoom. - `pub const fn decimal(whole: bool) -> Self`. PhotoCraft's decimal steps; `whole` keeps the step a whole number of units without 2.5. - `craft_behavior::TileLayout`: re-export of `craft_behavior::item_layout::TileLayout`. @@ -238,6 +247,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::ViewPlace`: `pub struct ViewPlace { pub key: K, pub center: Point, pub zoom: f64 }`. Where a view stood: what it showed (`key`: a page, an artboard, a document) and the view's - `pub const fn new(key: K, center: Point, zoom: f64) -> Self`. The view of `key` centred on `center` at `zoom`. - `craft_behavior::Wheel`: re-export of `craft_behavior::wheel::Wheel`. +- `craft_behavior::WheelEase`: re-export of `craft_behavior::wheel::WheelEase`. - `craft_behavior::WheelFocus`: re-export of `craft_behavior::wheel::WheelFocus`. - `craft_behavior::WheelGesture`: re-export of `craft_behavior::wheel::WheelGesture`. - `craft_behavior::WheelNotch`: re-export of `craft_behavior::wheel::WheelNotch`. @@ -251,6 +261,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::ZoomScheme`: re-export of `craft_behavior::canvas::zoom::ZoomScheme`. - `craft_behavior::count_clicks`: re-export of `craft_behavior::press::count_clicks`. - `craft_behavior::decimals_for_step`: re-export of `craft_behavior::codec::decimals_for_step`. +- `craft_behavior::frame_step`: re-export of `craft_behavior::frame_step::frame_step`. - `craft_behavior::is_checkable`: re-export of `craft_behavior::role_rule::is_checkable`. - `craft_behavior::is_selectable`: re-export of `craft_behavior::role_rule::is_selectable`. - `craft_behavior::keyed`: re-export of `craft_behavior::item_source::keyed`. @@ -312,14 +323,16 @@ The transform a canvas body is shown through, and the canvas view with its zoom - `pub fn layer_transform(&self) -> Option`. The transform a canvas body is shown through when this view only scales and moves the document: unturned, - `pub fn axis_aligned(&self) -> bool`. Whether the rotation is a multiple of 90°, so document axes are screen axes. - `pub fn level(&self, zero: Point) -> CanvasView`. The view without its rotation, moved so it draws `zero` where this view does: the same -- `craft_behavior::canvas::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks }`. The ruler unit of one document axis: its size and its ticks. Rulers label their ticks with it; guides use it for - - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`. +- `craft_behavior::canvas::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; + - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. + - `pub const fn with_labels(mut self, labels: TickLabels) -> Self`. The units with their ticks written as `labels`. - `pub const fn pixels() -> Self`. Whole document pixels. - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` - `pub fn distance(&self, position: f64, zero: f64) -> f64`. The distance of `position` (document units) from `zero`, in ruler units. - - `pub fn label_decimals(&self, step: f64) -> usize`. The decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; a step of at + - `pub fn label_decimals(&self, step: f64) -> RangeInclusive`. The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; - `pub fn label_value(&self, value: f64, step: f64) -> f64`. The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: +- `craft_behavior::canvas::TickLabels`: `pub enum TickLabels { Distance, Signed }`. How a ruler writes the number at a labelled tick. - `craft_behavior::canvas::Ticks`: `pub enum Ticks { Decimal { whole: bool }, Custom(fn(f64) -> (f64, u32)) }`. How a ruler divides its unit at a zoom. - `pub const fn decimal(whole: bool) -> Self`. PhotoCraft's decimal steps; `whole` keeps the step a whole number of units without 2.5. - `craft_behavior::canvas::ViewHistory`: `pub struct ViewHistory`. The places a window jumped between, oldest first, with the one it shows now. The app records @@ -384,6 +397,8 @@ Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zo - `pub fn new(reader: Reader, decimals: usize) -> Self`. A codec reading with `reader` and writing at most `decimals` decimal places. - `pub fn fixed(mut self) -> Self`. The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown - `pub fn zoom_typing(mut self) -> Self`. The same codec with the typing rules of a zoom field: digits, `/` and the decimal separator, `a/b` as the + - `pub fn signed_zoom(mut self) -> Self`. Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign. + - `pub fn share_of_start(mut self) -> Self`. The same codec reading a lone percentage (`50%`, [`Reader::share`]) as that share of the value the edit - `pub fn at_most(mut self, decimals: usize) -> Self`. The same codec writing at most `decimals` decimal places. - `pub fn or_parse(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self`. The same codec with `parse` as a second reader: it runs when the reader rejects the text, so words of the - `pub fn widest(&self, range: &RangeInclusive) -> String`. The widest text the codec writes for a number in `range`: the longest of each end and the number one place of @@ -429,11 +444,11 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `craft_behavior::cursor::Cursor`: `pub enum Cursor { System(CursorIcon), Painted(PaintedCursor) }`. What a cursor request names. - `craft_behavior::cursor::CursorBadge`: `pub enum CursorBadge { Add, Subtract, Intersect, Copy, NotAllowed, Scissors, Close, Move, Arrow, Target, Continue, Count(CountMark), Corner }`. A mark beside a painted cursor. - `craft_behavior::cursor::CursorIcon`: `pub enum CursorIcon { Default, None, ContextMenu, Help, PointingHand, Progress, Wait, Cell, Crosshair, Text, VerticalText, Alias, Copy, Move, NoDrop, NotAllowed, Grab, Grabbing, AllScroll, ResizeHorizontal, ResizeNeSw, ResizeNwSe, ResizeVertical, ResizeColumn, ResizeEast, ResizeSouthEast, ResizeSouth, ResizeSouthWest, ResizeWest, ResizeNorthWest, ResizeNorth, ResizeNorthEast, ZoomIn, ZoomOut }`. A system cursor: craft-behavior's copy of egui's set, converted by `runtime::egui::output`. -- `craft_behavior::cursor::CursorPriority`: `pub enum CursorPriority { Default, Tool, Hover, Part, DropTarget, Drag }`. Who asks, in ascending order of precedence. +- `craft_behavior::cursor::CursorPriority`: `pub enum CursorPriority { Default, Tool, Hover, Part, DropTarget, Drag, Hidden }`. Who asks, in ascending order of precedence. - `craft_behavior::cursor::IconId`: `pub struct IconId`. An icon's egui-free key (5.2), so plain data such as [`PaintedCursor::Tool`] names icons without egui. - `pub const fn new(name: &'static str) -> Self`. The icon named `name`. - `pub fn name(&self) -> &str`. The name. -- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool, toward: Option }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId }, Hidden, IBeam }`. A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush +- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool, toward: Option }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId, badge: Option }, Hidden, IBeam }`. A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush - `pub const CENTRE_ARM: f32`. The arm of the centre mark of a circle or an outline, in points. - `pub const fn circle(radius: f32) -> Self`. A circle of `radius` points, with no centre mark and no badge. - `pub fn outline(rings: Vec>) -> Self`. App shapes as closed rings, with no centre mark and no badge. @@ -448,6 +463,7 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `pub const fn arrow_toward(dir: Vec2) -> Self`. A solid arrow turned about its hotspot to point along `dir`. - `pub const fn path_text(start: bool, end: bool) -> Self`. An I-beam across the path with a triangle toward each grabbable side. - `pub const fn pointer_tool(pointer: PointerGlyph, icon: IconId) -> Self`. `pointer` with the tool's icon below and right of it. + - `pub const fn pointer_tool_badged(pointer: PointerGlyph, icon: IconId, badge: Option) -> Self`. `pointer` with the tool's icon below and right of it, and `badge` at the icon's lower right. - `pub const fn badged(base: CursorIcon, badge: CursorBadge) -> Self`. A system cursor with a mark. - `craft_behavior::cursor::PointerGlyph`: `pub enum PointerGlyph { Crosshair, Arrow }`. The pointer of a [`PaintedCursor::PointerTool`]. - `craft_behavior::cursor::pick`: `pub fn pick(requests: &[(Cursor, CursorPriority)]) -> Option<&Cursor>`. The winning request: the highest priority, the later request on a tie. @@ -655,7 +671,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `craft_behavior::edit_history::EditHistory`: `pub struct EditHistory`. Undo and redo stacks of a value `T`, at most 100 steps. A gesture is one step: `Begin` opens it, `Commit` closes it, - `pub fn new(now: &T) -> Self`. A history that starts at `now`. - `pub fn with_budget(mut self, max: usize, weight: fn(&T) -> usize) -> Self`. The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always - - `pub fn record(&mut self, event: &EditEvent)`. Takes in one event. Events of a gesture other than the open one are ignored. + - `pub fn record(&mut self, event: &EditEvent)`. Takes in one event. Events of a gesture other than the open one are ignored. A concrete - `pub fn is_open(&self) -> bool`. A gesture is open: a caller that restores a draft waits for it to end. - `pub fn step(&mut self, now: &mut T, step: Step) -> bool`. Steps `now` back or forward. False when there is nowhere to go. An open gesture is abandoned. - `pub fn take_back(&mut self) -> Option`. Takes back the newest undo step without a redo entry, for an edit that was refused: `settled` returns to the @@ -748,6 +764,13 @@ Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the f - `craft_behavior::focus::key_owner`: `pub fn key_owner(blocked: bool, present: &[OwnerClass]) -> KeyOwner`. Key ownership, in the order blocked, `Menu`, `Recorder`, `Dialog`, `Text`, `Popup` and `PassivePopup`, - `craft_behavior::focus::route_escapes`: `pub fn route_escapes(escapes: usize, press_captured: bool) -> EscapeRouting`. Routes `escapes` Escapes of one pass: with a press captured, the first one is the press's (`escape_step`'s +## `craft_behavior::frame_step` + +The step of one pass of motion: a Hand glide, a held Zoom press and an autoscroll integrate over it. + +- `craft_behavior::frame_step::FRAME_STEP_MAX`: `pub const FRAME_STEP_MAX: f64`. The longest step motion integrates, in seconds, so a stalled pass never jumps the view. +- `craft_behavior::frame_step::frame_step`: `pub fn frame_step(dt: f64) -> f64`. The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the + ## `craft_behavior::geometry` Pure canvas geometry in document units: the transform box ([`quad`]), snapping ([`snap`]), the @@ -756,6 +779,7 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( - `craft_behavior::geometry::AspectHold`: re-export of `craft_behavior::geometry::crop::AspectHold`. - `craft_behavior::geometry::BoxAllow`: re-export of `craft_behavior::geometry::quad::BoxAllow`. - `craft_behavior::geometry::BoxDrag`: re-export of `craft_behavior::geometry::quad::BoxDrag`. +- `craft_behavior::geometry::BoxHandles`: re-export of `craft_behavior::geometry::quad::BoxHandles`. - `craft_behavior::geometry::BoxPart`: re-export of `craft_behavior::geometry::quad::BoxPart`. - `craft_behavior::geometry::BoxRules`: re-export of `craft_behavior::geometry::quad::BoxRules`. - `craft_behavior::geometry::BoxState`: re-export of `craft_behavior::geometry::quad::BoxState`. @@ -830,7 +854,7 @@ The crop frame's pure geometry: the box, where a press lands on it, what each ge - `pub fn swapped(&self) -> Self`. Width and height swapped about the centre, the angle kept (X). - `pub fn nudged(&self, part: BoxPart, by: Vec2, ratio: Option) -> Self`. The frame after an arrow key moves `part` by `by`, as a plain drag of the part would, with `ratio` held. - `pub fn crop_size(&self) -> Option<(f64, f64)>`. The size Enter would crop to: the frame's own width and height in whole document units, at least 1; `None` - - `pub fn size_ok(&self) -> bool`. Whether both sides are at least one document unit. + - `pub fn size_ok(&self, min: f64) -> bool`. Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is - `pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option`. [`resized`](Self::resized) for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the - `pub fn turned_to(&self, grab: f64, to: Point, step: Option, image: bool) -> Self`. The frame turned from this one's angle by the pointer's sweep about the centre, from direction `grab` @@ -967,15 +991,19 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub const fn new(rotate: bool, skew: bool, distort: bool) -> Self`. What the content allows: turning, skewing and distorting. - `pub const fn with_warp(mut self, warp: bool) -> Self`. Whether the content allows warping. - `craft_behavior::geometry::quad::BoxDrag`: `pub enum BoxDrag { Move, Pivot, Rotate, Scale, Distort, Perspective, Skew, SlideCorner }`. What a drag of a box part does ([`BoxRules::drag_kind`]). +- `craft_behavior::geometry::quad::BoxHandles`: `pub enum BoxHandles { All, Corners, Sides }`. Which handles of a box are shown. - `craft_behavior::geometry::quad::BoxPart`: `pub enum BoxPart { Corner(u8), Edge(u8), Pivot, Inside, Outside }`. A part of a box under the pointer or picked from the keyboard. Edge `k` joins corners `k` and - `pub const fn index(self) -> u64`. The number a part is keyed by in a canvas control's part keys: 0 inside or outside, 1 to 4 the corners, 5 to - `pub const fn from_index(index: u64) -> Option`. The part keyed by `index`: the inverse of [`index`](Self::index), with 0 the inside. -- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64, pub min_side: f64 }`. How drags change a box. +- `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64, pub min_side: f64, pub handles: BoxHandles, pub edge_band: f32 }`. How drags change a box. - `pub fn in_mode(mode: TransformMode) -> BoxRules`. The rules of `mode` with the default scale rule, a linked aspect, everything allowed and - `pub fn with_scale(mut self, scale: ScaleRule) -> BoxRules`. The rules with `scale` as the plain corner and edge drag rule. - `pub fn with_aspect_linked(mut self, linked: bool) -> BoxRules`. The rules with the options bar's aspect link on or off. - `pub fn with_allow(mut self, allow: BoxAllow) -> BoxRules`. The rules with `allow` as what the content permits. - `pub fn with_min_side(mut self, side: f64) -> BoxRules`. The rules with `side` as the minimum side of a scaled box, in document units. + - `pub fn with_handles(mut self, handles: BoxHandles) -> BoxRules`. The rules with `handles` as the handles the box shows. + - `pub fn with_edge_band(mut self, points: f32) -> BoxRules`. The rules with each side grabbed within `points` of its line ([`edge_band`](Self::edge_band)). + - `pub fn shows(&self, part: BoxPart) -> bool`. Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides - `pub fn effective_mode(&self) -> TransformMode`. The mode drags follow: a mode the content refuses scales as Free Transform does. - `pub fn allows(&self, part: BoxPart) -> bool`. Whether a drag of `part` changes the box: in Distort only the corners, the inside and the - `pub fn drag_kind(&self, part: BoxPart, mods: Mods) -> Option`. What a drag of `part` with `mods` held (as the host has them, before @@ -1005,7 +1033,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `craft_behavior::geometry::quad::Parts`: `pub struct Parts { pub w: f64, pub h: f64, pub angle: f64, pub skew_h: f64, pub skew_v: f64 }`. A box read as the options bar shows it: the starting rect scaled by `w` and `h`, skewed by - `pub const fn new(w: f64, h: f64, angle: f64, skew_h: f64, skew_v: f64) -> Self`. The readings: scale factors `w` and `h`, the `angle` in degrees and the two skews in degrees. - `craft_behavior::geometry::quad::SKEW_LIMIT`: `pub const SKEW_LIMIT: f64`. The skew fields' reach in degrees: a skew of ±90° would flatten the box (PhotoCraft's). -- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, Shape, Corners }`. What a plain corner or edge drag does. +- `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, LargerAxis, Shape, Corners }`. What a plain corner or edge drag does. - `craft_behavior::geometry::quad::TransformMode`: `pub enum TransformMode { Free, Rotate, Skew, Distort, Perspective }`. Edit › Transform's modes. - `craft_behavior::geometry::quad::bisector`: `pub fn bisector(screen: &BoxState, i: usize) -> emath::Vec2`. Corner `i` of `screen`'s unit bisector, pointing into the box; zero for a collapsed corner. The - `craft_behavior::geometry::quad::drag`: `pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState`. The box after dragging `part` from `from` to `to` (document points) with `mods` held, from the @@ -1070,7 +1098,7 @@ The `Grid` cursor: columns resolved from last pass's measurements, and the cell - `craft_behavior::grid::GridCursor`: `pub struct GridCursor`. Hands out the cells of one `Grid` pass, row-major. Cells are placed from `last` pass's measurements; this - `pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A - `pub fn sized_by_content(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor for a measuring run under a body sized from its content: each `Fill` column of `columns` is placed - - `pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self`. A cursor for the sweep that asks each column for its least: every column but a `Fixed` one is placed as a + - `pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self`. A cursor for the sweep that asks each column for its least: the cells of every `Content` and `Fill` column - `pub fn each_alone(mut self) -> Self`. The cursor with each `Content` column measuring in the room the other columns leave at their least, whatever - `pub fn short(&self) -> bool`. Whether the columns, as this sweep measured them, do not fit beside each other: the columns that do not share - `pub fn cell(&mut self, size: Vec2) -> Rect`. The cell of the next child, whose measured size is `size`. @@ -1107,15 +1135,16 @@ Hit shapes, their priority and the arena's resolve rule (8.3). - `pub fn hit(&self, point: Pos2) -> bool`. Whether `point` hits the shape. - `craft_behavior::hit::LINE_REACH`: `pub const LINE_REACH: f32`. How far from a line a point still hits it, in points. - `craft_behavior::hit::ResolveFor`: `pub enum ResolveFor { Press, Hover }`. What a resolution is for. -- `craft_behavior::hit::Shape`: `pub struct Shape { pub shape: HitShape, pub sense: Sense, pub owner: O, pub part: Option, pub priority: HitPriority, pub position: u32, pub local: bool, pub min_across: f32 }`. One registered shape of the shape record: a root's, a member's or a part's. +- `craft_behavior::hit::Shape`: `pub struct Shape { pub shape: HitShape, pub sense: Sense, pub owner: O, pub part: Option, pub priority: HitPriority, pub position: u32, pub local: bool, pub min_across: f32, pub stacking: u32, pub drag_to_root: bool }`. One registered shape of the shape record: a root's, a member's or a part's. - `pub fn translated(&self, by: Vec2) -> Self`. The shape moved by `by`. - `pub fn snapped(&self, to: &Shape, within: f32) -> Self`. The shape with its geometry and least size across taken from `to`'s where they lie within `within` points - `pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self`. A shape of `owner` at stack `position`. - `pub const fn min_across(mut self, across: f32) -> Self`. The hit area is at least `across` points wide and high. + - `pub const fn stacking(mut self, order: u32) -> Self`. The shape's stacking order among shapes of its priority: the higher order wins before the nearest centre. - `pub const fn local(mut self, local: bool) -> Self`. The shape lies in the body layer's space. - `pub fn hits(&self, point: Pos2) -> bool`. Whether `point` lies in the hit area: the shape grown to be at least its `min_across` wide and high. The -- `craft_behavior::hit::Winner`: `pub struct Winner { pub index: usize, pub owner: O, pub part: Option, pub sense: Sense, pub local: bool }`. The shape that won a resolution. -- `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last +- `craft_behavior::hit::Winner`: `pub struct Winner { pub index: usize, pub owner: O, pub part: Option, pub sense: Sense, pub local: bool, pub drag_to_root: bool }`. The shape that won a resolution. +- `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest - `craft_behavior::hit::resolve_mapped`: `pub fn resolve_mapped(shapes: &[Shape], point: Pos2, what: ResolveFor, to_local: impl Fn(Pos2) -> Pos2) -> Option>`. [`resolve`] where shapes with `local` set are tested at `to_local(point)`. ## `craft_behavior::hold_repeat` @@ -1168,6 +1197,7 @@ Item geometry: where each item of a collection sits for a scroll offset and view - `fn visible(&self, offset: ScrollPos, view: Vec2, out: &mut Vec)`. The indices of the items that intersect a viewport of size `view` scrolled to `offset`, ascending. - `fn rect(&self, at: usize, offset: ScrollPos) -> Rect`. The rect of item `at`. - `fn hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item under `point`. + - `fn drop_hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item whose drop area contains `point`. Layouts with visible gaps can include those in a drop area while - `fn nav(&self) -> NavShape`. How arrow keys move through the items. - `fn row_len(&self, _row: usize) -> Option`. `NavShape::RaggedGrid`: the number of items in `row`, rows holding consecutive items and a run of hidden items - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows @@ -1242,6 +1272,7 @@ Where a collection's items come from: the data traits and the one way to show a - `fn open(&self, _at: usize) -> bool`. Whether the children of entry `at` show. - `fn is_section(&self, _at: usize) -> bool`. Whether entry `at` is a section header, which navigation skips. - `fn section_stop(&self, _at: usize) -> bool`. Whether section `at` is a stop of navigation: it holds the lead, takes Enter, the context-menu key and a + - `fn selectable_section(&self, _at: usize) -> bool`. Whether a section stop also represents an item that keyboard selection can pick or extend over. - `fn section_stops_before(&self, _at: usize) -> usize`. How many section stops (`section_stop`) come before entry `at`. They are not members of the set of items, so - `fn enabled(&self, _at: usize) -> bool`. Whether entry `at` can take the lead. - `fn text(&self, _at: usize) -> Option>`. The text type-ahead matches entry `at` against. @@ -1265,13 +1296,16 @@ Where a collection's items come from: the data traits and the one way to show a The key table (spec 9.2): the one place that maps a key press to an intent and modifiers to `MoveMods`. +- `craft_behavior::keys::ALT_ARROW_KEYS`: `pub const ALT_ARROW_KEYS: [Chord; 4]`. The four Alt+arrow chords of `ReorderKeys::AltArrows`. +- `craft_behavior::keys::CopyKeys`: `pub enum CopyKeys { Alt, Platform }`. Which held key turns a drag into a copy over a target. - `craft_behavior::keys::DropOperation`: `pub enum DropOperation { Move, Copy, Link }`. What a drop of a dragged payload does with it. -- `craft_behavior::keys::KeyRole`: `pub struct KeyRole { pub resettable: bool, pub space: bool, pub multi_select: bool, pub reorderable: bool, pub rename: bool, pub pages: bool, pub nudge: bool, pub document: bool, pub type_ahead: bool, pub digits: bool, pub value: bool, pub text: bool, pub moves: bool, pub deletes: bool, pub stacked: bool, pub owner_arrows: bool, pub home_row: usize }`. What the focused stop is, as far as the table's rows differ. +- `craft_behavior::keys::KeyRole`: `pub struct KeyRole { pub resettable: bool, pub space: bool, pub multi_select: bool, pub reorderable: Option, pub reorder_axis: Axis, pub rename: bool, pub pages: bool, pub nudge: bool, pub document: bool, pub type_ahead: bool, pub digits: bool, pub value: bool, pub text: bool, pub moves: bool, pub deletes: bool, pub stacked: bool, pub owner_arrows: bool, pub home_row: usize }`. What the focused stop is, as far as the table's rows differ. - `pub const fn new() -> KeyRole`. A role with no special rows. - `pub const fn resettable(mut self, on: bool) -> Self`. Delete resets the control. - `pub const fn space(mut self, on: bool) -> Self`. Space is the component's own intent. - `pub const fn multi_select(mut self, on: bool) -> Self`. Ctrl+Space toggles the lead's pick. - - `pub const fn reorderable(mut self, on: bool) -> Self`. The stacking keys move the selected items. + - `pub const fn reorderable(mut self, keys: Option) -> Self`. The scheme's keys move the selected items; `None` when the stop does not reorder. + - `pub const fn reorder_axis(mut self, axis: Axis) -> Self`. The axis the order is laid out along. - `pub const fn rename(mut self, on: bool) -> Self`. Rename has its key. - `pub const fn pages(mut self, on: bool) -> Self`. Ctrl+Tab switches pages. - `pub const fn nudge(mut self, on: bool) -> Self`. Arrows are nudges, not moves. @@ -1286,9 +1320,10 @@ The key table (spec 9.2): the one place that maps a key press to an intent and m - `pub const fn home_row(mut self, row: usize) -> Self`. Ctrl or Cmd with Home goes to item `row`. - `pub const fn text(mut self, on: bool) -> Self`. The stop is a text part. - `craft_behavior::keys::REORDER_KEYS`: `pub const REORDER_KEYS: [Chord; 6]`. The stacking keys (Photoshop's Bring Forward and Send Backward): Cmd+] moves the selected items one place toward the -- `craft_behavior::keys::drop_operation`: `pub fn drop_operation(os: Os, mods: Mods) -> DropOperation`. The drop operation the held modifiers pick. +- `craft_behavior::keys::ReorderKeys`: `pub enum ReorderKeys { Stacking, AltArrows }`. The named key scheme of a reorderable collection. +- `craft_behavior::keys::drop_operation`: `pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation`. The drop operation the held modifiers pick over a target that copies with `copy`. Link is Ctrl+Shift, Cmd+Option on - `craft_behavior::keys::intent`: `pub fn intent(os: Os, key: Key, mods: Mods, role: KeyRole) -> Option`. The intent a key press has for a stop of `role`, if any. `Enter` and `Space` as activation are not rows: -- `craft_behavior::keys::reorder_intent`: `pub fn reorder_intent(key: Key, mods: Mods) -> Option`. The `Intent::MoveItem` a stacking key asks for, `None` for any other press. +- `craft_behavior::keys::reorder_intent`: `pub fn reorder_intent(key: Key, mods: Mods, keys: ReorderKeys, axis: Axis) -> Option`. The `Intent::MoveItem` a key of the scheme `keys` asks for in an order laid out along `axis`, `None` for any other - `craft_behavior::keys::split_digits`: `pub fn split_digits(text: &str) -> (Vec, String)`. Typed `text` split for a role that takes digits: the ASCII digits it holds, in order, and the text without them. - `craft_behavior::keys::toward_end`: `pub fn toward_end(front: bool, axis: Axis) -> bool`. Whether a move toward the front goes toward the end of an order laid out along `axis`. The front of a vertical @@ -1312,6 +1347,20 @@ The tolerance rule of layout memory: when a measured size asks for a discard pas - `craft_behavior::layout_memory::measure_tolerance`: `pub fn measure_tolerance(pixels_per_point: f32) -> f32`. The tolerance in points under which a measured size equals the one placement used: half a physical pixel. - `craft_behavior::layout_memory::measured_change_asks_for_discard`: `pub fn measured_change_asks_for_discard(recorded: Option, real: Vec2, changed_last_frame: bool, tolerance: f32) -> bool`. Whether a measured size asks for a discard pass. `recorded` is the size placement used this frame +## `craft_behavior::middle_scroll` + +The middle button's auto-scroll latch: the gesture state of one middle press. + +- `craft_behavior::middle_scroll::MiddleButton`: `pub enum MiddleButton { Pan, AutoScroll }`. What the middle button does over a scroll area. +- `craft_behavior::middle_scroll::MiddleScroll`: `pub struct MiddleScroll`. The auto-scroll latch of one middle press. + - `pub fn press(&mut self, at: Pos2, inside: bool)`. A middle press: inside the scroll area it latches at `at`; a second press ends the latch. + - `pub fn release(&mut self)`. The button went up: after two held passes with the pointer past the dead zone the latch ends; an earlier + - `pub fn swallows(&mut self, phase: PressPhase) -> bool`. Whether a press's `phase` belongs to the press that ended a latch and so reaches nothing else: true for the + - `pub fn cancel(&mut self)`. Ends the latch. + - `pub fn step(&mut self, pointer: Pos2, held: bool, dt: f64, invert: bool) -> Vec2`. One pass: with this pass's `pointer` and `held` state it counts the held passes past the 15 pt dead zone and + - `pub fn anchor(&self) -> Option`. Where the latch is anchored, `None` when there is none. + - `pub fn active(&self) -> bool`. Whether a latch is active. + ## `craft_behavior::monitor` The connected monitors, as every window placement reads them. @@ -1491,6 +1540,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `craft_behavior::press::PointerSample`: `pub struct PointerSample { pub pressure: f32, pub tilt: [f32; 2], pub rotation: f32, pub eraser: bool, pub wheel: Option }`. Pressure and tilt of the current contact. - `pub const fn new(pressure: f32) -> Self`. A sample with no tilt or rotation. - `pub fn sanitized(self) -> Self`. The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value +- `craft_behavior::press::PressAside`: `pub struct PressAside { pub target: T, pub start: PressStart, pub pos: Pos2 }`. A secondary press made and released while a primary press was open ([`PressStep::aside`]). Its target is the one - `craft_behavior::press::PressCancel`: `pub enum PressCancel { Escape, FocusLost, Disabled, Removed, Host, Gesture }`. Why a captured press ended without a release. - `craft_behavior::press::PressMachine`: `pub struct PressMachine`. The press lifecycle of one root: the press winner it picked, kept until release or cancel. - `pub const fn new() -> Self`. A machine with no press. @@ -1500,7 +1550,8 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn start(&self) -> Option`. The press the open press began as. - `pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart)`. Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next - `pub fn release_held(&self) -> bool`. Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may - - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option<(T, Sense)>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None` + - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed + - `pub fn hand_over(&mut self, target: T, sense: Sense) -> Option>`. Makes `target` the open press's target in the pass that reported `passes`, dragging from the same - `craft_behavior::press::PressPhase`: `pub enum PressPhase { Idle, Hover, Down { start: PressStart }, Held { start: PressStart, pos: Pos2 }, DragStart { start: PressStart, pos: Pos2 }, Drag { start: PressStart, pos: Pos2, delta: Vec2 }, Release { start: PressStart, pos: Pos2, click: bool }, Cancel { start: PressStart, reason: PressCancel } }`. One part's press state in one pass. - `pub const fn is_press(&self) -> bool`. A press is in progress or just ended: not `Idle` or `Hover`. - `pub const fn start(&self) -> Option`. The press the phase belongs to. @@ -1508,16 +1559,20 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn is_drag(&self) -> bool`. Whether the phase is a drag in progress. - `pub const fn is_click(&self) -> bool`. Whether the phase is a click: a release within slop. - `pub fn mapped(self, point: impl Fn(Pos2) -> Pos2, delta: impl Fn(Vec2) -> Vec2) -> PressPhase`. The phase with its positions mapped by `point` and its drag delta by `delta`, for a part whose space +- `craft_behavior::press::PressPick`: `pub struct PressPick { pub target: T, pub sense: Sense, pub passed: bool }`. The press winner a root picks at a press position, as [`PressMachine::step`]'s `pick` returns it. + - `pub fn new(target: T, sense: Sense) -> Self`. `target`, sensing `sense`, takes the press. + - `pub fn passed(mut self) -> Self`. The press's click went to a shape above that passes its drag to this target. - `craft_behavior::press::PressStart`: `pub struct PressStart { pub origin: Pos2, pub button: PointerButton, pub time: f64, pub clicks: u32 }`. Where and when a press began. - `pub const fn new(origin: Pos2, button: PointerButton, time: f64, clicks: u32) -> Self`. A press of `button` at `origin`. -- `craft_behavior::press::PressState`: `pub struct PressState { pub phase: PressPhase, pub mods: Mods, pub sample: Option, pub captured: bool }`. A part's phase, the modifiers held, the pen sample and whether it holds the pointer. +- `craft_behavior::press::PressState`: `pub struct PressState { pub phase: PressPhase, pub mods: Mods, pub sample: Option, pub captured: bool, pub context: Option }`. A part's phase, the modifiers held, the pen sample and whether it holds the pointer. - `pub const IDLE: PressState`. A part with no press history. - - `pub const fn new(phase: PressPhase) -> Self`. A state in `phase` with no modifiers, sample or capture. + - `pub const fn new(phase: PressPhase) -> Self`. A state in `phase` with no modifiers, sample, capture or aside context request. + - `pub const fn context(mut self, at: Option) -> Self`. The aside secondary press that came up on the part at `at` in this pass. - `pub const fn mods(mut self, mods: Mods) -> Self`. The modifiers held. - `pub const fn sample(mut self, sample: Option) -> Self`. The pen sample of the contact. - `pub const fn captured(mut self, captured: bool) -> Self`. Whether a drag holds the pointer. - `pub const fn double_pressed(&self) -> bool`. Whether the phase is the `Down` of the second press of a double click: true once, false while the button is -- `craft_behavior::press::PressStep`: `pub struct PressStep { pub target: Option, pub phase: Option, pub dragging: bool, pub activated: Option }`. What one pass did to the press. +- `craft_behavior::press::PressStep`: `pub struct PressStep { pub target: Option, pub phase: Option, pub dragging: bool, pub activated: Option, pub passes: Option, pub aside: Option> }`. What one pass did to the press. - `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f64, mods: Mods, slop: f32) -> u32`. The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, ## `craft_behavior::quantity` @@ -1535,6 +1590,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn decimal_separator(&self) -> char`. The decimal separator the reader reads and writes. - `pub fn read(&self, text: &str, start: Option) -> Result`. The value of `text`. `start` is the value relative input applies to. - `pub fn read_tagged(&self, text: &str, start: Option) -> Result<(f64, Option), NotAValue>`. The value of `text` and the tag of the unit its last quantity named (`None` for a bare number or an untagged + - `pub fn share(&self, text: &str) -> Option`. The fraction a lone percentage writes (`50%` is 0.5): a number and `%`, with no sign, unit or operator; - `craft_behavior::quantity::is_unit_spelling`: `pub fn is_unit_spelling(spelling: &str) -> bool`. Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can ## `craft_behavior::role_rule` @@ -1776,7 +1832,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. - `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2 }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. - `pub const fn touch_zoom(mut self, zoom: f32) -> Self`. The same gesture with the two-finger touch zoom factor `zoom`. @@ -1785,6 +1841,11 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli - `pub const fn touch_pan(mut self, pan: Vec2) -> Self`. The same gesture with the two-finger touch movement `pan`, in points. - `pub const fn source(mut self, source: WheelSource) -> Self`. The same gesture from `source`. - `pub const fn at(mut self, at: Pos2) -> Self`. The same gesture with the pointer at `at`. +- `craft_behavior::wheel::WheelEase`: `pub struct WheelEase`. The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. + - `pub fn feed(&mut self, pan: Vec2, now: f64)`. Adds the line pan `pan` of this pass, at time `now`, to the owed motion; a burst of notches under 0.08 s apart + - `pub fn cancel_axis(&mut self, x: bool, y: bool)`. Drops the owed motion on the axes marked. + - `pub fn step(&mut self, now: f64) -> Vec2`. The step this pass pays at time `now`: `1 − 0.1^(dt/0.1)` of the owed motion, with `dt` since the last paid pass. + - `pub fn owes(&self) -> bool`. Whether motion is still owed. - `craft_behavior::wheel::WheelFocus`: `pub struct WheelFocus { pub taker: Option, pub app_field: bool, pub by_position: bool }`. Who holds key focus, as the split reads it. - `pub const fn new(taker: Option) -> Self`. Focus on `taker`, or on nothing that takes the wheel. - `pub const fn app_field(mut self, on: bool) -> Self`. The same focus, in a text field the app drew itself when `on`. @@ -1850,7 +1911,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn measures_items(&self) -> bool`. Whether the layout sizes its items from their own measure: the items step measures every item at its ideal - `fn dress_inputs(&self) -> u64`. What `dress` reads of the collection, hashed: a kept measure of the items serves only while it is the same. - `fn ideal_width(&self, _item: Option, _rows: usize, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of - - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. + - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env, _kept: Option<&Self::Key>,) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. `kept` is the - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this - `fn rename_editor(&mut self, _ui: &mut Ui, _draft: Bind<'_, String>, _label: Rect, _name: &str) -> Option>`. The rename editor at `label`: the label rect the renaming item reports (`ItemOutput::label_rect`), else its row. - `fn hosts_header(&self, _column: &ColumnKey) -> bool`. Whether the collection hosts a component in the header cell of `column`: the header then calls `header_cell` @@ -1861,7 +1922,8 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn accepts(&self, _drag: &ListDrag, _over: Option<&Self::Key>, _insert: usize) -> bool`. Whether the collection's own dragged items may land before `insert` (a position of the display order, `over` is - `fn drops(&self) -> &[DropKind<'_, Self::Key>]`. What the collection takes from drags that did not start in it, in order: the first kind that takes the drag's - `fn edge_press(&self) -> Option<&EdgePress<'_, Self::Key>>`. The press on the line between two adjacent rows the collection takes, reported as - - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): it reports + - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): the items step reports + - `fn zoom_anchor(&self, _wheel: Option) -> Option`. The point whose row stays in place across a zoom step this collection takes in the current pass, in screen - `fn empty_height(&self, width: f32, ui: &Ui, cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. The - `fn empty(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>)`. The empty state at the rect the item step placed. The default shows `CollectionProps::empty`. - `craft_ui::contract::Component`: `pub trait Component: Meta + Sized`. The core trait: every UI type is a `Component`. @@ -1873,6 +1935,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts - `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except - `const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy`. The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its + - `fn focus_scope(&self) -> crate::runtime::focus::FocusPolicy`. The focus scope this instance runs in. The default is `FOCUS_SCOPE`; a component whose scope is a choice of its - `const KEYS: crate::runtime::focus::KeyUse`. Keys the focused component keeps from egui and the shortcut dispatcher. - `fn keys(&self) -> crate::runtime::focus::KeyUse`. The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends - `const SHOWS_LABEL: bool`. Whether the component paints its label as visible text. `false` for a face that shows only an icon or a @@ -1886,6 +1949,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn shows_label(&self) -> bool`. Whether this instance paints its label as visible text; `SHOWS_LABEL` unless an instance prop decides, as - `fn label_detail(&self) -> Option`. The muted line a `LABELLED_AFTER` control's label shows after its text (`SideLabel::detail`), as a radio's - `fn paint_outset(_tokens: &crate::style::UiTokens) -> f32`. How far the component paints outside its rect by design, in points (a graph node's ports sit on its edge). + - `fn default_variant(_env: &crate::runtime::env::Env) -> Option`. The variant an instance that asks for none takes in `env`; `None` takes the style's first. A variant the caller - `fn style(cx: &StyleCx<'_>, key: Self::StyleKey) -> Self::Style`. Pure function of the resolved context and the key. - `fn padding(&self, _rect: Rect, style: &Self::Style) -> craft_behavior::Insets`. The insets from `rect` to the content rect where the component is shown: the style's padding. A component - `fn measure(&mut self, _cx: &MeasureCx<'_, Self>) -> Vec2`. Content size only; the pipeline adds padding and minimum size. @@ -1992,6 +2056,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn take_pick_answer(&self, ticket: craft_host::PickId) -> Option`. The host file service's answer to the picker `ticket`, taken once. A measuring run gets none and leaves - `pub fn is_exiting(&self) -> bool`. Whether the container has closed and its body only stays on screen while it fades out. `is_open` reads true - `pub fn field_message(&self) -> Option<(Message, craft_theme::variant::Tone)>`. The validity message of the first control in the container's label scope, recorded last frame, with the + - `pub fn moving(&self) -> bool`. Whether a drag of the container's move band (`DragBand::Move`) moves its layer in this pass, from the pass the - `pub fn is_open(&self) -> bool`. Whether the body is open. - `pub fn open(&mut self) -> &mut bool`. The open state: a title row's disclosure binds to it, and step 15 writes a change to its owner. - `pub fn gate(&mut self) -> Option<&mut bool>`. The gate's shown copy, for a container whose value is a bool: a title row's check box binds to it, and @@ -2014,20 +2079,26 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. - `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. +- `craft_ui::contract::CaptionColumn`: `pub struct CaptionColumn`. Whether the beside captions of a [`LabelScheme::Inline`] form share one column. Off (the default), each caption is + - `pub const SHARED: CaptionColumn`. The captions share one column. + - `pub const OWN: CaptionColumn`. Each caption is as wide as its own text (the default). + - `pub const fn shared(self) -> bool`. Whether the captions share one column. +- `craft_ui::contract::CaptionInk`: `pub enum CaptionInk { Muted, Normal }`. The ink of a side label's name, other than a link's ([`LinkLabelInk`]) and the text after a check box or a radio, - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. - `pub const fn new() -> Self`. A collapsible body that starts open, animated. - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. -- `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection { change: SelectionChange, by: LeadSource, mods: craft_keymap::Mods }, Picked { key: K, mods: craft_keymap::Mods }, LeadMoved { key: K, by: LeadSource }, Activate(K), Rested(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option