widgets-w3: net change of 2 commits

- widgets-w3: written from its sheet
- widgets-w3: repair 1
This commit is contained in:
bflatastic
2026-11-21 21:26:48 +07:00
parent 3873678892
commit 01a8bbd299
15 changed files with 277 additions and 30 deletions
@@ -219,7 +219,7 @@ impl<C: Component> Cx<'_, C> {
/// Whether the control's link label was clicked in this pass.
pub fn link_activated(&self) -> bool {
todo!("wg.W08")
crate::runtime::access::scope::field_label(&self.core.ctx).is_some_and(|label| label.link)
}
/// Asks the platform to open `url`, in a new tab where the platform has tabs and `new_tab` is set.
@@ -241,8 +241,8 @@ impl<C: Component> Cx<'_, C> {
/// activation came from (`part_activated` gives it). Returns whether the command was queued.
pub fn fire(&mut self, command: impl Into<CommandRef>, source: FireSource) -> bool {
let Some(resolved) = commands::resolve_scoped(&self.core.ctx, self.core.env.command_chain(), &command.into()) else { return false };
// P3(widgets-w3): ap.AP9
commands::fire_resolved(&self.core.ctx, &resolved, source, craft_keymap::Mods::NONE)
let mods = self.core.activation.map_or(craft_keymap::Mods::NONE, |activation| activation.mods);
commands::fire_resolved(&self.core.ctx, &resolved, source, mods)
}
/// Where an activation of `part` came from this pass: `Key` for a keyboard activation while `part` is the
+14 -3
View File
@@ -5,7 +5,7 @@ use super::step::LabelIn;
use crate::contract::InBar;
use crate::contract::{Component, Props};
use crate::contract::{Cx, MeasureCx, PaintUi, PartsCx, Styled as _};
use crate::primitives::{IconSpec, TextRun, Wrap};
use crate::primitives::{IconSpec, Span, TextRun, Wrap};
use crate::runtime::access::{Access, Name};
use crate::runtime::env::{Env, Label};
use crate::runtime::words::CommonWords;
@@ -87,6 +87,9 @@ pub(super) struct LabelLeaf {
/// and wraps in its room instead of eliding.
#[style_key]
pub(super) after: bool,
/// The label is a link (`LabelPress::Link`): its name reads in the link look and is underlined.
#[style_key]
pub(super) link: bool,
/// The control the label names takes the label into its own hit target: the label senses nothing itself.
pub(super) claimed: bool,
/// The size of the content the label step shows after the text, inside the label: 0 without one.
@@ -129,6 +132,7 @@ impl LabelLeaf {
baseline: Cell::new(0.0),
first_line: Cell::new(0.0),
after: false,
link: false,
claimed: false,
trailing: Vec2::ZERO,
named: true,
@@ -165,7 +169,9 @@ impl Component for LabelLeaf {
Stateful::new(muted).off(States::new(muted, muted, muted, off))
},
// A caption reads as secondary; a check box's or a radio's text after it is the control's own.
name: {
name: if key.link {
cx.link_look(true)
} else {
let text = &cx.tokens.color.text;
let (role, ink) = if key.after { (TypeRole::Body, text.normal) } else { (TypeRole::Label, text.muted) };
let (ink, off) = (cx.color(ink), cx.color(text.disabled));
@@ -348,7 +354,12 @@ impl Component for LabelLeaf {
let name_ink = cx.resolve(&cx.style.name.color);
let colon = self.colon.as_deref().map(|colon| TextRun::new(colon).role(cx.style.name.role).color(name_ink));
let colon_width = colon.as_ref().map_or(0.0, |run| draw.layout(run, f32::INFINITY).size().x);
let run = TextRun::new(cx.core.resolved.label).role(cx.style.name.role).color(name_ink);
let named = if self.link {
TextRun::spans(vec![Span::new(cx.core.resolved.label).underline()])
} else {
TextRun::new(cx.core.resolved.label)
};
let run = named.role(cx.style.name.role).color(name_ink);
let run = if wrapped { run.wrap(Wrap::Wrap) } else { run.elide() };
let name = draw.layout(&run, (rest.rect().width() - colon_width).max(0.0)).size();
let (name_rect, after) = rest.take_start(name.x);
@@ -170,6 +170,8 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<
}
leaf.colon = colon(env, input).filter(|_| leaf.named);
leaf.after = input.side.layout == FieldLayout::After;
let linked = input.side.press == super::props::LabelPress::Link;
leaf.link = linked;
leaf.claimed = input.claims;
leaf.trailing = input.trailing;
if let Some(tooltip) = input.side.tooltip.clone() {
@@ -217,8 +219,11 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option<
if let Some(trailing) = trailing {
(trailing.show)(ui, placed.trailing);
}
let label =
field_label(env, input, label_id_for_scope, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated);
let label = field_label(env, input, label_id_for_scope, placed.label)
.with_press(shown.press)
.with_hover(shown.hovered)
.activated(shown.activated && !linked)
.linked(shown.activated && linked);
scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(label));
scope::place_controls(&ctx, input.scope, placed.control.top());
if input.claims {
+19 -5
View File
@@ -2,22 +2,34 @@
use crate::contract::{Component, Cx};
use crate::runtime::access::scope;
use crate::runtime::env::ScrubDrags;
use crate::runtime::memory::sub;
use crate::runtime::windows::WindowHost;
use craft_behavior::{CancelReason, Cursor, CursorPriority, DragWarp, GesturePhase, PaintedCursor, ValueDrag};
use egui::{Pos2, Vec2};
/// Which of a scrub's label and body sources the root's `ScrubDrags` leaves on, as `(label, field)`. A part's source
/// is the component's own and is never gated.
fn scrub_sources<C: Component>(cx: &Cx<'_, C>) -> (bool, bool) {
match cx.core.env.get::<ScrubDrags>() {
ScrubDrags::FieldAndLabel => (true, true),
ScrubDrags::LabelOnly => (true, false),
_ => (false, false),
}
}
/// 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<C: Component>(comp: &C, cx: &Cx<'_, C>) -> Option<(craft_behavior::PressState, ValueDrag)> {
let scrub = comp.scrub()?;
let (label_on, field_on) = scrub_sources(cx);
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(|| side_label(cx)).flatten().map(|(press, _)| press).filter(pressed);
let field = || (scrub.on_field && !cx.core.text_takes_pointer).then_some(cx.core.press).filter(pressed);
let label = || (scrub.by_label && label_on).then(|| side_label(cx)).flatten().map(|(press, _)| press).filter(pressed);
let field = || (scrub.on_field && field_on && !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())))
}
@@ -76,13 +88,15 @@ pub(crate) fn scrub_by_label<C: Component>(comp: &C, cx: &mut Cx<'_, C>) {
}
return;
}
if scrub.by_label && scope::field_label(&cx.core.ctx).is_some() {
let (label_on, field_on) = scrub_sources(cx);
let by_label = scrub.by_label && label_on;
if by_label && scope::field_label(&cx.core.ctx).is_some() {
scope::register_scrub(&cx.core.ctx);
}
let label = scrub.by_label.then(|| side_label(cx)).flatten();
let label = by_label.then(|| side_label(cx)).flatten();
// 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();
let field_hovered = scrub.on_field && field_on && !cx.core.text_takes_pointer && cx.core.response.hovered();
if part_hovered || field_hovered || label.is_some_and(|(_, hovered)| hovered) {
crate::runtime::cursor::request(&cx.core.ctx, Cursor::System(craft_behavior::CursorIcon::ResizeHorizontal), CursorPriority::Part);
}
@@ -45,6 +45,8 @@ pub struct FieldLabel {
pub detail: Option<String>,
/// The label was clicked or activated this pass: focus goes to its control.
pub activated: bool,
/// The label is a link and was clicked this pass: the control's host is told (`Cx::link_activated`), focus stays.
pub link: bool,
/// The container shows its control's validity message as its status line (`FooterRegion::status`).
pub status: bool,
}
@@ -61,6 +63,7 @@ impl FieldLabel {
role: FieldLabelRole::Names,
detail: None,
activated: false,
link: false,
status: false,
}
}
@@ -93,6 +96,13 @@ impl FieldLabel {
self
}
/// Whether the label is a link that was clicked this pass.
#[must_use]
pub fn linked(mut self, link: bool) -> Self {
self.link = link;
self
}
/// The label's press this pass.
#[must_use]
pub fn with_press(mut self, press: PressState) -> Self {
+6
View File
@@ -221,6 +221,10 @@ pub struct Inherited {
pub(crate) today: Option<CalendarDate>,
/// `RootEnv::tab_toggles_chrome`.
pub(crate) tab_toggles_chrome: bool,
/// `RootEnv::cursor_follows_zoom`: painted cursor images follow the interface zoom.
pub(crate) cursor_follows_zoom: bool,
/// `RootEnv::tooltips`: tooltips show.
pub(crate) tooltips: bool,
/// `RootEnv::canvas_pattern`: the canvas surround shows the theme's pattern.
#[doc(hidden)]
pub canvas_pattern: bool,
@@ -482,6 +486,8 @@ impl Env {
dates: host_dates(ctx, host.as_ref()),
today: root.today,
tab_toggles_chrome: root.tab_toggles_chrome,
cursor_follows_zoom: root.cursor_follows_zoom,
tooltips: root.tooltips,
canvas_pattern: root.canvas_pattern,
host,
values: root.values.clone(),
+8 -6
View File
@@ -184,21 +184,23 @@ impl<'a> StyleCx<'a> {
/// Runs `f` with the style context of the root scope (`Env::of_root(ctx)`), for code with no `Ui` that reads a
/// component's style, such as the dock's sizes outside a style pass.
pub fn with_root<R>(ctx: &Context, f: impl FnOnce(&StyleCx<'_>) -> R) -> R {
let env = crate::runtime::env::Env::of_root(ctx);
f(&StyleCx::of_env(ctx, &env))
Self::with_root_scoped(ctx, &crate::runtime::env::ThemeScope::new(), f)
}
/// Runs `f` with the root style at the tokens `scope` resolves, for code that has a context and no `Ui`.
pub fn with_root_scoped<R>(ctx: &Context, scope: &crate::runtime::env::ThemeScope, f: impl FnOnce(&StyleCx<'_>) -> R) -> R {
let _ = (ctx, scope, f);
todo!("ch.K19")
let env = crate::runtime::env::Env::of_root(ctx).derive_local(|scoped| scope.apply(ctx, scoped));
f(&StyleCx::of_env(ctx, &env))
}
/// The one link look: body role, underlined, `accent.solid` (`accent.text` at high contrast), `text.disabled` when
/// not `enabled`.
pub fn link_look(&self, enabled: bool) -> super::look::TextLook {
let _ = enabled;
todo!("wg.W07")
let colors = &self.tokens.color;
let accent = if self.contrast() == Contrast::High { colors.accent.text } else { colors.accent.solid };
let (ink, off) = (self.color(accent), self.color(colors.text.disabled));
let rest = if enabled { ink } else { off };
super::look::TextLook::new(craft_theme::TypeRole::Body, Stateful::new(rest).off(States::new(rest, rest, rest, off)))
}
/// The same context with another variant.
+25 -6
View File
@@ -92,6 +92,8 @@ pub struct SliderField<'a> {
/// row, the Color panel's channels) instead of the number cell, and the slider takes the room it leaves.
#[prop]
field_sizing: Option<Sizing>,
/// The marks under the slider's track: one list, the last of `marks` and `marks_labelled` wins.
marks: Option<FieldMarks>,
/// The number field's width from this pass's measure (its `Proposal::Ideal` call, which runs before `paint`).
field_width: f32,
/// The field's range alert of this pass, which `finish` reports.
@@ -146,6 +148,7 @@ impl<'a> SliderField<'a> {
track_face: None,
thumb: SliderThumb::Round,
field_sizing: None,
marks: None,
field_width: 0.0,
out_of_range: None,
}
@@ -154,16 +157,16 @@ impl<'a> SliderField<'a> {
/// Values the field's slider snaps to, drawn as marks under the track: [`Slider::marks`].
#[must_use]
pub fn marks(self, marks: &[f64]) -> Self {
let _ = marks;
todo!("wg.W31")
pub fn marks(mut self, marks: &[f64]) -> Self {
self.marks = Some(FieldMarks::Plain(marks.to_vec()));
self
}
/// [`marks`](Self::marks) at the values, each with a caption centred under its mark: [`Slider::marks_labelled`].
#[must_use]
pub fn marks_labelled<L: Into<Label>>(self, marks: impl IntoIterator<Item = (f64, L)>) -> Self {
let _ = marks;
todo!("wg.W31")
pub fn marks_labelled<L: Into<Label>>(mut self, marks: impl IntoIterator<Item = (f64, L)>) -> Self {
self.marks = Some(FieldMarks::Labelled(marks.into_iter().map(|(at, caption)| (at, caption.into())).collect()));
self
}
/// What the children are built from, apart from the binding and the track face.
@@ -179,10 +182,20 @@ impl<'a> SliderField<'a> {
thumb: self.thumb,
reset: self.value.reset_value().copied(),
field_sizing: self.field_sizing,
marks: self.marks.clone(),
}
}
}
/// The marks of a slider field's slider.
#[derive(Clone)]
enum FieldMarks {
/// Marks the thumb snaps to.
Plain(Vec<f64>),
/// Marks with a caption under each.
Labelled(Vec<(f64, Label)>),
}
/// What a `SliderField` builds its two children from.
struct Look {
range: RangeInclusive<f64>,
@@ -196,6 +209,7 @@ struct Look {
/// The reset value of the composite's own binding, which both children restore on a double click.
reset: Option<f64>,
field_sizing: Option<Sizing>,
marks: Option<FieldMarks>,
}
/// The composite's check on a number, as a child with the same value type reads it.
@@ -222,6 +236,11 @@ impl Look {
bind = bind.check(check);
}
let slider = Slider::new(bind, self.range.clone()).scale(self.scale).fill(self.fill).thumb(self.thumb).label(name.clone());
let slider = match &self.marks {
Some(FieldMarks::Plain(marks)) => slider.marks(marks),
Some(FieldMarks::Labelled(marks)) => slider.marks_labelled(marks.iter().cloned()),
None => slider,
};
let slider = match face {
Some(face) => slider.track_face(face),
None => slider,
@@ -17,6 +17,15 @@ fn slider_field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
SliderField::new("Opacity", Bind::bound(data.value("opacity", 40.0)), PERCENT).unit_kind(UnitKind::Percent).show(ui).into()
}
/// Words at the two ends of the track, as a softness or a contrast control names its extremes.
#[story(SliderField<'static>, covers = [], drive = Drive::Never)]
fn slider_field_end_words(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
SliderField::new("Softness", Bind::bound(data.value("softness", 50.0)), PERCENT)
.marks_labelled([(0.0, "Soft"), (100.0, "Hard")])
.show(ui)
.into()
}
#[story(SliderField<'static>, covers = [], drive = Drive::Never)]
fn slider_field_log(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
SliderField::new("Brush size", Bind::bound(data.value("size", 8.0)), 1.0..=200.0).scale(SliderScale::Log).step(1.0).show(ui).into()
+9
View File
@@ -40,6 +40,15 @@ fn field_long_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.into()
}
/// A number field whose side label is a link: a click reports to the host and leaves focus alone, a drag scrubs.
#[story(Field, covers = [], drive = Drive::Never)]
fn field_link_label(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
Field::new("Opacity")
.side(SideLabel::new().link().scrub(true))
.show(ui, |ui, _| NumberField::new("Opacity", Bind::bound(data.value("link", Some(100.0)))).scrub_by_label().show(ui))
.into()
}
/// A glyph label: the icon shows, the text only names the control.
#[story(Field, covers = [], drive = Drive::Never)]
fn field_icon_label(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
@@ -12,7 +12,7 @@ use crate::runtime::env::Label;
use crate::runtime::focus::{ActivateKeys, KeyUse};
use crate::style::{ComponentStyle, Flags, FocusLook, Stateful, States, StyleColor, StyleCx, SurfaceKind, SurfaceLook, UiTokens};
use craft_behavior::{Anchor9, Metrics, NavShape, PartKey, PartRef, Roving, Sense};
use egui::{Pos2, Rect, Vec2, vec2};
use egui::{CornerRadius, Pos2, Rect, Vec2, vec2};
#[cfg(feature = "testing")]
mod stories;
@@ -22,6 +22,9 @@ const CELL: PartKey = PartKey::new("cell");
/// Points on each side of the grid.
const GRID: usize = 3;
/// The eight outer points in the order the `Squares` line joins them round the box; the centre point is left out.
const RING: [usize; 8] = [0, 1, 2, 5, 8, 7, 6, 3];
/// The side of the dot every point shows; the large picker draws the picked one twice as wide.
const DOT: f32 = 3.5;
@@ -58,8 +61,12 @@ pub struct ReferencePointStyle {
ink: Stateful<StyleColor>,
/// The side of the square one growth arrow fits in.
arrow: f32,
/// The unpicked dots and the growth arrows.
/// The unpicked dots and squares, the line joining the squares and the growth arrows.
arrow_ink: Stateful<StyleColor>,
/// The side of a square of the `Squares` look.
square: f32,
/// The width of the `Squares` line and of the unpicked squares' outline.
line: StrokeWidth,
}
/// How a [`ReferencePoint`] draws its nine points.
@@ -98,7 +105,6 @@ pub struct ReferencePoint<'a> {
/// How the nine points are drawn: dots, or squares joined by a line round the box.
#[style_key]
#[prop]
#[allow(dead_code)] // P3(widgets-w3): wg.W32
look: ReferencePointLook,
}
@@ -180,6 +186,8 @@ impl Component for ReferencePoint<'_> {
ink: look(cx.color(colors.accent.text)),
arrow: cx.tokens.size.icon.sm,
arrow_ink: look(cx.color(colors.text.muted)),
square: cx.tokens.size.handle.sm,
line: StrokeWidth::Thin,
}
}
@@ -228,8 +236,28 @@ impl Component for ReferencePoint<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let current = Self::position_of(cx.value());
debug_assert!(!(self.compact && self.growth.is_some()), "the compact picker shows no growth arrows");
let squares = self.look == ReferencePointLook::Squares;
debug_assert!(!(self.growth.is_some() && (self.compact || squares)), "the compact picker and the squares look show no growth arrows");
let draw = ui.draw();
if squares {
let centres: Vec<Pos2> = (0..Anchor9::ALL.len()).map(|at| Self::cell_rect(cx.rect, at).center()).collect();
let (half, outline) = (cx.style.square / 2.0, cx.resolve(&cx.style.arrow_ink));
// Each side of the ring runs between the squares it joins, so the line never crosses a square.
for (from, to) in RING.iter().zip(RING.iter().cycle().skip(1)) {
let (from, to) = (centres[*from], centres[*to]);
let along = (to - from).normalized() * half;
draw.stroke(&PaintShape::Path(vec![from + along, to - along]), cx.style.line, outline);
}
for (at, centre) in centres.iter().enumerate() {
let square = PaintShape::Rect(Rect::from_center_size(*centre, Vec2::splat(cx.style.square)), CornerRadius::ZERO);
if current == Some(at) {
draw.fill(&square, cx.resolve(&cx.style.ink));
} else {
draw.stroke(&square, cx.style.line, outline);
}
}
return;
}
for (at, point) in Anchor9::ALL.iter().enumerate() {
let cell = Self::cell_rect(cx.rect, at);
let (side, ink) = if current == Some(at) { (cx.style.picked_dot, &cx.style.ink) } else { (cx.style.dot, &cx.style.arrow_ink) };
@@ -1,6 +1,6 @@
//! Stories of `ReferencePoint`.
use super::ReferencePoint;
use super::{ReferencePoint, ReferencePointLook};
use crate::contract::{Bind, Show as _, Validity};
use crate::runtime::env::Message;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
@@ -38,6 +38,24 @@ fn reference_point_growth(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ReferencePoint::new("Reference point", Bind::bound(data.value("grown", Anchor9::TopLeft))).growth((200.0, -100.0)).show(ui).into()
}
/// The squares look: eight squares joined by a line round the box, the centre one alone, the pick filled.
#[story(ReferencePoint<'static>, covers = [], drive = Drive::Never)]
fn reference_point_squares(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ReferencePoint::new("Reference point", Bind::bound(data.value("squares", Anchor9::TopRight)))
.look(ReferencePointLook::Squares)
.show(ui)
.into()
}
/// The squares look with a mixed value: no square is filled.
#[story(ReferencePoint<'static>, covers = [], drive = Drive::Never)]
fn reference_point_squares_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ReferencePoint::new("Reference point", Bind::bound_mixed(data.value("squares_mixed", Mixed::Mixed)))
.look(ReferencePointLook::Squares)
.show(ui)
.into()
}
/// The options bar's size: the grid is an icon square and every point is a dot.
#[story(ReferencePoint<'static>, covers = [], drive = Drive::Never)]
fn reference_point_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+64
View File
@@ -0,0 +1,64 @@
//! A link side label reports its click to the control's host and leaves focus alone; a drag on it still scrubs, and a
//! plain label beside it still focuses its control.
use super::kit::{Dial, Field, Seen};
use super::{ROW_A, START};
use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, SideLabel};
use craft_ui::testing::{Fixture, trial};
use egui::{Pos2, Rect, Ui, Vec2, pos2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const ROW_B: Rect = Rect { min: pos2(10.0, 60.0), max: pos2(310.0, 90.0) };
const DRAG: f32 = 40.0;
/// One row of the trial: its value, what its dial saw and whether its label ever reported a link click.
#[derive(Clone)]
struct Row {
value: Rc<Cell<f64>>,
seen: Rc<RefCell<Seen>>,
linked: Rc<Cell<bool>>,
}
impl Row {
fn new() -> Self {
Row { value: Rc::new(Cell::new(START)), seen: Rc::default(), linked: Rc::default() }
}
fn show(&self, ui: &mut Ui, salt: &'static str, side: SideLabel, at: Rect) {
let mut value = self.value.get();
Field::new("Opacity", side).id_salt(salt).show_at(ui, at, |ui, _| {
Dial::new(&mut value, &self.seen).show(ui);
});
self.value.set(value);
let link = self.seen.borrow().label.as_ref().is_some_and(|label| label.link);
self.linked.set(self.linked.get() || link);
}
fn label_at(&self) -> Pos2 {
let seen = self.seen.borrow();
seen.label.as_ref().map(|label| label.rect.center()).unwrap_or_else(|| panic!("the dial ran inside a label scope"))
}
}
#[trial]
fn a_link_label_reports_its_click_to_the_host_and_still_scrubs() {
let (link, plain) = (Row::new(), Row::new());
let shown = (link.clone(), plain.clone());
let mut fixture = Fixture::new(move |ui| {
shown.0.show(ui, "link", SideLabel::new().link().scrub(true), ROW_A);
shown.1.show(ui, "plain", SideLabel::new().scrub(true), ROW_B);
});
fixture.settle();
fixture.click_at(link.label_at());
assert!(link.linked.get(), "a click on a link label reports to the host");
assert_ne!(fixture.focused(), link.seen.borrow().id, "a link click leaves focus alone");
fixture.click_at(plain.label_at());
assert!(!plain.linked.get(), "a plain label reports no link");
assert_eq!(fixture.focused(), plain.seen.borrow().id, "a click on a plain label focuses its control");
fixture.drag_at(link.label_at(), Vec2::new(DRAG, 0.0));
assert!(link.value.get() > START, "a drag on a link label scrubs: {}", link.value.get());
}
+2
View File
@@ -7,9 +7,11 @@ pub mod group;
mod hit;
mod inside;
pub mod kit;
mod link;
mod reach;
mod reset;
mod scheme;
mod scrub_drags;
mod short;
mod tooltip;
@@ -0,0 +1,50 @@
//! The root's `ScrubDrags` decides which drags scrub a number field: its body, its side label, both or neither.
use super::START;
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _, SideLabel};
use craft_ui::form::Field;
use craft_ui::runtime::env::ScrubDrags;
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::NumberField;
use egui::{Pos2, Vec2};
use std::cell::Cell;
use std::rc::Rc;
const DRAG: f32 = 40.0;
/// Whether a drag from `from` changed the value.
fn dragged(fixture: &mut Fixture, value: &Cell<Option<f64>>, from: Pos2) -> bool {
let before = value.get();
fixture.drag_at(from, Vec2::new(DRAG, 0.0));
value.get() != before
}
/// Whether a drag on the label and one on the body of a number field move its value under `drags`; the default root
/// when `None`.
fn scrubs(drags: Option<ScrubDrags>) -> (bool, bool) {
let value = Rc::new(Cell::new(Some(START)));
let shown = Rc::clone(&value);
let mut fixture = Fixture::new(move |ui| {
let mut number = shown.get();
Field::new("Opacity").side(SideLabel::new().scrub(true)).show(ui, |ui, _| {
NumberField::new("Opacity", Bind::bound(&mut number)).scrub_by_label().show(ui);
});
shown.set(number);
});
if let Some(drags) = drags {
fixture.root_value(drags);
}
fixture.settle();
let label = fixture.by_role(Role::LABEL).first().map(|target| target.center()).unwrap_or_else(|| panic!("the side label is shown"));
let body = fixture.by_label("Opacity").map(|target| target.center()).unwrap_or_else(|| panic!("the number field is shown"));
let by_label = dragged(&mut fixture, &value, label);
let by_body = dragged(&mut fixture, &value, body);
(by_label, by_body)
}
#[trial]
fn scrub_drags_label_only_leaves_the_body_to_text_and_off_scrubs_nothing() {
assert_eq!(scrubs(None), (true, true), "by default both the label and the body scrub");
assert_eq!(scrubs(Some(ScrubDrags::LabelOnly)), (true, false), "label only: the label scrubs, the body's drag is the text's");
assert_eq!(scrubs(Some(ScrubDrags::Off)), (false, false), "off: neither scrubs");
}