Merge pull request #3438 from storytold/design-port/pr-input-focus

Input and focus fixes: wheel over text fields, Scroll Into View on list rows, click modifiers, shown-only chords, face names, right-click outside menus, mixed sliders
This commit is contained in:
aiongg authored and GitHub committed 2026-11-29 10:52:12 -05:00
commit 9949e08d6f
37 files changed
+627 -116

No files matched your search

+11 -1
View File
@@ -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 {
+6 -3
View File
@@ -455,14 +455,17 @@ impl<O> WheelTaker<O> {
/// 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<Self> {
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)
}
+48
View File
@@ -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, PointerKind, 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,
@@ -17,6 +18,7 @@ use craft_ui::contract::{
};
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 _};
@@ -1811,6 +1813,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::<CanvasView>));
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::<Vec<_>>();
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)] {
@@ -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,
}
+4
View File
@@ -274,6 +274,9 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> {
page_reveal: Option<usize>,
/// The row this pass scrolls into view, placed before the rows are built (`place_reveal`).
revealing: Option<usize>,
/// 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<usize>,
/// 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.
@@ -341,6 +344,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,
@@ -77,10 +77,11 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
access::report_sub(ctx, &decl);
}
/// AccessKit requests on an item row's node or on a section row's collection node (`report_section_node`), while the
/// collection is enabled: 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 it does not select. Expand and
/// Collapse open and close rows with children.
/// AccessKit requests on an item or section row's collection node (`report_section_node`), while the collection
/// and row are enabled: 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 it does not select. Expand and
/// Collapse open and close rows with children. Scroll Into View brings the row into view without moving the lead or
/// focus. If the collection scrolls itself, the outer scroll owner then shows the row's visible piece.
pub(super) fn node_by_access(
&mut self,
comp: &C,
@@ -135,6 +136,12 @@ impl<C: Collection> 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 {
@@ -246,7 +246,7 @@ impl<C: Collection> ShapeHooks<C> 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
@@ -399,6 +399,9 @@ impl<C: Collection> ShapeHooks<C> 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());
@@ -58,6 +58,9 @@ impl<C: Collection> 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)
@@ -233,7 +236,7 @@ impl<C: Collection> 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);
@@ -248,7 +251,7 @@ impl<C: Collection> 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
@@ -276,7 +279,7 @@ impl<C: Collection> 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
@@ -299,9 +302,9 @@ impl<C: Collection> 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);
}
}
}
@@ -343,7 +346,7 @@ impl<C: Collection> 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);
@@ -34,9 +34,12 @@ 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) as the lone point it landed on; the record stands
// for the layers the pass already had, and presses inside the family and its anchors never get here.
if dismiss.outside == Outside::Absorb {
if overlay::absorbed_press(ctx).is_some() {
// A layer that appears in this pass opened after the press was made, so the press is not outside it: `opening`
// is what tells it from the layers the record stands for.
if overlay::absorbed_press(ctx).is_some() && !overlay::opening(ctx, layer.id) {
return Some(CloseReason::Outside);
}
} else if press_outside(ctx, layer, rect, anchor) {
@@ -23,7 +23,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,
}
@@ -272,7 +273,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);
+6 -3
View File
@@ -802,7 +802,10 @@ 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 ended the primary press (`PointerFrame::click_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, and another
/// button's release later in that pass does not take its modifiers.
fn activation_of(ctx: &Context, ui: &Ui, rect: Rect, resolved: &Resolved<'_>, keyed: bool, root_sense: Sense, clicked: bool) -> Option<Activation> {
if !steps::takes_activation(resolved) {
return None;
@@ -818,7 +821,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.click_mods)),
})
}
@@ -1046,7 +1049,7 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, (host_at, place): (Option<
};
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);
+7 -1
View File
@@ -780,12 +780,18 @@ pub(crate) fn paint_face<C: Show>(
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,
@@ -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::<ScrollMoves, _>(&core.ctx, |queue| queue.0.extend(moves.into_iter().map(|(mv, mods)| (owner, mv, mods, false))));
if reveal {
pass_state::with::<Reveals, _>(&core.ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(core.rect) }));
if let Some(rect) = reveal {
pass_state::with::<Reveals, _>(&core.ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(rect) }));
}
repaint::request(&core.ctx);
}
+27 -34
View File
@@ -4,42 +4,35 @@ 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 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.
pub(crate) fn register_wheel(
ctx: &Context,
id: Id,
rect: Rect,
sensed: Option<craft_behavior::WheelTaker<Id>>,
value_control: bool,
text: bool,
scope: WheelScope,
) {
let free = sensed.is_some() && scope == WheelScope::Free;
let directional = sensed.is_some() && value_control && scope == WheelScope::Directional;
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)));
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))
.horizontal(taker.horizontal || directional)
.directional(directional),
);
}
/// 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. In a
/// `WheelScope::Directional` scope, a value control that senses the wheel also takes horizontal intent, and takes
/// vertical intent only while armed.
pub(crate) fn register_wheel(ctx: &Context, sensed: Option<craft_behavior::WheelTaker<Id>>, value_control: bool, text: bool, scope: WheelScope) {
let Some(taker) = sensed else { return };
let free = !taker.gated && scope == WheelScope::Free;
let directional = value_control && scope == WheelScope::Directional;
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))
.horizontal(taker.horizontal || directional)
.directional(directional),
);
}
/// The part states: each part's press and hover from the sensing core, with its own flags.
+2 -1
View File
@@ -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,
+12
View File
@@ -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<String> {
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]
@@ -111,8 +111,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),
};
@@ -324,6 +324,9 @@ pub(crate) struct PointerRead {
pub release: Option<PointerButton>,
/// Where the pass's last button release went up, and its modifiers.
pub released_at: Option<(Pos2, Mods)>,
/// The modifiers of the release that ended the primary press, whatever else went up in the pass after it: a
/// primary click reads these.
pub click_mods: Option<Mods>,
/// The last press of a button other than the primary one: the button and where it went down.
pub other_press: Option<(PointerButton, Pos2)>,
/// Whether the primary button went down in this pass.
@@ -399,6 +402,7 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead {
let mut touch_sample = None;
let mut release = None;
let mut released_at = None;
let mut click_mods = None;
let mut touches = Vec::new();
let mut other_press = None;
let mut rotation = 0.0;
@@ -449,10 +453,14 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead {
Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } => {
released_at = Some((*pos, Mods::from_egui(modifiers, os)));
if barrel_press {
// The contact that ends here was the barrel's, whose press went down as the secondary one.
barrel_press = false;
release = Some(PointerButton::Secondary);
events.push(PointerEvent::released_by(PointerButton::Secondary, *pos));
} else {
// The primary press ends here, so a click of it reads this release's modifiers even when
// another button's release overwrites `released_at` in the same pass.
click_mods = Some(Mods::from_egui(modifiers, os));
release = Some(PointerButton::Primary);
events.push(PointerEvent::released(*pos));
}
@@ -517,6 +525,7 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead {
buttons,
release,
released_at,
click_mods,
touches,
other_press,
primary_pressed: input.pointer.primary_pressed() && !barrel_pressed,
+1 -1
View File
@@ -818,7 +818,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) {
PerViewport::<ViewportRecord>::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);
+12 -8
View File
@@ -170,7 +170,7 @@ pub struct OpenEntry {
pub(crate) cover: Option<Layer>,
/// 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,
/// A command run from outside it closes it (`Dismiss::commands`).
pub(crate) closes_on_commands: bool,
@@ -313,7 +313,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<Vec<Rect>>,
/// 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<Pos2>,
/// The top live modal layer of the last finished pass in this viewport.
top_modal: Option<TopModal>,
@@ -747,18 +747,20 @@ 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. The record is for the layers open when the press was made: a layer that appears
/// in this pass was not, and its dismissal reads none of it (`opening`). 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,
});
@@ -768,7 +770,9 @@ 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: the lone point it landed on, for the layers the pass
/// showed before it. `opening` is how a layer that appears in the pass tells it is none of those. A tracked input
/// (`Input::Press`).
pub(crate) fn absorbed_press(ctx: &Context) -> Option<Pos2> {
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press);
absorbed_press_raw(ctx)
+8 -2
View File
@@ -56,6 +56,10 @@ pub struct PointerFrame {
/// The modifiers of the pass's last button release, with the latched ones added; the held `mods` in a pass with no
/// release and in a rerun pass. The one source of a pick's and a drop's modifiers.
pub pick_mods: Mods,
/// The modifiers of the release that ended the primary press, with the latched ones added; the held `mods` in a
/// pass whose click completes without one (a release held for the pass after it). A click's activation reads these:
/// a release of another button later in the same pass overwrites `pick_mods`, never this.
pub click_mods: Mods,
/// Where the pass's last button release went up; the latest `pos` in a pass with no release and in a rerun pass. The
/// one source of a drop's position: a pointer that moves on or leaves the window after the release in the same
/// frame does not move the drop.
@@ -378,6 +382,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) {
release: read.release,
mods,
pick_mods: read.released_at.map_or(mods, |(_, released)| with_latched(released, latched)),
click_mods: read.click_mods.map_or(mods, |released| with_latched(released, latched)),
pick_pos: read.released_at.map_or(read.pos, |(at, _)| Some(at)),
multi_tap: tap,
time: read.time,
@@ -421,8 +426,8 @@ 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. The buttons
// held are part of the press state ([`press_state`]) too.
// Track held buttons as part of the press state. A press, release or recorded outside press bumps it;
// of the outside presses the layer stack records, only a primary press is taken before egui sees it.
inputs::observe(ctx, Input::Press, frame.buttons);
if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() {
inputs::bump(ctx, Input::Press);
@@ -584,6 +589,7 @@ pub(crate) fn frame_raw(ctx: &Context) -> PointerFrame {
release: None,
mods: Mods::NONE,
pick_mods: Mods::NONE,
click_mods: Mods::NONE,
pick_pos: None,
multi_tap: None,
time: 0.0,
+65 -1
View File
@@ -24,6 +24,8 @@ struct Log {
claimed: Vec<Chord>,
/// `pointer::frame(..).mods` of every pass.
pointer: Vec<Mods>,
/// `pointer::frame(..).pick_mods` of every pass: what a pick and a drop read.
pick: Vec<Mods>,
}
/// A focusable button that logs its activations' modifiers and the claimed chords it takes.
@@ -79,7 +81,10 @@ impl Rig {
fn show(&self, ui: &mut Ui) {
let response = LatchProbe { common: Common::new(), log: &self.log }.id_salt("latch").show(ui);
self.shown.set(Some((response.id, response.rect)));
self.log.borrow_mut().pointer.push(craft_ui::runtime::pointer::frame(ui.ctx()).mods);
let frame = craft_ui::runtime::pointer::frame(ui.ctx());
let mut log = self.log.borrow_mut();
log.pointer.push(frame.mods);
log.pick.push(frame.pick_mods);
if self.discard.take() {
ui.ctx().request_discard("the trial reruns the pass");
}
@@ -156,3 +161,62 @@ 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);
}
/// A press or release of `button` at `at`, carrying `modifiers`.
fn pointer_button(at: Pos2, button: egui::PointerButton, pressed: bool, modifiers: Modifiers) -> egui::Event {
egui::Event::PointerButton { pos: at, button, pressed, modifiers }
}
#[trial]
fn an_alt_click_keeps_its_alt_when_a_plain_secondary_release_follows() {
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, then an unmodified secondary release in the same pass. The click completes, and it carries
// the Alt of the release that ended its own press, which is not the pass's last release.
let alt = |pressed| pointer_button(at, egui::PointerButton::Primary, pressed, Modifiers::ALT);
let secondary = pointer_button(at, egui::PointerButton::Secondary, false, Modifiers::NONE);
frames.frame(vec![alt(true), alt(false), secondary], |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 Alt of the release that ended the primary press");
assert!(log.pick.iter().all(|mods| !mods.alt), "a pick and a drop read the pass's last release, which was the secondary's: {:?}", log.pick);
}
#[trial]
fn a_plain_click_takes_no_modifier_from_a_secondary_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 plain quick click, then a Shift-carrying secondary release in the same pass: the click gains no Shift.
let plain = |pressed| pointer_button(at, egui::PointerButton::Primary, pressed, Modifiers::NONE);
let secondary = pointer_button(at, egui::PointerButton::Secondary, false, Modifiers::SHIFT);
frames.frame(vec![plain(true), plain(false), secondary], |ui| rig.show(ui));
frames.idle(1, |ui| rig.show(ui));
let log = rig.log.borrow();
assert_eq!(log.activations, [Mods::NONE], "the activation carries the plain release of its own press");
assert!(log.pick.contains(&Mods::SHIFT), "a pick and a drop read the pass's last release, which carried Shift: {:?}", log.pick);
}
+19
View File
@@ -318,6 +318,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";
+2 -2
View File
@@ -85,8 +85,8 @@ impl<T: Value> Outcome for MenuPick<T> {
}
}
/// 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() };
@@ -196,10 +196,10 @@ impl Component for RangeSlider<'_> {
Vec2::new(cx.style.length.max(labels), 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.
+11 -7
View File
@@ -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::{
@@ -361,7 +361,11 @@ impl Component for Slider<'_> {
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)),
};
// Multi-clicks keep the legacy track path: reset wins on Down, and a later drag
// can still begin from the reset value through the existing DragStart handling.
let follow_track_on_down = self.track_press == TrackPress::OnPress
@@ -425,8 +429,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));
}
}
@@ -977,10 +977,10 @@ impl<const N: usize> 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>) {
@@ -1,10 +1,16 @@
//! 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 _, 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::{Key, Modifiers};
use egui::{Id, Key, Modifiers, Rect, Vec2};
use std::cell::Cell;
use std::rc::Rc;
#[trial]
fn scroll_into_view_moves_no_focus() {
@@ -22,3 +28,64 @@ 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::NULL.with("rows");
let mut fixture = Fixture::new(move |ui| {
let keys: Vec<usize> = (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:?}");
}
/// 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());
}
+22 -1
View File
@@ -4,10 +4,11 @@
//! the app runs itself), and a picture in the leading 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};
@@ -1203,6 +1204,26 @@ 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() {
// Not a Ctrl+Alt+F-key: Linux reserves those for its virtual consoles, so the keymap would drop the default and the
// opener would show no chord.
let find = CommandDef::new(CommandRef::new("demo.find"), "Find", Scope::app())
.with_default(Binding::parse("Cmd+Alt+K").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+K").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.
+6 -3
View File
@@ -16,7 +16,8 @@ struct Rig {
}
fn entries() -> Vec<HelpEntry> {
// The help rows show their command's label, so each entry has its own command.
// A help row shows its entry's label and runs its command; the results keep one row per command, so each entry has
// its own.
vec![
HelpEntry::new(EditCommands::Paste, "Café").with_path(["Edit"]),
HelpEntry::new(EditCommands::Copy, "Copy").with_english("Duplicate").with_path(["Edit"]),
@@ -60,11 +61,13 @@ fn help_search_ignores_accents_and_matches_the_english_label_and_the_path() {
rig.fixture.settle();
let search = rig.fixture.by_label("Search menus").expect("the search field");
rig.fixture.click(&search);
for (typed, found, absent) in [("cafe", "Paste", "Copy"), ("duplic", "Copy", "Paste"), ("clipboard", "Cut", "Copy")] {
// A row is found by the label it shows. "Café" runs Paste, but no node is named "Paste": the row's shortcut part is
// named by its chord spoken, not by the command's label.
for (typed, found, absent) in [("cafe", "Café", "Copy"), ("duplic", "Copy", "Café"), ("clipboard", "Cut", "Copy")] {
rig.fixture.key(Key::A, Modifiers::COMMAND);
rig.fixture.type_text(typed);
rig.fixture.settle();
assert!(rig.open(found), "{typed:?} finds the entry whose command row reads {found:?}");
assert!(rig.open(found), "{typed:?} finds the entry whose row reads {found:?}");
assert!(!rig.open(absent), "{typed:?} leaves {absent:?} out");
}
}
+41 -2
View File
@@ -1,4 +1,4 @@
//! A menu with several openers: a context menu over a popover.
//! Menus and their openers: a context menu over a popover, and a second opener's menu beside an open one.
use craft_behavior::IconId;
use craft_ui::buttons::{Button, IconButton, PopupMark};
@@ -9,7 +9,7 @@ use craft_ui::runtime::commands::{self, CommandSet as _, EditCommands, FireSourc
use craft_ui::runtime::env::Direction;
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Rect, Shape, pos2};
use egui::{Pos2, Rect, Shape, pos2};
use std::cell::Cell;
use std::rc::Rc;
@@ -126,6 +126,45 @@ fn a_new_right_click_moves_an_open_context_menu_to_the_pointer() {
assert!(after.min.x > before.min.x + 40.0, "the menu moved to the second point: {before:?} then {after:?}");
}
/// A right-click on a second opener while a menu is open closes that menu and opens the second one, as it does on the
/// opener of a closed one: the press lay outside the menu it closed, not outside the menu it opened. A press is judged
/// against the menus the pass before it showed: one that appears in the press's own pass comes after that record, and
/// the press is not outside it.
#[trial]
fn a_right_click_on_a_second_opener_closes_the_open_menu_and_opens_its_own() {
const FIRST: Rect = Rect { min: Pos2::new(8.0, 8.0), max: Pos2::new(200.0, 32.0) };
const SECOND: Rect = Rect { min: Pos2::new(8.0, 240.0), max: Pos2::new(200.0, 264.0) };
let mut fixture = Fixture::new(|ui| {
let first = Button::new("First target").show_at(ui, FIRST);
Menu::context("First menu", &first).show(ui, |ui, _| {
MenuItem::new("First action").show(ui);
});
let second = Button::new("Second target").show_at(ui, SECOND);
Menu::context("Second menu", &second).show(ui, |ui, _| {
MenuItem::new("Second action").show(ui);
});
});
fixture.settle();
let (first, second) = (FIRST.center(), SECOND.center());
right_click(&mut fixture, first);
let open = menu_rect(&fixture).expect("the right-click on the first target opens its menu");
assert!(fixture.by_label("First action").is_some(), "the first menu is open");
assert!(fixture.by_label("Second action").is_none(), "and only the first menu");
assert!(!open.contains(second), "the second target stands clear of the open menu: {open:?} {second:?}");
// A user's right-click: the press closes the first menu, its release opens the second.
right_click(&mut fixture, second);
assert!(fixture.by_label("Second action").is_some(), "the right-click on the second target opens its menu");
assert!(fixture.by_label("First action").is_none(), "the first menu closed");
// A press in the pass a menu appears in: a double right-click on the first target, its second press in the frame of
// the release that opens the first menu. That press is the frame's one press, and it lands outside the zone the
// frame begins with, which the second menu still set in the pass it closed, so the pass records it. The first menu
// appears in that same pass, after the record was made, and the record is not for it.
fixture.frame(vec![pointer::moved(first)]).frame(vec![pointer::secondary(first, true)]);
fixture.frame(vec![pointer::secondary(first, false), pointer::secondary(first, true)]).settle();
assert!(fixture.by_label("First action").is_some(), "the press recorded in the pass the first menu appears in does not close it");
assert!(fixture.by_label("Second action").is_none(), "and the second menu closed");
}
/// A menu request retains its point until an image arrives from the clipboard in a later frame.
#[trial]
fn context_menu_paste_delivers_image_at_the_requested_point() {
+21 -1
View File
@@ -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;
@@ -168,6 +168,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| {
+106 -4
View File
@@ -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 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 _, 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;
@@ -298,6 +299,107 @@ fn the_clear_part_empties_the_field_in_the_pass_of_its_click() {
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);
}
/// 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());
}
/// A field that keeps its text on Escape (`keeps_on_escape`, a live filter's query) commits the typing, lets focus
/// go and leaves the same Escape to its enclosing scope; it reports the focus loss as `text_lost_focus`.
#[trial]
+14
View File
@@ -200,6 +200,20 @@ fn a_log_slider_spreads_equal_ratios_evenly() {
assert!((bottom - min).abs() < 1e-2 * min, "a travel past the start lands on the minimum: {bottom}");
}
/// 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::<f64>::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]
+33 -8
View File
@@ -68,6 +68,8 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay
- `craft_behavior::DisplayOrder`: re-export of `craft_behavior::item_source::DisplayOrder`.
- `craft_behavior::DocKey`: re-export of `craft_behavior::doc_key::DocKey`.
- `craft_behavior::DockSide`: re-export of `craft_behavior::dock::DockSide`.
- `craft_behavior::DragModifier`: re-export of `craft_behavior::value_drag::DragModifier`.
- `craft_behavior::DragModifiers`: re-export of `craft_behavior::value_drag::DragModifiers`.
- `craft_behavior::DragWarp`: re-export of `craft_behavior::value_drag::DragWarp`.
- `craft_behavior::DropOperation`: re-export of `craft_behavior::keys::DropOperation`.
- `craft_behavior::EditCommand`: re-export of `craft_behavior::intent::EditCommand`.
@@ -393,7 +395,7 @@ Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zo
- `fn caret_on_focus(&self, _text: &str) -> Caret`. Where the caret goes when the part takes focus with this text.
- `fn sample(&self, current: &Self::Value) -> Cow<'_, str>`. The widest typical text, for the field's ideal width.
- `craft_behavior::codec::NotAValue`: `pub struct NotAValue`. The text is not a value of the codec's type.
- `craft_behavior::codec::NumberCodec`: `pub struct NumberCodec`. An optional number: empty text is `None`; anything else reads through a [`Reader`].
- `craft_behavior::codec::NumberCodec`: `pub struct NumberCodec`. An optional number: empty text is `None`; anything else reads through a [`Reader`] unless overridden with [`NumberCodec::parse_with`].
- `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 at a set precision does.
- `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 percentage `a ÷ b × 100`, and a second separator cutting the text.
@@ -401,6 +403,7 @@ Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zo
- `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 started from, as a size field does: every pass of the edit reads the same value.
- `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<f64> + 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 field's context ("Auto") can stand for numbers.
- `pub fn parse_with(mut self, parse: impl Fn(&str) -> Option<f64> + Send + Sync + 'static) -> Self`. The same codec with an authoritative reader for the complete, trimmed, non-empty input.
- `pub fn widest(&self, range: &RangeInclusive<f64>) -> String`. The widest text the codec writes for a number in `range`: the longest of each end and the number one place of the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized for any value it shows in it.
- `pub fn decimals(&self) -> usize`. The most decimal places the codec writes.
- `pub fn reader(&self) -> &Reader`. The reader the codec parses with.
@@ -1811,6 +1814,9 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev
`ValueDrag`: the drag maths of sliders, dials, scrubbing number fields and rulers, written once (8.7).
- `craft_behavior::value_drag::DragModifier`: `pub enum DragModifier { Alt, Shift, Control, Command }`. A modifier that changes continuous pointer-drag sensitivity.
- `craft_behavior::value_drag::DragModifiers`: `pub struct DragModifiers`. The pointer-only fine/coarse bindings of a continuous drag.
- `pub const fn new(fine: Option<DragModifier>, coarse: Option<DragModifier>) -> Self`. Selects the fine and coarse bindings; `None` disables that binding.
- `craft_behavior::value_drag::DragWarp`: `pub struct DragWarp`. The pointer warps of one drag.
- `pub fn shift(&mut self, pos: Pos2) -> Vec2`. The total warp so far, given the pointer `pos` of this pass.
- `pub const fn pending(&self) -> bool`. Whether a warp waits for the pointer to show up at its new place: no second warp starts before it does.
@@ -1821,6 +1827,7 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev
- `pub const fn axis(mut self, axis: Axis) -> Self`. The axis the pointer travels on; the default is horizontal.
- `pub const fn fine(mut self, factor: f64) -> Self`. The factor Alt (Option) applies to travel.
- `pub const fn coarse(mut self, factor: f64) -> Self`. The factor Shift applies to travel.
- `pub const fn modifiers(mut self, modifiers: DragModifiers) -> Self`. Selects pointer fine/coarse bindings without changing keyboard or wheel behavior.
- `pub const fn warp(mut self, on: bool) -> Self`. Warps the pointer to the other side of the window when the drag reaches an edge, so the drag has no end ([`ValueDrag::warp_by`], [`DragWarp`]).
- `pub const fn hide_cursor(mut self, on: bool) -> Self`. Hides the pointer while the drag runs, as a scrub does that warps the pointer.
- `pub const fn warps(&self) -> bool`. Whether the pointer warps at a window edge.
@@ -1835,7 +1842,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 zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option<Pos2>, 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`.
- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option<Pos2>, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: 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 zoom_lines(mut self, lines: Vec2) -> Self`. The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`).
@@ -1865,9 +1872,9 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli
- `pub const fn new(positive: Vec2, negative: Vec2) -> Self`. A room of `positive` and `negative` points.
- `craft_behavior::wheel::WheelSource`: `pub enum WheelSource { Unknown, Wheel, Trackpad, Momentum }`. The device a wheel event came from, where the system says (egui reports it on macOS only).
- `pub const fn fingers(self) -> bool`. Whether fingers drive the scroll: a trackpad or its momentum.
- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker<O> { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option<WheelRoom>, pub zooms_view: bool, pub field: bool, pub value: bool }`. A component that takes wheel input, as registered last pass.
- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker<O> { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub directional: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option<WheelRoom>, pub zooms_view: bool, pub field: bool, pub value: bool }`. A component that takes wheel input, as registered last pass.
- `pub const fn new(owner: O, rect: Rect) -> Self`. A taker over `rect` that takes no axis yet.
- `pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option<Self>`. 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.
- `pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option<Self>`. 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; `WHEEL_Y_FOCUSED` takes the vertical share and makes the taker gated, so every axis it takes waits for focus or arming.
- `pub const fn zooms_view(mut self, on: bool) -> Self`. Whether it is a zoom zone (`WheelTaker::zooms_view`).
- `pub const fn field(mut self, on: bool) -> Self`. Whether it is a value field (`WheelTaker::field`).
- `pub const fn value(mut self, on: bool) -> Self`. Whether it is a value control (`WheelTaker::value`).
@@ -1875,6 +1882,7 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli
- `pub const fn vertical(mut self, on: bool) -> Self`. Whether it takes vertical scroll.
- `pub const fn zoom(mut self, on: bool) -> Self`. Whether it takes zoom.
- `pub const fn gated(mut self, on: bool) -> Self`. Whether every axis needs focus or arming.
- `pub const fn directional(mut self, on: bool) -> Self`. Opts a value control into directional editing, without changing the default focus gate.
- `pub const fn notch(mut self, notch: WheelNotch) -> Self`. The distance of one wheel line.
- `pub const fn scrolls(mut self, on: bool) -> Self`. The taker is a scroll region (`WheelTaker::scrolls`).
- `pub const fn room(mut self, room: WheelRoom) -> Self`. The taker's scroll room: it passes a wheel on an axis it has no room left for to the next enclosing taker.
@@ -2276,7 +2284,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `pub fn lifted(response: Response, events: EditEvents<T>, shown: Option<Mixed<Arc<T>>>) -> Self`. The response of a composite that edits one value through several child components: `events` are the edits of the whole value the composite lifted from its children's events, `shown` the value it showed after the pass, and `response` its own.
- `pub fn value(&self) -> Option<&T>`. The latest value the pass's events carry: a proposal, a commit or a set; `None` when nothing was edited or no event carries one (a gesture's begin or cancel).
- `pub fn map<U>(self, f: impl Fn(T) -> U) -> EditResponse<U>`. The response of a child component's edit as the response of the edit of a value built from it: the events, the shown value and a fix are mapped by `f`; the response and flags are the child's own.
- `craft_ui::contract::EditorHandle`: `pub struct EditorHandle`. The editor part's widget, rect, purpose, focus and read-only state of this pass, which a body that runs inside a component reports through for the component's editor part.
- `craft_ui::contract::EditorHandle`: `pub struct EditorHandle`. The editor part's widget, rect, purpose, focus, read-only and disabled state of this pass, which a body that runs inside a component reports through for the component's editor part.
- `pub fn focused(&self) -> bool`. Whether the editor part holds the key focus this pass, whether or not its window has the system's.
- `pub fn report(&self, ctx: &egui::Context, state: EditorState<'_>)`. Reports the caret and composition to the input-method engine and puts the text facts in the running pass's editor record, which the owning component's report step reads in the same pass.
- `pub fn ime_receipt(&self, ctx: &egui::Context, before: ImeStamp, after: ImeStamp) -> bool`. Notes the input-method receipt between the stamps `before` and `after` for this editor part; true when the stamps prove the engine applied it.
@@ -2841,8 +2849,9 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the
- `pub const fn commands(mut self, on: bool) -> Self`. Closes when a key, a native menu pick or the palette runs a command from outside it; off for a layer its host opens and closes, as a dock panel's flyout.
- `pub const fn timeout(mut self, seconds: Option<f32>) -> Self`. Closes after `seconds`.
- `craft_ui::contract::overlay::DragBounds`: `pub enum DragBounds { Inside, TitleVisible }`. How much of a floating layer stays inside the window: the whole layer (`Inside`, the default) or a strip of its title.
- `craft_ui::contract::overlay::FloatPlace`: `pub struct FloatPlace { pub pos: Option<Pos2>, pub corner: Align2 }`. Where a floating layer sits.
- `craft_ui::contract::overlay::FloatPlace`: `pub struct FloatPlace { pub pos: Option<Pos2>, pub corner: Align2, pub top: Option<f32> }`. Where a floating layer sits.
- `pub const fn centred() -> Self`. Centred in the viewport.
- `pub const fn top_centered(share: f32) -> Self`. Centered across the viewport, with its top `share` of the viewport's height down from the viewport's top, so a layer whose content grows or shrinks keeps its top edge where it is.
- `pub const fn at(pos: Pos2) -> Self`. With its left-top at `pos`.
- `pub const fn corner_at(pos: Pos2, corner: Align2) -> Self`. With its `corner` at `pos`.
- `craft_ui::contract::overlay::HOLD`: `pub const HOLD: f64`. The seconds a press must be held for `Trigger::Hold`.
@@ -3854,6 +3863,12 @@ The pass's edit events and edit-command routing: the context-free calls an app m
- `craft_ui::runtime::edit::next_gesture_id`: `pub fn next_gesture_id(ctx: &Context) -> GestureId`. A gesture id no gesture of this context has had: ids grow in the order gestures begin, across components and across a component's eviction, as `GestureHost` assumes.
- `craft_ui::runtime::edit::watch_gestures`: `pub fn watch_gestures<R>(ctx: &Context, body: impl FnOnce() -> R) -> (R, bool)`. Runs `body` and says whether a gesture of a component shown inside it was running after the component's apply step: a drag or a typing run under way.
## `craft_ui::runtime::egui`
The one egui adapter: the only importer of egui's behavioural APIs.
- `craft_ui::runtime::egui::LayerId`: re-export of `egui::LayerId` (outside these crates).
## `craft_ui::runtime::egui::access`
AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: the one place that names AccessKit's node API. `node` writes a decided node, `patch` applies the label scope and the status node, `tree` reads a finished tree update, which automation keeps per viewport (`keep_trees`).
@@ -4085,6 +4100,7 @@ One-shot screenshot slots and the facts a screenshot is measured against.
- `pub fn window(&self) -> &WindowKey`. The window's key; components in slots key their ids and memory by it.
- `pub fn body_mode(&self) -> BodyMode`. The body mode of this pass.
- `pub fn slot_visible(&self, key: SlotKey) -> bool`. Is the slot with this key shown on this pass?
- `pub fn chrome_hidden(&self) -> bool`. Whether the user hid the editor's chrome with Tab in standard screen mode: the shell's bars are gone and the body's docks and floating panels hide with them, while the body and the document tabs stay.
- `pub fn with_reveals_key(mut self, id: egui::Id) -> Self`. The same skeleton with its revealed rects registered under `id`, which stays the same across passes.
- `pub fn reveal_rect(&self, ctx: &egui::Context, edge: RevealEdge, rect: Rect)`. Registers `rect`, a revealed panel the body drew on this pass, as part of the revealed `edge`: the edge reveal lasts while the pointer is over it, as it does over a revealed slot.
- `pub fn revealed_rects(&self, ctx: &egui::Context) -> Vec<(RevealEdge, Rect)>`. The rects registered with [`reveal_rect`] on this pass, in registration order.
@@ -4140,7 +4156,7 @@ One-shot screenshot slots and the facts a screenshot is measured against.
- `pub fn length_scale(&self, lengths: LengthUnits) -> Option<f64>`. How many `lengths.shown` make one `lengths.stored`; `None` when either is not a pixel or length unit or the resolution is not a positive number.
- `pub fn length_reader(&self, lengths: LengthUnits) -> Reader`. A reader for lengths shown in `lengths.shown`: the spellings of every length unit and of pixels convert to it, and a bare number is in it, or in `lengths.bare` when set.
- `pub fn document_reader(&self, ruler: UnitKind, extent: f64, pixels_per_inch: f64, points_per_inch: f64) -> Reader`. A reader for the numbers of a document measured in `ruler`: the unit spellings of every pixel and length unit (px, %, in, cm, mm, pt, pica) convert to `ruler` through the document's numbers, percent of `extent` pixels and lengths at `pixels_per_inch`, with points of `points_per_inch` to the inch (`UnitKind::to_pixels` clamps them).
- `craft_ui::runtime::env::WheelScope`: `pub enum WheelScope { Plain, Free, Gated }`. How the wheel takers of a scope take the wheel.
- `craft_ui::runtime::env::WheelScope`: `pub enum WheelScope { Plain, Free, Gated, Directional }`. How the wheel takers of a scope take the wheel.
- `craft_ui::runtime::env::WheelSpeed`: `pub struct WheelSpeed { pub line: f32, pub point: f32 }`. The user's wheel multipliers: `line` for notches, `point` for touchpad deltas.
- `pub const fn new(line: f32, point: f32) -> Self`. The multipliers for line (notch) and point (touchpad) scrolling.
- `craft_ui::runtime::env::WindowKey`: `pub struct WindowKey`. The key of a window.
@@ -4362,6 +4378,15 @@ The key stage (spec 9.1, 9.2, 9.3, 9.7): the input hook strips the keys the runt
- `craft_ui::runtime::keys::MoveMods`: re-export of `craft_behavior::intent::MoveMods`.
- `craft_ui::runtime::keys::NavMove`: re-export of `craft_behavior::intent::NavMove`.
- `craft_ui::runtime::keys::PartRef`: re-export of `craft_behavior::part::PartRef`.
- `craft_ui::runtime::keys::ScalarKeyPolicy`: `pub struct ScalarKeyPolicy`. Opt-in additive model-unit vertical-key and accessibility nudges.
- `pub const fn new(nudge: f64) -> Self`. A focused-row policy, with Shift multiplying the additive nudge by five.
- `pub const fn trigger(mut self, trigger: ScalarKeyTrigger) -> Self`. Chooses whether whole-row hover also makes a row eligible.
- `pub const fn shift_factor(mut self, factor: f64) -> Self`. Sets the multiplier used by Shift.
- `pub const fn model_step(mut self, step: f64) -> Self`. Selects an explicit zero-origin model grid for scalar keys and accessibility actions only.
- `pub fn is_valid(self) -> bool`. Whether the amounts and any selected model step describe usable, finite positive changes.
- `pub fn amount(self) -> Option<f64>`. The unmodified model-unit accessibility increment.
- `pub fn offset(self, movement: NavMove, modifiers: MoveMods) -> Option<f64>`. An additive offset for vertical keys or accessibility increment/decrement (Forward/Back).
- `craft_ui::runtime::keys::ScalarKeyTrigger`: `pub enum ScalarKeyTrigger { Focused, HoveredOrFocused }`. Which real scalar row can take a vertical arrow, without moving keyboard focus.
- `craft_ui::runtime::keys::escape_mods`: `pub fn escape_mods(ctx: &Context) -> Option<Mods>`. The Alt and Shift held at the press of the pass's last Escape that became a `Cancel`; `None` when the pass had none.
- `craft_ui::runtime::keys::focus_holds`: `pub fn focus_holds(ctx: &Context, chord: Chord) -> bool`. Whether the focused component of the running viewport holds a press of `chord`, as routing decides for the press:
- `craft_ui::runtime::keys::held`: `pub fn held(ctx: &Context) -> Vec<Key>`. The keys down in the running viewport this pass: the key stage's `down` (withheld presses included), plus each key automation holds there that is not already listed.
@@ -4499,7 +4524,7 @@ Background results (14): one result per key in runtime memory, produced by a job
The pointer snapshot, press targets, the shape record and press cancels (8.1, 8.3).
- `craft_ui::runtime::pointer::PointerFrame`: `pub struct PointerFrame { pub pos: Option<Pos2>, pub delta: Vec2, pub buttons: Buttons, pub press: Option<PressStart>, pub press_mods: Option<Mods>, pub release: Option<PointerButton>, pub mods: Mods, pub pick_mods: Mods, pub pick_pos: Option<Pos2>, pub multi_tap: Option<craft_behavior::MultiTap>, pub time: f64, pub kind: PointerKind, pub sample: Option<PointerSample>, pub multi_touch: Option<MultiTouch>, pub scroll: Vec2, pub zoom: f32, pub rotation: f32, pub slop: f32, pub target: f32 }`. The pointer input of one pass of one viewport, egui-converted.
- `craft_ui::runtime::pointer::PointerFrame`: `pub struct PointerFrame { pub pos: Option<Pos2>, pub delta: Vec2, pub buttons: Buttons, pub press: Option<PressStart>, pub press_mods: Option<Mods>, pub release: Option<PointerButton>, pub mods: Mods, pub pick_mods: Mods, pub click_mods: Mods, pub pick_pos: Option<Pos2>, pub multi_tap: Option<craft_behavior::MultiTap>, pub time: f64, pub kind: PointerKind, pub sample: Option<PointerSample>, pub multi_touch: Option<MultiTouch>, pub scroll: Vec2, pub zoom: f32, pub rotation: f32, pub slop: f32, pub target: f32 }`. The pointer input of one pass of one viewport, egui-converted.
- `craft_ui::runtime::pointer::PressState`: `pub struct PressState { pub buttons: Buttons, pub press: Option<PressStart>, pub release: Option<PointerButton> }`. The press state of a pass: the buttons held, and the primary press and the release the pass brought.
- `craft_ui::runtime::pointer::active_part`: `pub fn active_part(ctx: &Context, owner: Id) -> Option<PartRef>`. The part of `owner` holding the pointer's hover or an open press in this viewport.
- `craft_ui::runtime::pointer::follows_pointer`: `pub fn follows_pointer(ctx: &Context, rect: Rect)`. Records that what the running pass shows in `rect` (screen points) follows the pointer: a cursor drawn at the pointer, a readout of the point under it.
+1 -1
View File
@@ -167,7 +167,7 @@ An app with its own eframe `App` calls the hooks in `craft::ui::shell::embed`. `
| 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). |
| Wheel | `RootEnv::wheel_speed` scales each wheel delta once; a Ctrl or Cmd wheel keeps the device's distance. The install's `WheelModifiers` set egui's zoom and sideways modifiers. On Windows and Linux, a Ctrl+wheel in fractions of a notch (a point-unit one on Linux) is a touchpad pinch and arrives as `Event::Zoom`, at egui's Ctrl-scroll zoom speed: Windows hands a precision touchpad's pinch to apps only that way. Whole notches stay wheel events, except within 0.25 s of a pinch step. An app whose Ctrl+wheel does something else, or zooms at its own rate, sets `RootEnv::ctrl_wheel_pinch(false)` and reads the wheel events itself. |
| App modals | A modal the app draws with its own egui code blocks nothing outside egui by itself. While one shows, the app names its window each frame with `FrameInput::app_modal(Some(viewport))`: the app's other windows, panels floated into windows of their own among them, are then blocked as under a framework app-modal layer (their presses, keys, wheel and text are dropped, a press there brings the modal's window forward, they refuse to close, and the modal's window takes the keyboard if one of them has it when the modal opens). |
| 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 menus that were open when it was made; a primary press goes no further, and a secondary or middle press reaches what it lands on, so a right-click opens that part's menu. 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 nothing has the focus, neither a framework stop nor one of the app's own widgets or popups, and the arrows' nudge. The window's plain Enter also stays in egui's input. `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 Escape and the plain Enter from egui (Tab only where the widget keeps it or a popup is open), and no window intent comes of them. An Escape pressed in the OS window of a floated dock panel that nothing there takes, not even a reader of that window's intents, is the Cancel of the window the dock is in, in its next pass, so the app reads it where it reads its own; a popup or a modal open over the panel keeps it, and any other OS window (an app's own viewport, a dialog or document window) keeps its Escape to itself (`WindowSpec::hands_on_cancel`).
+1
View File
@@ -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 |