PageView: the page and arrow keys of the old view through a canvas that leaves its keys to its body, and the zoom and pan decided from the canvas's settled view

This commit is contained in:
aiongg
2026-11-12 14:32:41 +00:00
parent 823a586f9c
commit 5815b66839
4 changed files with 210 additions and 28 deletions
+77 -16
View File
@@ -24,8 +24,10 @@ use crate::layout::{
Fit, LayoutOptions, PageDisplay, PageSpacing, PagedLayout, SCREEN_POINTS_PER_POINT, ViewDefaults, ZOOM_RANGE, fit_scale, place_pages, shown_row,
};
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
use craft_behavior::{CanvasView, PressPhase, WheelNotch, ZoomLadder};
use craft_ui::canvas::{Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageFrame, Pasteboard, PasteboardOutput, canvas_space};
use craft_behavior::{CanvasView, MoveMods, NavMove, PressPhase, WheelNotch, ZoomLadder};
use craft_ui::canvas::{
BodyKeys, Canvas, CanvasOutput, CanvasScrollbars, NavigationOptions, PageFrame, PageKey, Pasteboard, PasteboardOutput, canvas_space,
};
use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContainer as _};
use craft_ui::primitives::textures::ThumbSource;
use craft_ui::runtime::env::{Env, Label};
@@ -313,7 +315,7 @@ impl<'a> PageView<'a> {
let given = frame.view(rect, start.offset, geo.scale / SCREEN_POINTS_PER_POINT);
let mut navigation = navigation;
navigation.overscroll = !start.continuous;
let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation);
let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true);
if start.continuous {
canvas = canvas.document(frame.document(&geo));
}
@@ -468,7 +470,10 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState>
let Inputs { source, describer, build, rect, given, paper } = *inputs;
let mut state = held.read(cx)?;
let started = state.clone();
let shown = canvas_space(&cx.env)?.view;
let space = canvas_space(&cx.env)?;
// The canvas's settled view decides the zoom and the pan; the view on screen, part way there while a zoom eases,
// draws.
let (target, shown) = (space.target(), space.view);
let env = Env::of(ui);
let words = env.words::<PageViewWords>();
let mut mem = cx.memory::<Memory>().clone();
@@ -493,20 +498,20 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState>
}
state.zoom = geo.scale / SCREEN_POINTS_PER_POINT;
// The canvas folded the wheel, a pinch and the view commands into the view it shows: a different zoom is the
// The canvas folded the wheel, a pinch and the view commands into the view it settled on: a different zoom is the
// user's, anchored at the point that stayed still; a different centre is a scroll.
let zooming = (shown.zoom - given.zoom).abs() > given.zoom * 1e-9;
let zooming = (target.zoom - given.zoom).abs() > given.zoom * 1e-9;
let mut want = state.offset;
let mut wheel_left = 0.0;
if zooming {
let fixed = (shown.center - given.center) * (given.zoom * shown.zoom / (shown.zoom - given.zoom));
let fixed = (target.center - given.center) * (given.zoom * target.zoom / (target.zoom - given.zoom));
let pointer = rect.center() + Vec2::new(fixed.x as f32, fixed.y as f32);
geo = zoom_about(build, &mut state, &geo, rect, pointer, shown.zoom / given.zoom);
geo = zoom_about(build, &mut state, &geo, rect, pointer, target.zoom / given.zoom);
want = state.offset;
} else {
// The canvas was given the view the pass started with, so its change of it is the pan; the state's offset
// may have moved on since (a scale change anchors the page at the top), and the pan adds to that.
let panned = drawn_frame.offset_of(shown.center, vw, vh);
let panned = drawn_frame.offset_of(target.center, vw, vh);
let given_at = drawn_frame.offset_of(given.center, vw, vh);
let (along_x, along_y) = (panned.0 - given_at.0, panned.1 - given_at.1);
if along_x.abs() > OFFSET_EPSILON || along_y.abs() > OFFSET_EPSILON {
@@ -517,12 +522,13 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState>
if wheel_left == 0.0 {
mem.overshoot = 0.0;
}
let keys = KeyMoves::of(space.keys(), &state, &geo, rect);
want.0 += keys.pan.0;
want.1 = if keys.to_end { f64::INFINITY } else { want.1 + keys.pan.1 };
// A page that fits turns with the wheel; one panned to its edge turns with the wheel past it.
if !state.continuous
&& wheel_left != 0.0
&& let Some(forward) = mem.turn(&geo, want.1, vh, notch())
{
// A key turns the page; else a page that fits turns with the wheel, and one panned to its edge with the wheel past it.
let turn = keys.turn.or_else(|| (!state.continuous && wheel_left != 0.0).then(|| mem.turn(&geo, want.1, vh, notch())).flatten());
if let Some(forward) = turn {
let next = if forward {
(geo.row.end < count).then_some(geo.row.end)
} else {
@@ -538,8 +544,9 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState>
want.1 = state.offset.1;
}
}
let went = state.go_to.is_some();
if let Some((page, fraction)) = state.go_to.take() {
let go_to = keys.go_to.or(state.go_to.take());
let went = go_to.is_some();
if let Some((page, fraction)) = go_to {
state.current = page.min(count.saturating_sub(1));
geo = build.of(&state);
state.zoom = geo.scale / SCREEN_POINTS_PER_POINT;
@@ -636,6 +643,60 @@ craft_ui::words! {
}
}
/// What this pass's keys ask of the view (plain keys only).
#[derive(Default)]
struct KeyMoves {
/// Screen points to move the offset.
pan: (f64, f64),
/// End in a continuous view: the bottom.
to_end: bool,
/// Turn to the next (`true`) or previous row when not continuous.
turn: Option<bool>,
/// The page to bring to the top, and the fraction of its height at the top.
go_to: Option<(usize, f64)>,
}
impl KeyMoves {
/// Page Up and Down a screen (a row when not continuous), Home and End the first and last page, Up and Down a
/// line, Left and Right a page when the page fits the width, else a line sideways.
fn of(keys: BodyKeys, state: &PageViewState, geo: &Placed, rect: Rect) -> KeyMoves {
let (last, line) = (geo.layout.rects.len().saturating_sub(1), f64::from(PageKey::SMALL_STEP));
let mut moves = KeyMoves::default();
// Shift, Cmd and Alt leave the keys to nothing, as in the old view.
let plain = |mods: &MoveMods| !mods.extend && !mods.lead && !mods.fine;
match keys.page.filter(|(_, mods)| plain(mods)).map(|(step, _)| step) {
Some(step @ (NavMove::PageUp | NavMove::PageDown)) => {
let forward = step == NavMove::PageDown;
if state.continuous {
let screen = f64::from(rect.height());
moves.pan.1 += if forward { screen } else { -screen };
} else {
moves.turn = Some(forward);
}
}
Some(NavMove::Start) => moves.go_to = Some((0, 0.0)),
Some(NavMove::End) if state.continuous => moves.to_end = true,
Some(NavMove::End) => moves.go_to = Some((last, 0.0)),
_ => {}
}
let Some((direction, _)) = keys.nudge.filter(|(_, mods)| mods.is_none()) else { return moves };
if direction.y != 0.0 {
moves.pan.1 += f64::from(direction.y.signum()) * line;
} else if direction.x != 0.0 {
let forward = direction.x > 0.0;
if geo.doc.width() > f64::from(rect.width()) {
moves.pan.0 += if forward { line } else { -line };
} else if state.continuous {
let next = if forward { state.current + 1 } else { state.current.saturating_sub(1) };
moves.go_to = Some((next.min(last), 0.0));
} else {
moves.turn = Some(forward);
}
}
moves
}
}
/// The wheel's notch in points: what gathered past a row's edge turns the page.
fn notch() -> f64 {
match WheelNotch::DEFAULT {
+55
View File
@@ -112,3 +112,58 @@ fn the_preview_steps_with_the_arrow_and_page_keys_from_a_footer_button() {
assert_eq!(*at.borrow(), 2, "Left steps back");
assert_eq!(fixture.focused_stop(), button, "the keys leave the focus where it was");
}
/// Tabs to the view's canvas.
fn focus_canvas(fixture: &mut Fixture) {
for _ in 0..4 {
if fixture.focused_role().is_some_and(|role| role.nudge) {
return;
}
fixture.key(Key::Tab, Modifiers::NONE);
}
assert!(fixture.focused_role().is_some_and(|role| role.nudge), "Tab reaches the view's canvas");
}
#[trial]
fn page_keys_turn_and_go_to_the_ends_in_a_view_that_is_not_continuous() {
let (mut fixture, state, _) = layout_rig(
5,
state_with(|s| {
s.continuous = false;
s.fit = Fit::Page;
}),
);
focus_canvas(&mut fixture);
fixture.key(Key::PageDown, Modifiers::NONE);
fixture.idle(1);
assert_eq!(state.borrow().current, 1, "Page Down turns one page");
fixture.key(Key::End, Modifiers::NONE);
fixture.idle(1);
assert_eq!(state.borrow().current, 4, "End goes to the last page");
fixture.key(Key::Home, Modifiers::NONE);
fixture.idle(1);
assert_eq!(state.borrow().current, 0, "Home goes to the first page");
}
#[trial]
fn arrows_go_to_the_next_page_and_scroll_a_line_in_a_continuous_view() {
let (mut fixture, state, _) = layout_rig(5, state_with(|s| s.fit = Fit::Page));
focus_canvas(&mut fixture);
fixture.key(Key::ArrowRight, Modifiers::NONE);
fixture.idle(1);
assert_eq!(state.borrow().current, 1, "Right goes to the next page while the page fits the width");
let before = state.borrow().offset.1;
fixture.key(Key::ArrowDown, Modifiers::NONE);
fixture.idle(1);
assert!(state.borrow().offset.1 > before, "Down scrolls forward");
}
#[trial]
fn zoom_in_zooms_a_focused_view_with_animated_zoom() {
let (mut fixture, state, _) = layout_rig(3, PageViewState::default());
focus_canvas(&mut fixture);
let before = state.borrow().zoom;
fixture.key(Key::Equals, Modifiers::COMMAND);
fixture.settle();
assert!(state.borrow().zoom > before, "Zoom In zooms: {before} -> {}", state.borrow().zoom);
}
+25 -8
View File
@@ -57,7 +57,7 @@ pub(crate) use rulers::LABEL_STEP_MIN;
pub use rulers::{NUDGE, NUDGE_FAR};
pub use snap::{Snap, canvas_snap};
pub(crate) use space::context_menu;
pub use space::{BackgroundPress, CanvasRulers, context_click};
pub use space::{BackgroundPress, BodyKeys, CanvasRulers, context_click};
// End of l4d-space.
// canvas-navigate-a
@@ -187,6 +187,11 @@ pub struct Canvas<'a> {
/// Whether the rulers show along the top and left edges (View > Rulers): the view lies inside them.
#[prop]
show_rulers: bool,
/// Whether the canvas leaves Page Up, Page Down, Home, End and the arrows to its body: it applies no page keys
/// and gives no tool or session control the arrows, and its body reads them in [`CanvasSpace::keys`]. For a
/// body that pages its document itself (a page view).
#[prop]
keys_to_body: bool,
/// The rulers' units and zero point, published to the body in its [`CanvasSpace`].
rulers: Option<CanvasRulers>,
/// The snapping of the coordinates the pointer sets on this canvas (View > Snap To): one function that the rulers
@@ -207,6 +212,8 @@ struct Settled {
target: CanvasView,
/// The view on screen: the target, or a view part way to it while a zoom eases.
shown: CanvasView,
/// The keys the canvas leaves to its body.
keys: BodyKeys,
}
impl<'a> Canvas<'a> {
@@ -222,6 +229,7 @@ impl<'a> Canvas<'a> {
document: None,
navigation: NavigationOptions::default(),
show_rulers: false,
keys_to_body: false,
rulers: None,
snap: None,
settled: None,
@@ -295,12 +303,19 @@ impl<'a> Canvas<'a> {
pan(&mut view, delta);
jumped = true;
}
// Page Up and Down, Home and End scroll the view as in Photoshop; the arrows are the tool's nudges.
// Page Up and Down, Home and End scroll the view as in Photoshop; the arrows are the tool's nudges. A canvas
// that leaves its keys to its body hands both to it.
let mut keys = BodyKeys::default();
while let Some((step, mods)) = cx.intents().take_move() {
if let (Some(document), Some(key)) = (self.document, PageKey::of(step, mods, area.size())) {
if self.keys_to_body {
keys.page = Some((step, mods));
} else if let (Some(document), Some(key)) = (self.document, PageKey::of(step, mods, area.size())) {
jumped |= key.apply(&mut view, document);
}
}
if self.keys_to_body {
keys.nudge = cx.intents().take_nudge();
}
// A pan or a scroll takes over from an ease, here or in a tool.
let mut steer = motion.steer.take();
if jumped {
@@ -328,7 +343,7 @@ impl<'a> Canvas<'a> {
}
let shown = motion.animation.shown(&target, progress);
motion.restore(&ctx, id);
Settled { target, shown }
Settled { target, shown, keys }
}
/// Measures the document's axes in `x` and `y`, counted from `zero` (document units). The rulers, the guides and
@@ -342,10 +357,12 @@ impl<'a> Canvas<'a> {
}
fn space(&self, id: egui::Id, pixels_per_point: f32, background: BackgroundPress) -> Option<CanvasSpace> {
let view = self.settled.map(|settled| settled.shown).or(self.given);
view.map(|view| {
CanvasSpace::new(view, pixels_per_point).with_document(self.document).with_rulers(self.rulers).with_background(background).with_canvas(id)
})
let (shown, target, keys) = match self.settled {
Some(settled) => (settled.shown, settled.target, settled.keys),
None => (self.given?, self.given?, BodyKeys::default()),
};
let space = CanvasSpace::new(shown, pixels_per_point).with_target(target).with_keys(keys);
Some(space.with_document(self.document).with_rulers(self.rulers).with_background(background).with_canvas(id))
}
/// The press on the background part as the canvas reports it, and the pan of a middle-button drag: a middle press
+53 -4
View File
@@ -9,8 +9,9 @@ use crate::contract::{Component, Cx, Focus as _, Pointer as _};
use crate::runtime::env::{AppValues, EnvValue, EnvView, UnitKind, Units};
use craft_behavior::canvas::zoom;
use craft_behavior::kurbo::{Point, Size};
use craft_behavior::{Axis, CanvasView, Intent, PartRef, PointerButton, PressPhase, PressState, RulerUnits, Ticks};
use egui::Pos2;
use craft_behavior::{Axis, CanvasView, Intent, MoveMods, NavMove, PartRef, PointerButton, PressPhase, PressState, RulerUnits, Ticks};
use craft_keymap::Mods;
use egui::{Pos2, Vec2};
use std::ops::RangeInclusive;
/// How a canvas shows its document, as its body and its tool see it: the view, and the interface scale it is
@@ -18,10 +19,13 @@ use std::ops::RangeInclusive;
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct CanvasSpace {
/// The view: document to the canvas root's screen space.
/// The view on screen: document to the canvas root's screen space, part way to [`target`](Self::target) while a
/// zoom eases.
pub view: CanvasView,
/// Device pixels per point.
pub pixels_per_point: f32,
target: CanvasView,
keys: BodyKeys,
document: Option<Size>,
rulers: Option<CanvasRulers>,
background: BackgroundPress,
@@ -33,7 +37,30 @@ impl CanvasSpace {
/// The space of `view` at `pixels_per_point` device pixels per point, with no rulers published and no press on
/// the background.
pub fn new(view: CanvasView, pixels_per_point: f32) -> Self {
Self { view, pixels_per_point, document: None, rulers: None, background: BackgroundPress::default(), canvas: None }
Self {
view,
pixels_per_point,
target: view,
keys: BodyKeys::default(),
document: None,
rulers: None,
background: BackgroundPress::default(),
canvas: None,
}
}
/// This space with `target`, the view the canvas settled on in the pass, which `view` eases toward.
#[must_use]
pub fn with_target(mut self, target: CanvasView) -> Self {
self.target = target;
self
}
/// This space with the keys the canvas left to its body in the pass.
#[must_use]
pub fn with_keys(mut self, keys: BodyKeys) -> Self {
self.keys = keys;
self
}
/// This space with the size of the document the canvas shows, in document units: the one size the zoom ladder's
@@ -86,6 +113,17 @@ impl CanvasSpace {
self.background
}
/// The view the canvas settled on in this pass: what the app keeps, and what a body that keeps its own view state
/// decides from. It differs from `view` only while a zoom eases.
pub fn target(&self) -> CanvasView {
self.target
}
/// The page and arrow keys the canvas left to its body in this pass ([`Canvas::keys_to_body`](super::Canvas)).
pub fn keys(&self) -> BodyKeys {
self.keys
}
/// Device pixels per document unit (1 is 100 %) of the view at this scale.
pub fn zoom_device(&self) -> f64 {
zoom::device(&self.view, self.pixels_per_point)
@@ -144,6 +182,17 @@ pub struct BackgroundPress {
pub context_key: bool,
}
/// The keys a canvas that leaves them to its body took in a pass, one of each kind: a key held down repeats over
/// passes, not within one.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct BodyKeys {
/// Page Up, Page Down, Home or End, with the modifiers held.
pub page: Option<(NavMove, MoveMods)>,
/// An arrow: a unit direction on screen and the modifiers held.
pub nudge: Option<(Vec2, Mods)>,
}
impl BackgroundPress {
/// What `press`, the press on the background part after the middle button's pan is taken out, and the canvas's
/// keyed menu request report.