From d6b9cb66ae6b49d5a1838e56f1025bbbc76ffc54 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 12 Nov 2026 06:36:18 +0000 Subject: [PATCH] StrokeEditor: Illustrator's six dash and gap fields, no tall sample, and the panel as the default story --- crates/draw/src/ui/stroke/editor.rs | 160 ++++++++------------------ crates/draw/src/ui/stroke/mod.rs | 14 +-- crates/draw/src/ui/stroke/stories.rs | 14 +-- crates/draw/src/ui/stroke/words.rs | 14 +-- crates/draw/tests/it/main.rs | 1 + crates/draw/tests/it/stroke_editor.rs | 46 ++++++++ 6 files changed, 112 insertions(+), 137 deletions(-) create mode 100644 crates/draw/tests/it/stroke_editor.rs diff --git a/crates/draw/src/ui/stroke/editor.rs b/crates/draw/src/ui/stroke/editor.rs index 765dc3ace..e76398dae 100644 --- a/crates/draw/src/ui/stroke/editor.rs +++ b/crates/draw/src/ui/stroke/editor.rs @@ -3,24 +3,22 @@ use std::borrow::Cow; use std::ops::RangeInclusive; -use craft_behavior::{Axis, CancelReason, DisplayOrder, EditEvent, EditEvents, IconId, Input, ItemSource, Metrics, Mixed, Selection, Sense, Value}; +use craft_behavior::{CancelReason, ColumnWidth, DisplayOrder, EditEvent, EditEvents, IconId, ItemSource, Mixed, Selection, Value}; use craft_theme::variant::Tone; -use craft_ui::buttons::Button; use craft_ui::choice::{Checkbox, Segmented}; use craft_ui::contract::{ - Bind, Common, Component, Cx, Entry, MeasureCx, NoValue, Outcome, PaintUi, Props as _, Remember as _, Role, SelectMode, Show as _, - ShowCollection as _, ShowContainer as _, clicked, + Bind, Entry, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, }; use craft_ui::display::{Divider, Shade, Text}; use craft_ui::form::{Field, FieldGroup}; -use craft_ui::layout_components::{Row, Stack}; +use craft_ui::layout_components::{Grid, Stack}; use craft_ui::list::{List, ListRow, ThumbAspect, ThumbSize}; use craft_ui::pickers::Select; use craft_ui::primitives::{ContentPainterCx, IconSpec}; use craft_ui::runtime::env::{Env, Label, UnitKind}; -use craft_ui::style::{ComponentStyle, StyleCx, SurfaceLook, TypeRole}; +use craft_ui::style::TypeRole; use craft_ui::text::NumberField; -use egui::{Rect, Response, Ui, Vec2}; +use egui::{Rect, Response, Ui}; use std::sync::Arc; use super::{ @@ -30,8 +28,10 @@ use super::{ /// The width of a preset row's line sample as a multiple of its height. const PRESET_ASPECT: (u16, u16) = (8, 1); -/// The tall sample's width as a multiple of its height, for the room it measures. -const SAMPLE_ASPECT: f32 = 6.0; +/// The dash and gap fields in a row (Illustrator's Stroke panel). +const DASH_FIELDS: usize = 6; +/// The columns of a row of dash and gap fields. +const DASH_COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content; DASH_FIELDS]; /// The preset rows, in list order. const PRESETS: [LineStyle; 3] = [LineStyle::Solid, LineStyle::Dashed, LineStyle::Dotted]; @@ -75,11 +75,12 @@ impl Outcome for StrokeEditorOutput { /// corners); Opacity ([`StrokeSections::OPACITY`], 0–100 %, stored 0..=1). Choices are selects, or segmented icon /// buttons with [`StrokeSections::ICONS`]. Under the rows of an open path: "Open paths use centered strokes". /// - Dashes ([`StrokeSections::DASHES`]): a "Dashed line" check (setting it applies the Dashed preset, clearing it -/// Solid); while dashed, a hint by [`StrokeStyle::dash_unit`], then one row per pair of Dash and Gap fields (0–10000, -/// `×`, or `pt` for document units); "Add pair" (enabled under 32 entries: appends `[4, 2]`, or `2` to complete an -/// odd pattern) and "Remove pair" (enabled over 2 entries: drops the last two); "Dash offset" (±1,000,000). -/// - Sample ([`StrokeSections::SAMPLE`]): a tall [`StrokePreview`], a rectangle when closed, a line otherwise. While -/// the style fails [`StrokeStyle::validate`], the invalid word shows under it and nothing is reported. +/// Solid); while dashed, a hint by [`StrokeStyle::dash_unit`], then Illustrator's row of six fields, dash, gap, +/// dash, gap, dash, gap (0–10000, `×`, or `pt` for document units), each with its word under it. A field shows its +/// entry of [`StrokeStyle::dashes`] or is blank; typing in the blank after the pattern adds an entry, the blanks +/// after it are off, and clearing a field after the first ends the pattern there. A pattern longer than six shows in +/// further rows of six. Then "Dash offset" (±1,000,000). +/// - While the style fails [`StrokeStyle::validate`], the invalid word shows at the end and nothing is reported. /// - [`mixed`](Self::mixed): a mixed field shows the mixed state and lights no button or preset; the first edit sets it /// for all. /// @@ -118,7 +119,7 @@ impl<'a> StrokeEditor<'a> { self } - /// Whether the stroked path is closed: alignment applies, caps need dashes, and the tall sample is a rectangle. + /// Whether the stroked path is closed: alignment applies and caps need dashes. /// True by default. pub fn closed(mut self, closed: bool) -> Self { self.closed = closed; @@ -275,9 +276,6 @@ impl Body<'_> { Divider::horizontal().show(ui); self.dashes(ui, found); } - if self.sections.contains(StrokeSections::SAMPLE) { - Sample { common: Common::new(), value: self.style, closed: self.closed }.label(self.words.sample.clone()).show(ui); - } if found.invalid.is_some() || self.style.validate().is_err() { Text::new(self.words.invalid.clone()).role(TypeRole::Caption).tone(Tone::Bad).show(ui); } @@ -421,44 +419,28 @@ impl Body<'_> { DashUnit::Document => &words.dash_document, }; Text::new(hint.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); - for (pair, lengths) in style.dashes.chunks(2).enumerate() { - Row::new().id_salt(("pair", pair)).show(ui, |ui, _| { - for (k, &length) in lengths.iter().enumerate() { - let (index, name) = (pair * 2 + k, if k == 0 { &words.dash } else { &words.gap }); - Text::new(name.clone()).shade(Shade::Muted).id_salt(("name", index)).show(ui); - let bind = Bind::>::given(Some(f64::from(length))); - let out = NumberField::new(name.clone(), bind) - .id_salt(("dash", index)) - .range(wide(StrokeStyle::DASH_RANGE)) - .unit_kind(self.dash_unit()) - .show(ui); - let with = |v: Option| { - let mut next = style.clone(); - next.dashes[index] = v.map_or(length, |v| v as f32); - next - }; - found.push(StrokeField::Dash(index), out.edit.events.map(with)); + let count = style.dashes.len().max(1).div_ceil(DASH_FIELDS) * DASH_FIELDS; + for (line, first) in (0..count).step_by(DASH_FIELDS).enumerate() { + Grid::new(DASH_COLUMNS).id_salt(("dashes", line)).show(ui, |ui, _| { + for index in first..first + DASH_FIELDS { + let (caption, name) = if index % 2 == 0 { (&words.dash, &words.dash_number) } else { (&words.gap, &words.gap_number) }; + let name = Label::from(name.fill(&[("n", &(index / 2 + 1).to_string())])); + Stack::new().id_salt(("dash", index)).show(ui, |ui, _| { + let shown = style.dashes.get(index).map(|length| f64::from(*length)); + let out = NumberField::new(name.clone(), Bind::>::given(shown)) + .id_salt("field") + .range(wide(StrokeStyle::DASH_RANGE)) + .unit_kind(self.dash_unit()) + .enabled(index <= style.dashes.len() && index < StrokeStyle::MAX_DASHES) + .sizing(Sizing::Content) + .show(ui); + let with = |v: Option| StrokeStyle { dashes: dashes_with(&style.dashes, index, v), ..style.clone() }; + found.push(StrokeField::Dash(index), out.edit.events.map(with)); + Text::new(caption.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + }); } }); } - Row::new().id_salt("pair-buttons").show(ui, |ui, _| { - let add = Button::new(words.add_pair.clone()).id_salt("add-pair").enabled(style.dashes.len() < StrokeStyle::MAX_DASHES).show(ui); - if clicked(&add) { - let mut next = style.clone(); - if next.dashes.len() % 2 == 1 { - next.dashes.push(StrokeStyle::DASHED[1]); - } else { - next.dashes.extend(StrokeStyle::DASHED); - } - self.set(found, StrokeField::AddPair, next); - } - let remove = Button::new(words.remove_pair.clone()).id_salt("remove-pair").enabled(style.dashes.len() > 2).show(ui); - if clicked(&remove) { - let mut next = style.clone(); - next.dashes.truncate(style.dashes.len().saturating_sub(2)); - self.set(found, StrokeField::RemovePair, next); - } - }); FieldGroup::new(words.dash_offset.clone()).id_salt("offset").show(ui, |ui, _| { let range = -f64::from(StrokeStyle::DASH_OFFSET_MAX)..=f64::from(StrokeStyle::DASH_OFFSET_MAX); let event = @@ -468,6 +450,19 @@ impl Body<'_> { } } +/// `dashes` with dash field `index` set to `value`: a number sets that entry, or adds it after the last; a cleared field +/// after the first ends the pattern there; the first field never clears (the "Dashed line" check turns dashes off). +pub(super) fn dashes_with(dashes: &[f32], index: usize, value: Option) -> Vec { + let mut next = dashes.to_vec(); + match value { + Some(length) if index < next.len() => next[index] = length as f32, + Some(length) if index == next.len() => next.push(length as f32), + None if index > 0 => next.truncate(index), + _ => {} + } + next +} + /// `value` as a field's binding value: mixed while the field is. fn held(mixed: bool, value: T) -> Mixed { if mixed { Mixed::Mixed } else { Mixed::Same(value) } @@ -526,62 +521,3 @@ fn number( }); event } - -/// The style of the tall sample: the field well and its height. -#[derive(Clone, Debug, PartialEq, ComponentStyle)] -#[non_exhaustive] -struct SampleStyle { - #[style(surface)] - surface: SurfaceLook, - #[style(metrics)] - metrics: Metrics, - /// The sample's height. - height: f32, -} - -/// The tall line sample under the rows: a [`StrokePreview`] on a sunken well, a rectangle when closed, a line -/// otherwise. It is the stroke document art the editor shows, so it paints with the content painter. -#[derive(craft_ui::contract::Component, craft_ui::contract::Props)] -#[component(content_painter, unregistered)] -struct Sample<'a> { - #[common] - common: Common, - value: &'a StrokeStyle, - closed: bool, -} - -impl Component for Sample<'_> { - const ROLE: Role = Role::IMAGE; - const PARTS: bool = false; - const STOPS: bool = false; - const INPUT: Input = Input::Display; - const SHOWS_LABEL: bool = false; - const OVERLAYS: bool = false; - type Style = SampleStyle; - type Output = Response; - - fn style(cx: &StyleCx<'_>, _: SampleStyleKey) -> SampleStyle { - SampleStyle { surface: cx.field(), metrics: Metrics::new(), height: cx.tokens.size.thumb.lg } - } - - fn sense(&self) -> Sense { - Sense::empty() - } - - fn fills(&self) -> Option { - Some(Axis::X) - } - - fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - Vec2::new(cx.style.height * SAMPLE_ASPECT, cx.style.height) - } - - fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { - let painter = ui.content_painter(cx); - StrokePreview::sized(self.value, cx.content_rect).closed(self.closed).paint(&painter, cx.content_rect); - } - - fn finish(self, cx: Cx<'_, Self>) -> Response { - cx.response.clone() - } -} diff --git a/crates/draw/src/ui/stroke/mod.rs b/crates/draw/src/ui/stroke/mod.rs index 36ee64af3..78d87d33e 100644 --- a/crates/draw/src/ui/stroke/mod.rs +++ b/crates/draw/src/ui/stroke/mod.rs @@ -40,15 +40,13 @@ impl StrokeSections { /// The Opacity row, 0–100 % (lead call 18: PhotoCraft has it, VectorCraft and DesignCraft do /// not). pub const OPACITY: Self = Self(1 << 1); - /// The "Dashed line" check, the Dash and Gap pairs, Add pair, Remove pair and Dash offset. + /// The "Dashed line" check, the dash and gap fields and Dash offset. pub const DASHES: Self = Self(1 << 2); - /// The tall line sample at the bottom. - pub const SAMPLE: Self = Self(1 << 3); /// Alignment, Caps and Corners as rows of icon toggle buttons (`Segmented` with icons) in /// place of selects (VectorCraft's panel). - pub const ICONS: Self = Self(1 << 4); - /// PhotoCraft's popover: presets, opacity, dashes and the sample, choices as selects. - pub const POPOVER: Self = Self(Self::PRESETS.0 | Self::OPACITY.0 | Self::DASHES.0 | Self::SAMPLE.0); + pub const ICONS: Self = Self(1 << 3); + /// PhotoCraft's popover: presets, opacity and dashes, choices as selects. + pub const POPOVER: Self = Self(Self::PRESETS.0 | Self::OPACITY.0 | Self::DASHES.0); /// A docked panel: dashes, choices as icon buttons. pub const PANEL: Self = Self(Self::DASHES.0 | Self::ICONS.0); @@ -136,10 +134,6 @@ pub enum StrokeField { Dashed, /// The dash or gap at this index of [`StrokeStyle::dashes`]. Dash(usize), - /// The add-pair button. - AddPair, - /// The remove-pair button. - RemovePair, /// The dash offset. DashOffset, } diff --git a/crates/draw/src/ui/stroke/stories.rs b/crates/draw/src/ui/stroke/stories.rs index b58821a3e..80841edf2 100644 --- a/crates/draw/src/ui/stroke/stories.rs +++ b/crates/draw/src/ui/stroke/stories.rs @@ -51,18 +51,18 @@ fn with_readout(data: &mut StoryData, output: impl Into, latest: Op output.into().readout(readout) } -#[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)] -fn stroke_editor_popover(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("popover", StrokeStyle::default()); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER).show(ui); +#[story(StrokeEditor<'static>, covers = [Default], drive = Drive::Never)] +fn stroke_editor_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let style = data.value("panel", StrokeStyle::default()); + let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::PANEL).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } #[story(StrokeEditor<'static>, covers = [], drive = Drive::Never)] -fn stroke_editor_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - let style = data.value("panel", StrokeStyle::default()); - let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::PANEL).show(ui); +fn stroke_editor_popover(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let style = data.value("popover", StrokeStyle::default()); + let out = StrokeEditor::new("Stroke", Bind::bound(style)).sections(StrokeSections::POPOVER).show(ui); let latest = out.events.last().map(|event| format!("{event:?}")); with_readout(data, out, latest) } diff --git a/crates/draw/src/ui/stroke/words.rs b/crates/draw/src/ui/stroke/words.rs index 5512e69f1..2ab122846 100644 --- a/crates/draw/src/ui/stroke/words.rs +++ b/crates/draw/src/ui/stroke/words.rs @@ -48,22 +48,20 @@ craft_ui::words! { open_paths: "strokeEditor.openPaths" = "Open paths use centered strokes"; /// The check that turns the dashes on. dashed_line: "strokeEditor.dashedLine" = "Dashed line"; - /// Over the pairs, for `DashUnit::Widths`. + /// Over the dash fields, for `DashUnit::Widths`. dash_widths: "strokeEditor.dashWidths" = "Dash / gap lengths × stroke width"; - /// Over the pairs, for `DashUnit::Document`. + /// Over the dash fields, for `DashUnit::Document`. dash_document: "strokeEditor.dashDocument" = "Dash / gap lengths in document units"; /// A dash length field. dash: "strokeEditor.dash" = "Dash"; /// A gap length field. gap: "strokeEditor.gap" = "Gap"; - /// The button that appends a pair. - add_pair: "strokeEditor.addPair" = "Add pair"; - /// The button that drops the last pair. - remove_pair: "strokeEditor.removePair" = "Remove pair"; + /// The accessible name of the `n`th dash field. + dash_number: template "strokeEditor.dashNumber" = "Dash {n}"; + /// The accessible name of the `n`th gap field. + gap_number: template "strokeEditor.gapNumber" = "Gap {n}"; /// The Dash offset row. dash_offset: "strokeEditor.dashOffset" = "Dash offset"; - /// The tall sample's accessible name prefix is the style's name; this is the sample row's label. - sample: "strokeEditor.sample" = "Sample"; /// Under the dash rows while the style fails `StrokeStyle::validate`. invalid: "strokeEditor.invalid" = "Use finite lengths and a positive pattern total"; } diff --git a/crates/draw/tests/it/main.rs b/crates/draw/tests/it/main.rs index a9031e131..b8f97f579 100644 --- a/crates/draw/tests/it/main.rs +++ b/crates/draw/tests/it/main.rs @@ -28,6 +28,7 @@ mod measure; // draw-stroke mod stroke_button; +mod stroke_editor; // draw-brush-presets mod brush_presets; diff --git a/crates/draw/tests/it/stroke_editor.rs b/crates/draw/tests/it/stroke_editor.rs new file mode 100644 index 000000000..ef00e0b97 --- /dev/null +++ b/crates/draw/tests/it/stroke_editor.rs @@ -0,0 +1,46 @@ +//! The stroke editor's dash fields: typing in the blank after the pattern adds an entry, clearing a later field ends +//! the pattern there, and the first field never clears. + +use craft_draw::ui::stroke::{StrokeEditor, StrokeSections, StrokeStyle}; +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers}; +use std::cell::RefCell; +use std::rc::Rc; + +/// The panel editor over a style with `dashes`, and the style it writes through to. +fn editor(dashes: Vec) -> (Fixture, Rc>) { + let style = Rc::new(RefCell::new(StrokeStyle { dashes, ..StrokeStyle::default() })); + let shown = Rc::clone(&style); + let mut fixture = Fixture::new(move |ui| { + let mut style = shown.borrow_mut(); + let _ = StrokeEditor::new("Stroke", Bind::bound(&mut *style)).sections(StrokeSections::PANEL).show(ui); + }); + fixture.settle(); + (fixture, style) +} + +/// Replaces the text of the field named `label` with `text` (empty clears it) and commits it with Enter. +fn type_into(fixture: &mut Fixture, label: &str, text: &str) { + let field = fixture.by_label(label).unwrap_or_else(|| panic!("the editor shows {label}")); + fixture.click(&field); + fixture.key(Key::A, Modifiers::COMMAND); + if text.is_empty() { + fixture.key(Key::Backspace, Modifiers::NONE); + } else { + fixture.type_text(text); + } + fixture.key(Key::Enter, Modifiers::NONE); + fixture.idle(3); +} + +#[trial] +fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() { + let (mut fixture, style) = editor(vec![4.0, 2.0]); + type_into(&mut fixture, "Dash 2", "3"); + assert_eq!(style.borrow().dashes, [4.0, 2.0, 3.0], "the blank after the pattern adds an entry"); + type_into(&mut fixture, "Gap 1", ""); + assert_eq!(style.borrow().dashes, [4.0], "clearing the second field ends the pattern there"); + type_into(&mut fixture, "Dash 1", ""); + assert_eq!(style.borrow().dashes, [4.0], "the first field never clears"); +}