From 7d0bf2b01af7c825a822fc27826fb892fad1f4cc Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 11 Nov 2026 23:42:39 +0000 Subject: [PATCH] Scrub sources: a drag on a field that is not in edit scrubs it (NumberField, every TimecodeField), a press that begins in edit stays the text's, and a drag from the popup slider's chevron moves the value as far as the slider would and its release closes the slider --- crates/timeline/src/ui/timecode.rs | 18 +++---- crates/timeline/tests/it/main.rs | 1 + crates/timeline/tests/it/timecode.rs | 35 +++++++++++++ crates/ui-contract/src/contract/cx/context.rs | 3 ++ .../ui-contract/src/contract/label/props.rs | 39 ++++++++++++--- crates/ui-contract/src/contract/mod.rs | 3 +- crates/ui-contract/src/contract/run.rs | 1 + .../ui-contract/src/contract/steps/label.rs | 41 ++++++++++------ .../ui-contract/src/contract/steps/update.rs | 2 +- crates/ui-contract/src/contract/text.rs | 8 ++- crates/ui-widgets/src/text/number.rs | 49 ++++++++++++++----- crates/ui-widgets/tests/it/label/kit.rs | 2 +- crates/ui-widgets/tests/it/text/number.rs | 44 ++++++++++++++++- 13 files changed, 194 insertions(+), 52 deletions(-) create mode 100644 crates/timeline/tests/it/timecode.rs diff --git a/crates/timeline/src/ui/timecode.rs b/crates/timeline/src/ui/timecode.rs index 41ce693789..82dd53b6bc 100644 --- a/crates/timeline/src/ui/timecode.rs +++ b/crates/timeline/src/ui/timecode.rs @@ -184,7 +184,8 @@ impl Outcome for TimecodeFieldOutput { /// - Click (or Tab) to type: the text is selected; Enter or a click away commits through [`parse_time`] relative to /// the current value; Esc cancels. A time that does not parse commits nothing and is reported on /// [`TimecodeFieldOutput::error`]. -/// - A drag on the field's side label scrubs one frame per point, Shift ten, as a gesture of `EditEvent`s. +/// - A drag on the field while it is not in edit, or on its side label, scrubs one frame per point, Shift ten, as a +/// gesture of `EditEvent`s; a click without a drag edits, and in edit a drag selects text. /// - Never before `min` (the sequence start). One Tab stop; Up and Down step one frame, Shift ten. /// - AccessKit: a spin button whose text is the formatted time. #[derive(Component, Props)] @@ -197,8 +198,6 @@ pub struct TimecodeField<'a> { #[prop] min: Tick, options: TextOptions, - /// The readout form: large accent text that scrubs under a drag on the field itself. - large: bool, } impl<'a> TimecodeField<'a> { @@ -209,17 +208,15 @@ impl<'a> TimecodeField<'a> { options.select_on_focus = true; options.submits = true; options.steps_value = true; - TimecodeField { common: Common::new(), value, format, min: Tick::ZERO, options, large: false }.label(label) + TimecodeField { common: Common::new(), value, format, min: Tick::ZERO, options }.label(label) } - /// The large readout: the prominent text role in the accent ink. A drag on the field itself scrubs the time, as a - /// drag on the side label does for the plain field. + /// The large readout: the prominent text role in the accent ink. #[must_use] pub fn large(mut self) -> Self { self.options.mono = false; self.options.role = TypeRole::BodyLarge; self.options.ink = Some(Ink::Accent); - self.large = true; self } @@ -246,8 +243,9 @@ impl Component for TimecodeField<'_> { FieldStyle::at(cx) } + /// A drag on the body scrubs a field that is not in edit. fn sense(&self) -> Sense { - if self.large { Sense::CLICK | Sense::DRAG | Sense::FOCUS | Sense::TAKE_FOCUS } else { Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS } + Sense::CLICK | Sense::DRAG | Sense::FOCUS | Sense::TAKE_FOCUS } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { @@ -269,13 +267,13 @@ impl Component for TimecodeField<'_> { Some(self.value.reborrow()) } - /// A drag on the side label moves the time a frame per point. + /// A drag on the field while it is not in edit, or on its side label, moves the time a frame per point. fn scrub(&self) -> Option> { let (rate, min) = (self.format.rate, self.min); let frames = rate.frame_at(min) as f64..=rate.frame_at(Tick::MAX) as f64; let drag = ValueDrag::relative(1.0, frames).warp(true).hide_cursor(true).coarse(LARGE_STEPS); let scrub = Scrub::new(drag, move |time: &Tick| rate.frame_at(*time) as f64, move |frames: f64| rate.tick_of(frames.round() as i64).max(min)); - Some(if self.large { scrub.on_field() } else { scrub }) + Some(scrub.on_field().by_label()) } /// Up and Down step the time by a frame, with Shift by ten. diff --git a/crates/timeline/tests/it/main.rs b/crates/timeline/tests/it/main.rs index d4720fdb0b..4b188e6060 100644 --- a/crates/timeline/tests/it/main.rs +++ b/crates/timeline/tests/it/main.rs @@ -3,3 +3,4 @@ mod features; mod lanes; mod panel; +mod timecode; diff --git a/crates/timeline/tests/it/timecode.rs b/crates/timeline/tests/it/timecode.rs new file mode 100644 index 0000000000..ce44551185 --- /dev/null +++ b/crates/timeline/tests/it/timecode.rs @@ -0,0 +1,35 @@ +//! The timecode field: a drag scrubs a field that is not in edit. + +use craft_timeline::ui::TimecodeField; +use craft_timeline::{FrameRate, Tick, TimeFormat}; +use craft_ui::contract::{Bind, Role, Show as _}; +use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial}; +use egui::{Ui, Vec2}; + +/// One and a half seconds: "00:00:01:15" at 30 frames per second. +fn start() -> Tick { + Tick::from_seconds_f64(1.5) +} + +fn field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + TimecodeField::new("Time", Bind::bound(data.value("time", start())), TimeFormat::timecode(FrameRate::FPS_30)).show(ui).edit.into() +} + +fn fixture() -> Fixture { + let mut fixture = Fixture::story(&Story::new("timecode", field)); + fixture.settle(); + fixture +} + +fn time(fixture: &mut Fixture) -> Tick { + *fixture.data().value("time", start()) +} + +#[trial] +fn a_drag_on_a_timecode_field_moves_the_time() { + let mut fixture = fixture(); + let target = fixture.by_role(Role::SPIN_BUTTON).first().copied().expect("the field"); + fixture.drag(&target, Vec2::new(20.0, 0.0)); + fixture.settle(); + assert!(time(&mut fixture) > start(), "a drag to the right moved the time on"); +} diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 6091e86229..3cb104a922 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -168,6 +168,9 @@ pub struct CxCore<'a> { pub(crate) editor_inputs: Vec, /// The text part's draft is not a value of its codec. pub(crate) text_invalid: bool, + /// The text part takes the pointer this pass: the field is in edit, or the press under way began in edit. A body + /// scrub (`Scrub::on_field`) leaves such a press to the text. + pub(crate) text_takes_pointer: bool, /// The row and column counts of the collection, which the item step records for its node. pub(crate) grid: crate::runtime::access::GridPlace, /// The text part's completion list is open: Escape belongs to its popup, not to the component's gesture. diff --git a/crates/ui-contract/src/contract/label/props.rs b/crates/ui-contract/src/contract/label/props.rs index c1b0ea681e..79f1457413 100644 --- a/crates/ui-contract/src/contract/label/props.rs +++ b/crates/ui-contract/src/contract/label/props.rs @@ -4,7 +4,7 @@ use crate::contract::Tooltip; use crate::primitives::IconSpec; use crate::runtime::access::scope::FieldLabelRole; use crate::runtime::env::{Env, Label}; -use craft_behavior::{ColumnWidth, ValueDrag}; +use craft_behavior::{ColumnWidth, PartRef, ValueDrag}; use std::sync::Arc; /// How a side label is shown. @@ -193,18 +193,27 @@ impl SideLabel { } } -/// How a drag on the side label (or on the control itself) changes a control's value: the drag maths over the -/// control's number. +/// How a drag changes a control's value: the drag maths over the control's number, and the sources a drag starts on +/// (`by_label`, `on_field`, `part`). A scrub with no source does nothing. pub struct Scrub { pub(crate) drag: ValueDrag, + pub(crate) by_label: bool, pub(crate) on_field: bool, + pub(crate) parts: Vec<(PartRef, ValueDrag)>, pub(crate) read: Arc f64 + Send + Sync>, pub(crate) write: Arc V + Send + Sync>, } impl Clone for Scrub { fn clone(&self) -> Self { - Scrub { drag: self.drag.clone(), on_field: self.on_field, read: Arc::clone(&self.read), write: Arc::clone(&self.write) } + Scrub { + drag: self.drag.clone(), + by_label: self.by_label, + on_field: self.on_field, + parts: self.parts.clone(), + read: Arc::clone(&self.read), + write: Arc::clone(&self.write), + } } } @@ -212,11 +221,27 @@ impl Scrub { /// A scrub by `drag`, reading the number a value holds with `read` and making a value of a number with `write`. /// Both may capture the control's decimals and step, so a scrubbed value is rounded the way the control rounds. pub fn new(drag: ValueDrag, read: impl Fn(&V) -> f64 + Send + Sync + 'static, write: impl Fn(f64) -> V + Send + Sync + 'static) -> Self { - Scrub { drag, on_field: false, read: Arc::new(read), write: Arc::new(write) } + Scrub { drag, by_label: false, on_field: false, parts: Vec::new(), read: Arc::new(read), write: Arc::new(write) } } - /// The drag starts on the control itself instead of its side label, for a readout with no label. The control - /// must sense a drag. + /// A drag on the control's side label scrubs, with or without the focus in the control; the label senses the + /// drag from the pass after the control first declared it. + #[must_use] + pub fn by_label(mut self) -> Self { + self.by_label = true; + self + } + + /// A drag on the part `part` scrubs by `drag`, with or without the focus in the control: a scrub handle, or an + /// opener whose drag moves the value as far as its popup's control would. + #[must_use] + pub fn part(mut self, part: impl Into, drag: ValueDrag) -> Self { + self.parts.push((part.into(), drag)); + self + } + + /// A drag on the control's body scrubs while its text part does not take the pointer: a field that is not in + /// edit. A click enters edit, and in edit a drag selects text. The control must sense a drag. #[must_use] pub fn on_field(mut self) -> Self { self.on_field = true; diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index f757f79bba..5b4409dc6c 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -373,7 +373,8 @@ pub trait Component: Meta + Sized { proposed == host } - /// Lets a drag on the field's side label change the value; the pipeline runs the gesture (16.3, B2). + /// Lets a drag on the scrub's sources (the side label, the body, a part) change the value; the pipeline runs the + /// gesture (16.3, B2). fn scrub(&self) -> Option>> { None } diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index fee764d25e..ee33636e51 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -375,6 +375,7 @@ fn blank_core<'a>( editor: None, editor_inputs: Vec::new(), text_invalid: false, + text_takes_pointer: false, grid: crate::runtime::access::GridPlace::default(), escape_to_list: false, text_access: std::cell::RefCell::new(None), diff --git a/crates/ui-contract/src/contract/steps/label.rs b/crates/ui-contract/src/contract/steps/label.rs index d5cc303bd0..afe241b90b 100644 --- a/crates/ui-contract/src/contract/steps/label.rs +++ b/crates/ui-contract/src/contract/steps/label.rs @@ -1,4 +1,4 @@ -//! Step 9's side-label part: the label scrub. +//! Step 9's scrub: a drag on the side label, the body or a part changes the value. use crate::contract::{Component, Cx}; use crate::runtime::access::scope; @@ -7,10 +7,18 @@ use crate::runtime::windows::WindowHost; use craft_behavior::{CancelReason, Cursor, CursorPriority, DragWarp, GesturePhase, PaintedCursor, ValueDrag}; use egui::{Pos2, Vec2}; -/// The press that carries a scrub: the field's own, or for a scrub by the label, the label's. -pub(super) fn scrub_press(comp: &C, cx: &Cx<'_, C>) -> Option { +/// The press that carries a scrub and the drag it scrubs by: a scrub part's, the side label's, or the field's own +/// while its text part leaves it the pointer. +pub(super) fn scrub_press(comp: &C, cx: &Cx<'_, C>) -> Option<(craft_behavior::PressState, ValueDrag)> { let scrub = comp.scrub()?; - if scrub.on_field { Some(cx.core.press) } else { scope::field_label(&cx.core.ctx).map(|label| label.press) } + let pressed = |press: &craft_behavior::PressState| press.phase.is_press(); + let part = scrub.parts.iter().find_map(|(part, drag)| { + let press = cx.core.results.get(&(part.key, part.index)).map(|result| result.press)?; + pressed(&press).then(|| (press, drag.clone())) + }); + let label = || scrub.by_label.then(|| scope::field_label(&cx.core.ctx)).flatten().map(|label| label.press).filter(pressed); + let field = || (scrub.on_field && !cx.core.text_takes_pointer).then_some(cx.core.press).filter(pressed); + part.or_else(|| label().or_else(field).map(|press| (press, scrub.drag.clone()))) } /// The value a label scrub started from. @@ -45,9 +53,9 @@ fn scrub_warp(cx: &mut Cx<'_, C>, drag: &ValueDrag, pos: Pos2) -> shift } -/// Step 9, before the component: a drag on the side label (or on the component itself, for a scrub that -/// `Scrub::on_field` declares) scrubs the value of a component that opts in with `Component::scrub`. A label scrub -/// registers the control with its label scope so the label senses the drag from the next pass on. +/// Step 9, before the component: a drag on a source of the component's `Component::scrub` (its side label, its body, +/// a part) scrubs its value. A label scrub registers the control with its label scope so the label senses the drag +/// from the next pass on. pub(crate) fn scrub_by_label(comp: &C, cx: &mut Cx<'_, C>) { use crate::contract::cx::Edit as _; use craft_behavior::{PressCancel, PressPhase}; @@ -59,30 +67,31 @@ pub(crate) fn scrub_by_label(comp: &C, cx: &mut Cx<'_, C>) { } return; } - let label = (!scrub.on_field).then(|| scope::field_label(&cx.core.ctx)).flatten(); + let label = scrub.by_label.then(|| scope::field_label(&cx.core.ctx)).flatten(); if label.is_some() { scope::register_scrub(&cx.core.ctx); } - // The scrub's source shows the horizontal resize cursor under the pointer. - let source_hovered = if scrub.on_field { cx.core.response.hovered() } else { label.is_some_and(|label| label.hovered) }; - if source_hovered { + // A scrub's source shows the horizontal resize cursor under the pointer. + let part_hovered = scrub.parts.iter().any(|(part, _)| cx.core.results.get(&(part.key, part.index)).is_some_and(|result| result.hovered)); + let field_hovered = scrub.on_field && !cx.core.text_takes_pointer && cx.core.response.hovered(); + if part_hovered || field_hovered || label.is_some_and(|label| label.hovered) { crate::runtime::cursor::request(&cx.core.ctx, Cursor::System(craft_behavior::CursorIcon::ResizeHorizontal), CursorPriority::Part); } - let Some(press) = scrub_press(comp, cx) else { return }; + let Some((press, drag)) = scrub_press(comp, cx) else { return }; let start_id = sub(cx.core.id, "scrub_start"); let rtl = cx.core.env.direction().is_rtl(); match press.phase { PressPhase::DragStart { .. } => { cx.core.memory.shown::(start_id).0 = cx.value().map_or(0.0, |value| (scrub.read)(value)); *cx.core.memory.shown::(sub(cx.core.id, "scrub_warp")) = ScrubWarp::default(); - hide_scrub_cursor(cx, &scrub.drag); + hide_scrub_cursor(cx, &drag); cx.begin(); } PressPhase::Drag { pos, .. } => { - hide_scrub_cursor(cx, &scrub.drag); + hide_scrub_cursor(cx, &drag); let start = cx.core.memory.shown::(start_id).0; - let shift = scrub_warp(cx, &scrub.drag, pos); - if let Some(next) = scrub.drag.value_shifted(start, &press, rtl, shift) { + let shift = scrub_warp(cx, &drag, pos); + if let Some(next) = drag.value_shifted(start, &press, rtl, shift) { cx.propose((scrub.write)(next)); } } diff --git a/crates/ui-contract/src/contract/steps/update.rs b/crates/ui-contract/src/contract/steps/update.rs index cf834bcbbe..4213d7d8ff 100644 --- a/crates/ui-contract/src/contract/steps/update.rs +++ b/crates/ui-contract/src/contract/steps/update.rs @@ -36,7 +36,7 @@ pub(crate) fn update_inputs(core: &mut CxCore<'_>) { /// Step 9, before the component: a gesture cancelled under its press is live again once the press is released. pub(crate) fn gesture_gate(comp: &C, cx: &mut Cx<'_, C>) { - let held = cx.core.press_held() || scrub_press(comp, cx).is_some_and(|press| press.phase.button_down()); + let held = cx.core.press_held() || scrub_press(comp, cx).is_some_and(|(press, _)| press.phase.button_down()); let slot = gesture_key(cx.core.id); let gesture = cx.core.memory.shown::>>(slot); if gesture.dead && !held { diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 9f8a7185a4..f1f95c6cca 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -370,8 +370,10 @@ pub(crate) fn run( let enabled = cx.core.resolved.enabled && decl.options.enabled; let focusable = super::steps::takes_focus(cx.core.resolved) && decl.options.enabled; // A component that senses a drag on its root scrubs its value by it: the field takes the pointer only once it is - // in edit, and a click that enters it puts the caret where it went down. + // in edit, a press that begins in edit stays the text's (a drag selects), and a click that enters it puts the + // caret where it went down. let scrubs = cx.core.root_sense.contains(craft_behavior::Sense::DRAG); + let mut in_edit_before = false; if scrubs { let before = cx.core.memory.shown::(sub(id, "in_edit_before_press")); if cx.core.press.phase.is_drag() { @@ -383,8 +385,10 @@ pub(crate) fn run( } else if !cx.core.press.phase.button_down() { before.0 = focused; } + in_edit_before = before.0; } - let pointer = !scrubs || (focused && !cx.core.press.phase.is_drag()); + let pointer = !scrubs || in_edit_before || (focused && !cx.core.press.phase.is_drag()); + cx.core.text_takes_pointer = pointer; let click = match cx.core.press.phase { craft_behavior::PressPhase::Release { pos, click: true, .. } if scrubs && focusable => Some(pos), _ => None, diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index a78a7b3186..df8c67ead3 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -1,7 +1,8 @@ //! `NumberField`: a text part over [`NumberCodec`] with a range, a step, a unit, presets and a popup slider. //! //! Typing, expressions, unit spellings and locale digits are the codec's (`quantity::Reader`); the field adds the -//! range every written value stays in and the step that arrows, the wheel and the label scrub move by. +//! range every written value stays in and the step that arrows, the wheel and a scrub move by. A drag on a field that +//! is not in edit scrubs it; a click enters edit, where a drag selects text. #[cfg(feature = "testing")] mod stories; @@ -11,14 +12,16 @@ use super::words::TextWords; use super::{FieldStyle, text_part}; use crate::buttons::IconButton; use crate::contract::{ - Access, Bind, BindMut, Common, Component, Cx, Edit as _, Entry, Focus as _, Input, MeasureCx, Numeric, OverlayUi, PaintUi, PartsCx, Pointer as _, - Props as _, Role, Scrub, Styled as _, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Cx, Edit as _, Entry, Focus as _, Input, MeasureCx, Numeric, OverlayUi, Overlays as _, PaintUi, + PartsCx, Pointer as _, Props as _, Role, Scrub, Styled as _, WordSetCx as _, }; use crate::primitives::{TextOptions, TextRun}; use crate::runtime::env::{Label, LengthUnits, UnitKind, Units}; use crate::style::{ComponentStyle, StyleCx, SurfaceLook, TextLook, TypeRole}; use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps}; -use craft_behavior::{Codec, Flow, HitLevel, HitPriority, Metrics, NavMove, NumberCodec, PartKey, Sense, ValueDrag, decimals_for_step, wheel_step}; +use craft_behavior::{ + Codec, Flow, HitLevel, HitPriority, Metrics, NavMove, NumberCodec, PartKey, PressPhase, Sense, ValueDrag, decimals_for_step, wheel_step, +}; use craft_theme::{Stateful, States}; use egui::{Pos2, Rect, Vec2}; use std::borrow::Cow; @@ -33,7 +36,7 @@ pub use rule::NumberStepper; use rule::{Rule, Ruled, key_scale, round_to}; pub use value::{NamedOr, NumberName, NumberOutput, NumberPick, NumberValue}; -/// The step of an arrow press, the wheel and the label scrub when the field sets none. +/// The step of an arrow press, the wheel and a scrub when the field sets none. const DEFAULT_STEP: f64 = 1.0; /// The placeholder of a mixed field. const BLANK: &str = "\u{2014}"; @@ -86,7 +89,7 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// The range typed, stepped and scrubbed values stay in. #[prop] range: Option>, - /// What one arrow press, one wheel notch and one point of label scrub change; the default is 1. + /// What one arrow press, one wheel notch and one point of scrub change; the default is 1. #[prop(quantity = "step")] step: Option, /// Where an arrow press, a Page key and a wheel notch go from the current value, for values on a ladder (the zoom @@ -99,7 +102,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// The rows of the list a chevron after the field opens; Alt+Down opens it too. #[prop] presets: Option<&'a [Entry]>, - /// A chevron after the field opens a slider over `range` below it. + /// A chevron after the field opens a slider over `range` below it; pressing the chevron and dragging moves the + /// value at once, as far as the slider would, and the release closes the slider. #[prop] popup_slider: Option>, /// A typed value goes to the nearest multiple of the step when it commits. @@ -123,6 +127,9 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { scale: f64, options: TextOptions, scrub: bool, + /// The popup slider's track length, read from the tokens in parts: a drag on its chevron moves the value as far + /// as a drag on the slider would. + track: f32, picked: Option, unit_size: Vec2, } @@ -174,13 +181,14 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { scale: 1.0, options: TextOptions::default(), scrub: false, + track: 0.0, picked: None, unit_size: Vec2::ZERO, } .label(label) } - /// A drag on the field's side label scrubs the value. + /// A drag on the field's side label scrubs the value too, with or without the focus in the field. #[must_use] pub fn scrub_by_label(mut self) -> Self { self.scrub = true; @@ -326,8 +334,9 @@ impl Component for NumberField<'_, V> { } } + /// A drag on the body scrubs a field that is not in edit. fn sense(&self) -> Sense { - Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS + Sense::CLICK | Sense::DRAG | Sense::FOCUS | Sense::TAKE_FOCUS } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { @@ -357,6 +366,7 @@ impl Component for NumberField<'_, V> { fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { self.settle_lengths(&cx.env.units()); self.unit_size = self.unit_extent(cx); + self.track = cx.tokens.size.length.track; let rtl = cx.flow.is_rtl(); let chevrons = self.chevrons(&cx.words::()); let placed = Self::laid_out(cx.style, cx.content_rect, rtl, &chevrons); @@ -380,7 +390,7 @@ impl Component for NumberField<'_, V> { let reason = if *key == PRESETS { "Alt+Down opens the list" } else { slider_reason }; let popup = if *key == PRESETS { "presets" } else { "slider" }; cx.part(*key, *at) - .sense(Sense::CLICK | Sense::KEEP_FOCUS) + .sense(Sense::CLICK | Sense::DRAG | Sense::KEEP_FOCUS) .priority(HitPriority::new(HitLevel::Handle, 0)) .pointer_only(reason) .toggles(popup); @@ -398,6 +408,8 @@ impl Component for NumberField<'_, V> { proposed == host || (proposed.named() == host.named() && at_precision(proposed) == at_precision(host)) } + /// A drag on the body of a field not in edit, or on its side label with `scrub_by_label`, moves a step a point; + /// a drag on the popup slider's chevron moves the value as far as the same drag on the slider. fn scrub(&self) -> Option> { let rule = self.rule(); let drag = ValueDrag::relative(rule.step, rule.bounds()).warp(true).hide_cursor(true).coarse(LARGE_STEPS).fine(1.0 / LARGE_STEPS); @@ -405,9 +417,18 @@ impl Component for NumberField<'_, V> { // here: an Alt drag moves by a share of it. let decimals = self.decimals(); let scale = self.scale; - self.scrub.then(|| { + let mut scrub = Scrub::new(drag, move |value: &V| value.number().unwrap_or(0.0) * scale, move |number| V::of_number(round_to(number, decimals) / scale)) - }) + .on_field(); + if self.scrub { + scrub = scrub.by_label(); + } + if let Some(range) = self.popup_slider.as_ref().filter(|_| self.track > 0.0) { + let shown = range.start() * scale..=range.end() * scale; + let rate = (shown.end() - shown.start()) / f64::from(self.track); + scrub = scrub.part(SLIDER, ValueDrag::relative(rate, shown)); + } + Some(scrub) } /// Arrows, Page keys, the wheel and AccessKit Increment and Decrement step the value, AccessKit sets it, and the @@ -417,6 +438,10 @@ impl Component for NumberField<'_, V> { /// fine step. A step starts from the applied value, or from 0 kept in the /// range while the field is blank. fn update(&mut self, cx: &mut Cx<'_, Self>) { + // A drag from the slider's chevron is one gesture with the slider it opened: its release closes the slider. + if cx.part_if_declared(SLIDER).is_some_and(|part| matches!(part.press.phase, PressPhase::Release { click: false, .. })) { + cx.popup("slider").close(cx); + } let rule = self.rule(); let fine_shows = self.decimals() >= decimals_for_step(rule.step / LARGE_STEPS); while let Some((mv, mods)) = cx.intents().take_move() { diff --git a/crates/ui-widgets/tests/it/label/kit.rs b/crates/ui-widgets/tests/it/label/kit.rs index 149789e3ce..804a85f93f 100644 --- a/crates/ui-widgets/tests/it/label/kit.rs +++ b/crates/ui-widgets/tests/it/label/kit.rs @@ -86,7 +86,7 @@ impl Component for Dial<'_> { fn scrub(&self) -> Option> { let drag = ValueDrag::relative(RATE, RANGE); let drag = if self.warping { drag.warp(true).hide_cursor(true) } else { drag }; - Some(Scrub::new(drag, |value| *value, |value| value)) + Some(Scrub::new(drag, |value| *value, |value| value).by_label()) } fn update(&mut self, cx: &mut Cx<'_, Self>) { diff --git a/crates/ui-widgets/tests/it/text/number.rs b/crates/ui-widgets/tests/it/text/number.rs index d2f0874162..fe58859296 100644 --- a/crates/ui-widgets/tests/it/text/number.rs +++ b/crates/ui-widgets/tests/it/text/number.rs @@ -4,10 +4,10 @@ use craft_host::{AppInfo, Host}; use craft_ui::contract::{Bind, Entry, Props as _, Show as _}; use craft_ui::runtime::env::UnitKind; use craft_ui::testing::input::key_press; -use craft_ui::testing::pointer::click; +use craft_ui::testing::pointer::{click, drag}; use craft_ui::testing::{Frames, trial}; use craft_ui::text::{NumberField, NumberPick}; -use egui::{Event, Key, Modifiers, Pos2, Rect, Ui}; +use egui::{Event, Key, Modifiers, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::ops::RangeInclusive; use std::sync::Arc; @@ -59,6 +59,13 @@ impl Rig { self.idle(2); } + fn drag(&mut self, by: Vec2) { + let Rig { frames, value, rect, picked, range, presets, whole } = self; + let from = rect.get().center(); + drag(frames, from, by, &mut |ui| show(ui, value, rect, picked, range, presets, *whole)); + self.idle(2); + } + fn key(&mut self, key: Key, modifiers: Modifiers) { self.frame(vec![key_press(key, modifiers)]); self.idle(3); @@ -112,6 +119,18 @@ fn arrows_step_to_the_next_multiple_and_stay_in_range() { assert_eq!(rig.value(), Some(0.0), "Shift moves ten steps and stops at the start of the range"); } +/// A drag on a field that is not in edit scrubs it; once a click has put it in edit, a drag is the text's. +#[trial] +fn a_drag_scrubs_a_field_not_in_edit_and_is_the_text_s_in_edit() { + let mut rig = Rig::new(START, None); + rig.drag(Vec2::new(30.0, 0.0)); + let scrubbed = rig.value().unwrap_or_default(); + assert!(scrubbed > START, "a drag to the right on the field raised the value"); + rig.focus(); + rig.drag(Vec2::new(30.0, 0.0)); + assert_eq!(rig.value(), Some(scrubbed), "a drag in edit leaves the value"); +} + /// Alt steps a tenth where the field's decimals show it, and a whole step on a whole-number field. #[trial] fn a_fine_step_moves_only_as_far_as_the_decimals_show() { @@ -168,3 +187,24 @@ fn a_localised_decimal_types_in() { let host = Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).i18n(Arc::new(i18n)).build()); assert_eq!(typed(Some(host), None, "12,5"), Some(12.5)); } + +/// A field over 0 to 100 with a popup slider. +fn with_slider(ui: &mut Ui, data: &mut craft_ui::testing::StoryData) -> craft_ui::testing::StoryOutput { + NumberField::new("Opacity", Bind::bound(data.value("value", Some(50.0)))).range(0.0..=100.0).popup_slider(0.0..=100.0).show(ui).into() +} + +/// Pressing the popup slider's chevron and dragging moves the value at once, and the release closes the slider. +#[trial] +fn a_drag_from_the_slider_chevron_moves_the_value_and_its_release_closes_the_slider() { + use craft_ui::contract::Role; + let mut fixture = craft_ui::testing::Fixture::story(&craft_ui::testing::Story::new("number_slider", with_slider)); + fixture.settle(); + let chevron = fixture.by_role(Role::BUTTON).first().expect("the chevron").center(); + fixture.drag_hold_at(chevron, Vec2::new(30.0, 0.0)); + fixture.settle(); + assert!(!fixture.by_role(Role::SLIDER).is_empty(), "the press opened the slider"); + assert!(fixture.data().value("value", Some(50.0)).is_some_and(|value| value > 50.0), "the drag moved the value at once"); + fixture.release_at(chevron + Vec2::new(30.0, 0.0)); + fixture.settle(); + assert!(fixture.by_role(Role::SLIDER).is_empty(), "the release closed the slider"); +}