mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:14:31 +01:00
Merge branch 'pdf-port/sync-forms' into pdf-port/sync
This commit is contained in:
12 files changed
+280
-17
No files matched your search
@@ -432,6 +432,12 @@ pub struct TextEditor<'a> {
|
||||
/// Whether Esc commits (Photoshop's default) or cancels the session.
|
||||
#[prop]
|
||||
esc_commits: bool,
|
||||
/// Whether focus goes back to the stop it came from when the session ends (on by default: the canvas text editor
|
||||
/// hands it back to the canvas). Off, the editor opens no focus scope, and an ended session leaves focus where the
|
||||
/// removal of a stop leaves it: for a form field whose own part handed it the focus, returning there would open the
|
||||
/// field again.
|
||||
#[prop]
|
||||
returns_focus: bool,
|
||||
/// What the editor is: the canvas text editor, or a one-line or multi-line form field.
|
||||
#[prop]
|
||||
mode: EditorMode,
|
||||
@@ -455,6 +461,7 @@ impl<'a> TextEditor<'a> {
|
||||
selection,
|
||||
smart_quotes: None,
|
||||
esc_commits: true,
|
||||
returns_focus: true,
|
||||
mode: EditorMode::Canvas,
|
||||
masked: false,
|
||||
changed: false,
|
||||
@@ -625,6 +632,10 @@ impl Component for TextEditor<'_> {
|
||||
type Style = TextEditorStyle;
|
||||
type Output = TextEditorOutput;
|
||||
|
||||
fn focus_scope(&self) -> FocusPolicy {
|
||||
if self.returns_focus { Self::FOCUS_SCOPE } else { FocusPolicy::NONE }
|
||||
}
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: TextEditorStyleKey) -> TextEditorStyle {
|
||||
let overlay = &cx.tokens.color.overlay;
|
||||
TextEditorStyle {
|
||||
|
||||
@@ -654,3 +654,49 @@ fn an_ended_session_returns_the_focus_to_the_canvas_and_the_view_stays() {
|
||||
assert_eq!(view.get(), before, "rulers {rulers}: the view stays");
|
||||
}
|
||||
}
|
||||
|
||||
/// An editor shown with `returns_focus(false)` opens no focus scope: when its session ends, focus does not go back to
|
||||
/// the stop that handed it over (a form field's part, which would open the field again), while the default editor
|
||||
/// hands it back there.
|
||||
#[trial]
|
||||
fn an_editor_that_does_not_return_focus_leaves_its_opener_alone() {
|
||||
const EDITOR: craft_behavior::DocKey = craft_behavior::DocKey::new("trial.field-editor");
|
||||
const OPENER: craft_behavior::DocKey = craft_behavior::DocKey::new("trial.field-opener");
|
||||
use craft_ui::runtime::focus::{FocusTarget, request};
|
||||
use craft_ui::testing::access::{focused_key, name};
|
||||
|
||||
for returns in [true, false] {
|
||||
let editing = Rc::new(Cell::new(false));
|
||||
let shown_editing = Rc::clone(&editing);
|
||||
let mut host = Host { text: "abc".to_owned(), ..Host::default() };
|
||||
let mut selection = TextSelection::caret_at(3);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
drop(Button::new("Opener").doc_key(OPENER).show(ui));
|
||||
if shown_editing.get() {
|
||||
let bounds = Rect::from_min_size(ui.cursor().min, vec2(200.0, 20.0));
|
||||
drop(
|
||||
TextEditor::new("Field", &mut host, Bind::bound(&mut selection))
|
||||
.mode(EditorMode::FieldLine)
|
||||
.returns_focus(returns)
|
||||
.doc_key(EDITOR)
|
||||
.show_at(ui, bounds),
|
||||
);
|
||||
}
|
||||
ui.add_space(30.0);
|
||||
drop(Button::new("After").show(ui));
|
||||
});
|
||||
fixture.room(vec2(400.0, 300.0)).settle();
|
||||
let focused = |fixture: &Fixture| name(fixture.tree(), focused_key(fixture.tree())).map(str::to_owned);
|
||||
request(fixture.ctx(), FocusTarget::Doc(OPENER));
|
||||
fixture.settle();
|
||||
assert_eq!(focused(&fixture).as_deref(), Some("Opener"), "returns {returns}: the opener has the focus");
|
||||
editing.set(true);
|
||||
fixture.settle();
|
||||
request(fixture.ctx(), FocusTarget::Doc(EDITOR));
|
||||
fixture.settle();
|
||||
assert_eq!(focused(&fixture).as_deref(), Some("Field"), "returns {returns}: the editor took the focus");
|
||||
editing.set(false);
|
||||
fixture.settle();
|
||||
assert_eq!(focused(&fixture).as_deref() == Some("Opener"), returns, "returns {returns}: the focus went back to the opener only when asked");
|
||||
}
|
||||
}
|
||||
@@ -72,8 +72,8 @@ mod zoom_motion;
|
||||
|
||||
pub use momentary::{Momentary, MomentaryCommands, MomentaryTool};
|
||||
pub use navigate::{
|
||||
Autoscroll, FlickPan, MiddleButton, NavigateBar, NavigateBarOutput, NavigationOptions, PageKey, WheelAction, WheelInput, WheelNavigation,
|
||||
WheelScheme, pan,
|
||||
Autoscroll, FlickPan, MiddleAutoscrollFeel, MiddleButton, NavigateBar, NavigateBarOutput, NavigationOptions, PageKey, WheelAction, WheelInput,
|
||||
WheelNavigation, WheelScheme, pan,
|
||||
};
|
||||
pub use rotate::{RotateView, RotateViewOutput, RotateViewStyle, ViewTurn};
|
||||
pub use tools::{HandTool, LayerBounds, RotateViewTool, ViewCommands, ViewRequest, ViewTarget, ZoomTool};
|
||||
@@ -664,7 +664,11 @@ impl<'a> Canvas<'a> {
|
||||
let left = crate::runtime::pointer::with_pass_pointer(&ctx, |pointer| {
|
||||
pointer.focus_lost || pointer.events.iter().any(|event| matches!(event, craft_behavior::PointerEvent::Gone))
|
||||
});
|
||||
let unfocused = left || !ctx.input(|i| i.focused);
|
||||
let feel = self.navigation.middle_autoscroll;
|
||||
// The reader's run lives while the canvas holds the focus: a modal over it or another control taking
|
||||
// the keys ends it once the button is up.
|
||||
let canvas_left = feel == MiddleAutoscrollFeel::Reader && !run.held() && !cx.is_focused();
|
||||
let unfocused = left || !ctx.input(|i| i.focused) || canvas_left;
|
||||
let off = self.navigation.middle_button != MiddleButton::AutoScroll;
|
||||
if keyed || ended || down || input.press.is_some() || unfocused || input.pos.is_none() || off {
|
||||
// Escape only stops the scroll; any other key also does its own job.
|
||||
@@ -680,7 +684,7 @@ impl<'a> Canvas<'a> {
|
||||
if phase.start().is_some_and(|start| start.button == PointerButton::Middle) {
|
||||
match phase {
|
||||
PressPhase::DragStart { .. } | PressPhase::Drag { .. } => run.drag(),
|
||||
PressPhase::Release { .. } | PressPhase::Cancel { .. } => run.release(),
|
||||
PressPhase::Release { .. } | PressPhase::Cancel { .. } => run.release(feel),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -694,7 +698,7 @@ impl<'a> Canvas<'a> {
|
||||
cx.focus_own();
|
||||
}
|
||||
let Some(pointer) = input.pos.filter(|_| run.mark().is_some()) else { break 'pass false };
|
||||
let step = run.step(pointer, frame::clock(&ctx));
|
||||
let step = run.step(pointer, frame::clock(&ctx), self.navigation.middle_autoscroll);
|
||||
let step = if self.navigation.invert_middle { -step } else { step };
|
||||
crate::runtime::cursor::request(&ctx, run.cursor(Some(pointer)).into(), CursorPriority::Drag);
|
||||
frame::request_repaint(&ctx);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! `MiddleAutoscroll`: the press, dead zone, mark and end of a middle-button autoscroll.
|
||||
|
||||
use super::Autoscroll;
|
||||
use super::{Autoscroll, MiddleAutoscrollFeel};
|
||||
use crate::canvas::frame_step;
|
||||
use crate::primitives::{Draw, PaintShape, StrokeWidth};
|
||||
use crate::style::StyleColor;
|
||||
@@ -43,11 +43,21 @@ pub(crate) struct MiddleAutoscroll {
|
||||
/// A press ended the run: it and its release reach no tool and start nothing.
|
||||
swallow: bool,
|
||||
last: Option<f64>,
|
||||
/// Under [`MiddleAutoscrollFeel::Reader`], the stepped passes the held press rested past the dead zone.
|
||||
held_passes: u32,
|
||||
}
|
||||
|
||||
impl MiddleAutoscroll {
|
||||
/// Pointer distance around the mark, in screen points, that does not scroll.
|
||||
pub(crate) const DEAD_ZONE: f32 = 15.0;
|
||||
/// Under [`MiddleAutoscrollFeel::Reader`], the held passes past the dead zone after which a release ends the run.
|
||||
const READER_HELD_PASSES: u32 = 2;
|
||||
/// Under [`MiddleAutoscrollFeel::Reader`], the power of the pointer's distance the speed grows with.
|
||||
const READER_EXPONENT: f32 = 2.2;
|
||||
/// Under [`MiddleAutoscrollFeel::Reader`], points per second per unit of the distance raised to the exponent.
|
||||
const READER_GAIN: f32 = 0.04;
|
||||
/// The farthest distance the reader's speed is computed from, so the power of a hostile pointer stays finite.
|
||||
const READER_MAX_DISTANCE: f32 = 1_000_000.0;
|
||||
|
||||
/// Starts the autoscroll with the mark at `at`, the point of the press that is now held. A point that is not finite
|
||||
/// starts nothing.
|
||||
@@ -57,6 +67,7 @@ impl MiddleAutoscroll {
|
||||
self.held = true;
|
||||
self.dragged = false;
|
||||
self.last = None;
|
||||
self.held_passes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,25 +78,56 @@ impl MiddleAutoscroll {
|
||||
|
||||
/// The press that started the run came up (or was cancelled): after a drag that ends the run, after a click the run
|
||||
/// goes on.
|
||||
pub(crate) fn release(&mut self) {
|
||||
let dragged = self.held && self.dragged;
|
||||
///
|
||||
/// Under [`MiddleAutoscrollFeel::Reader`] the drag threshold does not count: the release ends the run after the held
|
||||
/// press rested past the dead zone for two stepped passes, and keeps it after a shorter hold.
|
||||
pub(crate) fn release(&mut self, feel: MiddleAutoscrollFeel) {
|
||||
let ends = match feel {
|
||||
MiddleAutoscrollFeel::Reader => self.held && self.held_passes >= Self::READER_HELD_PASSES,
|
||||
_ => self.held && self.dragged,
|
||||
};
|
||||
self.held = false;
|
||||
self.dragged = false;
|
||||
if dragged {
|
||||
if ends {
|
||||
self.end();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the press that started the run is still down.
|
||||
pub(crate) fn held(&self) -> bool {
|
||||
self.held
|
||||
}
|
||||
|
||||
/// The view's step this pass for the pointer at `pointer`, `clock` being the pass clock in seconds: screen points
|
||||
/// toward the pointer, zero inside the dead zone, while stopped and in the first pass after the press. Later passes
|
||||
/// of one frame share the clock, so they step zero.
|
||||
pub(crate) fn step(&mut self, pointer: Pos2, clock: f64) -> Vec2 {
|
||||
///
|
||||
/// Under [`MiddleAutoscrollFeel::Reader`] the speed is the pointer's whole vertical distance from the mark raised to
|
||||
/// the power 2.2, times 0.04, in points per second, and a held press resting past the dead zone counts its stepped
|
||||
/// passes for [`release`](Self::release).
|
||||
pub(crate) fn step(&mut self, pointer: Pos2, clock: f64, feel: MiddleAutoscrollFeel) -> Vec2 {
|
||||
let Some(origin) = self.origin else { return Vec2::ZERO };
|
||||
let dt = self.last.map_or(0.0, |last| frame_step(clock - last));
|
||||
if clock.is_finite() {
|
||||
self.last = Some(clock);
|
||||
}
|
||||
Autoscroll::step(Self::past(origin, pointer), dt as f32)
|
||||
let past = Self::past(origin, pointer);
|
||||
match feel {
|
||||
MiddleAutoscrollFeel::Reader => {
|
||||
if past == Vec2::ZERO || dt <= 0.0 {
|
||||
return Vec2::ZERO;
|
||||
}
|
||||
// A frame's later passes take no time: counting them would count one frame's hold twice.
|
||||
if self.held {
|
||||
self.held_passes = self.held_passes.saturating_add(1);
|
||||
}
|
||||
let dy = pointer.y - origin.y;
|
||||
let speed = dy.abs().min(Self::READER_MAX_DISTANCE).powf(Self::READER_EXPONENT) * Self::READER_GAIN;
|
||||
let step = dy.signum() * speed * dt as f32;
|
||||
if step.is_finite() { Vec2::new(0.0, step) } else { Vec2::ZERO }
|
||||
}
|
||||
_ => Autoscroll::step(past, dt as f32),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer's vertical offset from `origin` beyond the dead zone; zero inside it.
|
||||
@@ -103,6 +145,7 @@ impl MiddleAutoscroll {
|
||||
self.held = false;
|
||||
self.dragged = false;
|
||||
self.last = None;
|
||||
self.held_passes = 0;
|
||||
}
|
||||
|
||||
/// The press that ended the run is still down: it is the autoscroll's to its release, so a stopping click cannot
|
||||
|
||||
@@ -17,7 +17,7 @@ mod wheel;
|
||||
pub(crate) use autoscroll::{MiddleAutoscroll, paint_mark};
|
||||
pub use bar::{NavigateBar, NavigateBarOutput};
|
||||
pub use keys::PageKey;
|
||||
pub use options::{MiddleButton, NavigationOptions, WheelScheme};
|
||||
pub use options::{MiddleAutoscrollFeel, MiddleButton, NavigationOptions, WheelScheme};
|
||||
pub use wheel::{WheelAction, WheelInput, WheelNavigation};
|
||||
|
||||
use super::frame_step;
|
||||
|
||||
@@ -44,6 +44,23 @@ pub struct NavigationOptions {
|
||||
pub middle_button: craft_behavior::MiddleButton,
|
||||
/// The middle-button scroll runs the other way. Off.
|
||||
pub invert_middle: bool,
|
||||
/// How a middle-button autoscroll feels under [`MiddleButton::AutoScroll`]. [`MiddleAutoscrollFeel::Edge`].
|
||||
pub middle_autoscroll: MiddleAutoscrollFeel,
|
||||
}
|
||||
|
||||
/// How a middle-button autoscroll runs: its speed, what its release does and what ends it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum MiddleAutoscrollFeel {
|
||||
/// The canvas's one autoscroll rule (`Autoscroll::step`) on the pointer's offset past the dead zone; letting go
|
||||
/// after a drag past the drag threshold ends the run.
|
||||
#[default]
|
||||
Edge,
|
||||
/// A document reader's (PdfCraft): the speed grows as the pointer's whole distance from the mark raised to the
|
||||
/// power 2.2, times 0.04, in points per second; letting go ends the run only after the held pointer rested past
|
||||
/// the dead zone for two stepped passes (a shorter hold is a click, which keeps it); and the run ends when the
|
||||
/// canvas loses the focus (a modal over it, another control taking the keys).
|
||||
Reader,
|
||||
}
|
||||
|
||||
/// What a plain and a modified wheel do over a canvas.
|
||||
@@ -86,6 +103,7 @@ impl Default for NavigationOptions {
|
||||
touchpad_glide: false,
|
||||
middle_button: craft_behavior::MiddleButton::default(),
|
||||
invert_middle: false,
|
||||
middle_autoscroll: MiddleAutoscrollFeel::Edge,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,8 @@ use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_behavior::{Axis, CancelReason, CanvasView, GESTURE_GAP, MotionMode, ZoomLadder};
|
||||
use craft_keymap::{Mods, Platform};
|
||||
use craft_ui::canvas::{
|
||||
Autoscroll, Canvas, CanvasSpace, CanvasTool, Guide, GuideKey, MiddleButton, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions,
|
||||
ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer, ViewCommands, ViewRequest, WheelNavigation, WheelScheme, tool_pass,
|
||||
Autoscroll, Canvas, CanvasSpace, CanvasTool, Guide, GuideKey, MiddleAutoscrollFeel, MiddleButton, Momentary, MomentaryCommands, MomentaryTool,
|
||||
NavigationOptions, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer, ViewCommands, ViewRequest, WheelNavigation, WheelScheme, tool_pass,
|
||||
};
|
||||
use craft_ui::canvas_controls::Guides;
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
@@ -500,6 +500,55 @@ fn a_latched_middle_scroll_ends_on_escape_a_second_press_or_the_wheel_and_a_held
|
||||
/// The seconds of one fixture frame.
|
||||
const FRAME: f64 = 1.0 / 60.0;
|
||||
|
||||
/// A canvas over a large document whose middle button autoscrolls with `feel`: the fixture and the view it shows.
|
||||
fn feel_rig(feel: MiddleAutoscrollFeel) -> (Fixture, Rc<Cell<CanvasView>>) {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.middle_button = MiddleButton::AutoScroll;
|
||||
options.middle_autoscroll = feel;
|
||||
let view = Rc::new(Cell::new(CanvasView::new(egui::Rect::ZERO, Point::new(2000.0, 2000.0), 1.0)));
|
||||
let shown = Rc::clone(&view);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = Canvas::new("Document").document(Size::new(4000.0, 4000.0)).navigation(options).view(given).show(ui, |_, _| {});
|
||||
shown.set(canvas.output.view.unwrap_or(given));
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, view)
|
||||
}
|
||||
|
||||
/// Under `MiddleAutoscrollFeel::Reader` (a document reader's autoscroll) a held press dragged past the drag threshold
|
||||
/// but let go inside the dead zone keeps the run, where the default feel ends it; and the speed grows with the
|
||||
/// pointer's whole distance from the mark, |d|^2.2 x 0.04 points per second.
|
||||
#[trial]
|
||||
fn a_reader_autoscroll_keeps_a_short_hold_and_speeds_up_with_the_whole_distance() {
|
||||
for feel in [MiddleAutoscrollFeel::Edge, MiddleAutoscrollFeel::Reader] {
|
||||
let (mut fixture, view) = feel_rig(feel);
|
||||
let anchor = view.get().rect.center();
|
||||
let near = anchor + Vec2::new(0.0, 12.0);
|
||||
middle(&mut fixture, anchor, true);
|
||||
fixture.frame(vec![pointer::moved(anchor + Vec2::new(0.0, 6.0))]);
|
||||
fixture.frame(vec![pointer::moved(near)]);
|
||||
middle(&mut fixture, near, false);
|
||||
fixture.frame(vec![pointer::moved(anchor + Vec2::new(0.0, 80.0))]);
|
||||
let reader = feel == MiddleAutoscrollFeel::Reader;
|
||||
assert_eq!(scrolls(&mut fixture, &view), reader, "{feel:?}: a release inside the dead zone keeps the run only for the reader");
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
}
|
||||
|
||||
let (mut fixture, view) = feel_rig(MiddleAutoscrollFeel::Reader);
|
||||
let anchor = view.get().rect.center();
|
||||
middle(&mut fixture, anchor, true);
|
||||
middle(&mut fixture, anchor, false);
|
||||
fixture.frame(vec![pointer::moved(anchor + Vec2::new(0.0, 50.0))]);
|
||||
fixture.idle(2);
|
||||
let before = view.get().center.y;
|
||||
fixture.idle(60);
|
||||
let travelled = view.get().center.y - before;
|
||||
let expected = 50f64.powf(2.2) * 0.04 * 60.0 * FRAME;
|
||||
assert!((travelled - expected).abs() < 1.0, "a second 50 points below the mark scrolls {expected}, not {travelled}");
|
||||
}
|
||||
|
||||
type EasedRig = (Fixture, Rc<Cell<CanvasView>>, Rc<Cell<bool>>);
|
||||
|
||||
/// A canvas over a large document with the eased wheel, whose app reruns the pass of a frame while the flag is set:
|
||||
|
||||
@@ -364,6 +364,11 @@ pub trait Component: Meta + Sized {
|
||||
/// goes away with focus inside (a canvas text editor hands it back to the canvas). Containers and collections take
|
||||
/// their scope from their props, not from this.
|
||||
const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy = crate::runtime::focus::FocusPolicy::NONE;
|
||||
/// The focus scope this instance runs in. The default is `FOCUS_SCOPE`; a component whose scope is a choice of its
|
||||
/// caller (an editor that hands focus back to where it came from, or not) overrides it.
|
||||
fn focus_scope(&self) -> crate::runtime::focus::FocusPolicy {
|
||||
Self::FOCUS_SCOPE
|
||||
}
|
||||
/// Keys the focused component keeps from egui and the shortcut dispatcher.
|
||||
const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(Self::INPUT);
|
||||
/// The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends
|
||||
|
||||
@@ -317,8 +317,9 @@ impl<C: Component> ShapeHooks<C> for LeafHooks {
|
||||
self.scope
|
||||
}
|
||||
|
||||
fn focus(&self, _: &C) -> Option<crate::runtime::focus::FocusPolicy> {
|
||||
(C::FOCUS_SCOPE != crate::runtime::focus::FocusPolicy::NONE).then_some(C::FOCUS_SCOPE)
|
||||
fn focus(&self, comp: &C) -> Option<crate::runtime::focus::FocusPolicy> {
|
||||
let scope = comp.focus_scope();
|
||||
(scope != crate::runtime::focus::FocusPolicy::NONE).then_some(scope)
|
||||
}
|
||||
|
||||
fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 {
|
||||
|
||||
@@ -463,7 +463,12 @@ impl State {
|
||||
None => return Vec::new(),
|
||||
},
|
||||
};
|
||||
let found = self.find_stop(key).or_else(|| self.stops.iter().chain(&self.last_stops).find(|rec| rec.stop.id == key.0).cloned());
|
||||
// A request for a part lands on that part, never on another stop of its component: a part first declared in
|
||||
// this pass registers its stop after `update` asks for it, and then takes the focus (the awaited stop below).
|
||||
let found = self.find_stop(key).or_else(|| match key.1 {
|
||||
Some(_) => None,
|
||||
None => self.stops.iter().chain(&self.last_stops).find(|rec| rec.stop.id == key.0).cloned(),
|
||||
});
|
||||
match found {
|
||||
Some(rec) => self.focus_stop(rec),
|
||||
// An app's own widget, or a stop that registers later in this pass, which then takes the focus.
|
||||
|
||||
@@ -11,6 +11,7 @@ pub(crate) mod focus;
|
||||
pub(crate) mod frame;
|
||||
pub(crate) mod latch;
|
||||
pub(crate) mod memory;
|
||||
pub(crate) mod part_request;
|
||||
pub(crate) mod paste;
|
||||
pub(crate) mod pen;
|
||||
pub(crate) mod pointer;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! A request for a part lands on that part: one declared in the pass its owner asks for it (from `update`, before the
|
||||
//! stops register) waits for its stop instead of landing on another of the owner's parts.
|
||||
|
||||
use craft_behavior::{Input, PartKey, PartRef};
|
||||
use craft_ui::contract::{Common, Component, Cx, Focus as _, MeasureCx, PartsCx, Props as _, Role, Show as _};
|
||||
use craft_ui::runtime::focus::{FocusTarget, KeyUse, request};
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use craft_ui_test_kit::contract::PlainStyle;
|
||||
use egui::{Id, Rect, Vec2, pos2};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
const CELL: PartKey = PartKey::new("cell");
|
||||
|
||||
/// Cells 0 and 2 always, cell 1 once `late` is set; a focused row asks for cell 1 from `update` in the pass it shows.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
struct Row {
|
||||
#[common]
|
||||
common: Common,
|
||||
late: bool,
|
||||
}
|
||||
|
||||
impl Component for Row {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
type Style = PlainStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn keys(&self) -> KeyUse {
|
||||
KeyUse::of(Input::Pointer)
|
||||
}
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: RowStyleKey) -> PlainStyle {
|
||||
PlainStyle::default()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(150.0, 30.0)
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let third = rect.width() / 3.0;
|
||||
let cell = |at: f32| Rect::from_min_max(pos2(rect.min.x + third * at, rect.min.y), pos2(rect.min.x + third * (at + 1.0), rect.max.y));
|
||||
cx.part(CELL.at(0), cell(0.0)).focusable();
|
||||
if self.late {
|
||||
cx.part(CELL.at(1), cell(1.0)).focusable();
|
||||
}
|
||||
cx.part(CELL.at(2), cell(2.0)).focusable();
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
if self.late && cx.is_focused() && cx.focus_arrived().is_none() {
|
||||
cx.focus_part(CELL.at(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_part_asked_for_in_the_pass_it_appears_takes_the_focus_not_a_sibling() {
|
||||
let late = Rc::new(Cell::new(false));
|
||||
let root = Rc::new(Cell::new(Id::NULL));
|
||||
let (shown, seen) = (Rc::clone(&late), Rc::clone(&root));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let response = Row { common: Common::new(), late: shown.get() }.label("Row").show(ui);
|
||||
seen.set(response.id);
|
||||
});
|
||||
fixture.settle();
|
||||
let id = root.get();
|
||||
request(fixture.ctx(), FocusTarget::Part(id, CELL.at(2)));
|
||||
fixture.settle();
|
||||
assert_eq!(fixture.focused_stop(), Some((id, Some(CELL.at(2)))), "the last cell has the focus");
|
||||
late.set(true);
|
||||
fixture.settle();
|
||||
let middle: PartRef = CELL.at(1);
|
||||
assert_eq!(fixture.focused_stop(), Some((id, Some(middle))), "the cell asked for takes the focus, not the first cell");
|
||||
}
|
||||
Reference in new issue
Block a user