panels-w12: written from its sheet

This commit is contained in:
aiongg
2026-11-14 17:56:01 +00:00
parent ac056667b1
commit ead709b8d5
12 changed files with 311 additions and 80 deletions
+1
View File
@@ -3,6 +3,7 @@
//! - [`BrushPresetPicker`]: a closed field that opens a popover with Size, Hardness, the Brush Settings and New
//! Brush Preset buttons, the gear menu and the preset browser; it reports [`BrushPick`]s and the size and hardness
//! edits.
//! - [`BrushesPanel`]: the Brushes panel, a Size field over the preset browser with Import in its footer.
//! - [`brush_row`] and [`BrushRowPaint`]: the preset rows it shows, picture chosen by [`BrushCardParts`].
//! - [`BrushPickerSettings`]: the picker's persisted view (parts and scale).
//!
+41 -13
View File
@@ -2,24 +2,30 @@
use std::hash::Hash;
use craft_behavior::EditEvents;
use craft_ui::contract::{Bind, EditResponse, Outcome};
use craft_ui::patterns::presets::{PresetEvent, PresetFooterEvent, PresetRow, PresetState};
use craft_behavior::{EditEvents, IconId};
use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, Show as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState};
use craft_ui::runtime::drag::DropZone;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::sections::FooterAction;
use craft_ui::tile_grid::TileZoom;
use egui::{Response, Ui};
use super::picker::BrushPick;
use super::settings::BrushPickerSettings;
use super::words::BrushPresetWords;
use crate::ui::brush_settings::BrushSizeField;
/// The thumbnail zoom range of the brush lists.
#[allow(dead_code)] // P3(panels-w12): pn.C49 the picker takes its range from here.
/// How far one key press changes the thumbnail scale.
const SCALE_STEP: f64 = 0.05;
/// The thumbnail zoom range of the brush lists: the picker and the panel share it.
pub(super) const BRUSH_THUMBS: TileZoom =
TileZoom::bounded(*BrushPickerSettings::SCALE_RANGE.start() as f64, *BrushPickerSettings::SCALE_RANGE.end() as f64, 0.05, 1.0);
TileZoom::bounded(*BrushPickerSettings::SCALE_RANGE.start() as f64, *BrushPickerSettings::SCALE_RANGE.end() as f64, SCALE_STEP, 1.0);
/// The Brushes panel: a Size field over a [`PresetBrowser`](craft_ui::patterns::presets::PresetBrowser)
/// of the brush presets, with Import as the footer's one action.
/// The Brushes panel: a Size field over a [`PresetBrowser`] of the brush presets, with Import as the footer's one
/// action.
#[must_use = "show the panel with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
#[pattern(probe(BrushesPanel<'static, u32>))]
@@ -70,15 +76,37 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> {
/// Shows the panel.
pub fn show(self, ui: &mut Ui) -> BrushesPanelOutput<K> {
let BrushesPanel { label, rows, state, diameter, max_size, selected, drop_zone, import } = self;
let _ = (ui, label, rows, state, diameter, max_size, selected, drop_zone, import, EditEvents::<f64>::new());
todo!("pn.C49")
let BrushesPanel { label, rows, mut state, mut diameter, max_size, mut selected, mut drop_zone, import } = self;
let words = Env::of(ui).words::<BrushPresetWords>();
let shown = Stack::new().label(label.clone()).fill().show(ui, |ui, _| {
let size = BrushSizeField::new(words.size.clone(), diameter.reborrowed(), max_size).show(ui);
let mut footer = PresetFooterOptions::new().new_group(false);
if import {
footer = footer.action(FooterAction::new(IconId::new("folder_open"), words.menu_import.clone()));
}
let mut browser = PresetBrowser::new(label.clone(), state.reborrowed(), rows)
.toolbar(true)
.row_menu(true)
.reorder(PresetReorder::items_and_groups())
.thumb_range(BRUSH_THUMBS)
.footer(footer);
if let Some(key) = selected.take() {
browser = browser.selected(key);
}
if let Some(zone) = drop_zone.take() {
browser = browser.drop_zone(zone);
}
let listed = browser.show(ui);
(size.edit, listed.events)
});
let response = shown.output;
let (diameter, events) = shown.inner.unwrap_or_else(|| (EditResponse::lifted(response.clone(), EditEvents::new(), None), Vec::new()));
BrushesPanelOutput { response, diameter, picks: picks_of(events) }
}
}
/// Maps the browser's events to picks: `Select` and `Activate` to their picks, the footer's New to
/// `NewPreset`, the footer's one custom action to `Import`, every other event to `List`.
#[allow(dead_code)] // P3(panels-w12): pn.C49 the picker maps its browser events through this.
pub(super) fn picks_of<K>(events: Vec<PresetEvent<K>>) -> Vec<BrushPick<K>> {
events
.into_iter()
+13 -13
View File
@@ -19,17 +19,16 @@ use craft_ui::patterns::presets::{
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Env, Label, UnitKind};
use craft_ui::runtime::overlay::CloseReason;
use craft_ui::tile_grid::TileZoom;
use egui::{Pos2, Response, Ui};
use super::panel::{BRUSH_THUMBS, picks_of};
use super::settings::{BrushCardPart, BrushCardParts, BrushPickerSettings};
use super::words::BrushPresetWords;
use crate::ui::brush_settings::{BrushSizeField, TipAngle, TipEllipse};
/// The largest diameter the picker's Size row allows until the app sets its engine's limit.
const DEFAULT_MAX_DIAMETER: f64 = 5000.0;
/// How far one key press changes the thumbnail scale.
const SCALE_STEP: f64 = 0.05;
/// The brush values the picker's head edits, given by the app each pass.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
@@ -67,7 +66,8 @@ pub enum BrushPick<K> {
/// A double click or Enter on a preset: the binding holds it and the picker closes.
Activate(K),
/// A browser event: `Rename` (also from the gear's Rename Brush…, which opens the name field on the current
/// preset), `Delete` (also from the gear), `Reorder`, `MoveTo` and the footer's buttons.
/// preset), `Delete` (also from the gear), `Reorder`, `MoveTo` and the footer's buttons other than New, which
/// arrives as `NewPreset`.
List(PresetEvent<K>),
/// Brush Settings…: open the Brush Settings panel.
OpenSettings,
@@ -242,6 +242,8 @@ impl Opened {
/// - **Presets.** The browser, with the scale slider (0.15 to 2.0) in its footer. The tip alone is a grid with the
/// size as each caption; the name or the stroke is a list, with the stroke band while the stroke shows. A click
/// picks and keeps the picker open; a double click or Enter picks and closes it.
/// - **Compact form.** [`compact`](Self::compact) leaves out the search row, the gear and the browser and keeps the head;
/// [`rows`](Self::rows) draws the app's rows under it.
/// - **Opening.** The closed field, or the app at a point with [`open_at`](Self::open_at) (a right-click on the
/// canvas), without the field. With [`resizable`](Self::resizable) the popover's grips resize it and the size is
/// saved.
@@ -333,9 +335,8 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
resizable,
mut opened_at,
compact,
app_rows,
mut app_rows,
} = self;
let _ = (compact, app_rows); // P3(panels-w12): pn.C60 the compact form.
let env = Env::of(ui);
let words = env.words::<BrushPresetWords>();
let name: std::sync::Arc<str> = std::sync::Arc::from(label.as_str());
@@ -377,6 +378,9 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
});
});
Divider::horizontal().show(ui);
if let Some(rows) = app_rows.take() {
rows(ui);
}
};
// The buttons and the gear at the reading end of the browser's search row.
let tools = |ui: &mut Ui| {
@@ -463,12 +467,8 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
.toolbar(true)
.search(before.search)
.keep_open()
.thumb_range(TileZoom::bounded(
f64::from(*BrushPickerSettings::SCALE_RANGE.start()),
f64::from(*BrushPickerSettings::SCALE_RANGE.end()),
SCALE_STEP,
1.0,
))
.browser(!compact)
.thumb_range(BRUSH_THUMBS)
.footer(PresetFooterOptions::new().new_group(false))
.browser_id(browser_id)
.head(head)
@@ -484,7 +484,7 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
if let Some(key) = out.picked.clone() {
picks.insert(0, if out.closed { BrushPick::Activate(key) } else { BrushPick::Select(key) });
}
picks.extend(std::mem::take(&mut out.events).into_iter().map(BrushPick::List));
picks.extend(picks_of(std::mem::take(&mut out.events)));
let after = BrushPickerState { browser, parts: next_parts.get(), search: next_search.get() };
let mut settings = None;
if after != before {
+11 -1
View File
@@ -8,7 +8,9 @@ use craft_ui::testing::pictures::{SampleTip, paint_tip, paint_wave};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use super::{BrushCardParts, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row};
use craft_ui::patterns::presets::PresetState;
use super::{BrushCardParts, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, BrushesPanel, brush_row};
use crate::ui::brush_settings::TipAngle;
const SOFT: u32 = 1;
@@ -64,6 +66,14 @@ fn picker_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
.into()
}
#[story(BrushesPanel<'static, u32>, covers = [Default], drive = Drive::Never)]
fn panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let env = Env::of(ui);
let (state, diameter) = data.value("panel", (PresetState::<u32>::new(), SOFT_SIZE));
let rows = rows(&env, BrushCardParts::ALL);
BrushesPanel::new("Brushes", &rows, Bind::bound(state), Bind::bound(diameter), MAX_SIZE).selected(SOFT).import(true).show(ui).into()
}
#[story(BrushPresetPicker<'static, u32>, covers = [Mixed], drive = Drive::Never)]
fn picker_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let env = Env::of(ui);
+10 -12
View File
@@ -83,11 +83,11 @@ impl<W> Outcome for TransformBarOutput<W> {
/// phase).
/// - Warp phase: the app's [`warp_fields`](Self::warp_fields) group in place of the fields; then cancel, commit, Reset
/// warp, a rule and the switch.
/// - [`groups`](Self::groups) narrows the strip; [`mode_switch`](Self::mode_switch) hides the switch (Content-Aware
/// Scale).
/// - [`groups`](Self::groups) narrows the strip. The switch is hidden for content that cannot warp (Content-Aware
/// Scale, masks, channels, Quick Mask): the session's `BoxAllow::warp`.
/// - Every control is an ordinary focusable control. The bar never changes the session: it reports
/// [`TransformEdit`]s, and writes the persisted choices (Show Reference Point, the aspect link, the interpolation,
/// the W and H unit) to its settings binding as well.
/// the W and H unit, the relative position) to its settings binding as well.
#[must_use = "show the bar with `show`"]
#[derive(craft_ui::contract::Pattern)]
#[pattern(probe(TransformBar<'static, ()>))]
@@ -96,7 +96,6 @@ pub struct TransformBar<'a, W> {
session: &'a TransformSession<W>,
settings: Bind<'a, TransformSettings>,
groups: TransformGroups,
mode_switch: bool,
warp_fields: Option<BarSlot<'a>>,
extra: Option<BarSlot<'a>>,
units: (RulerText, RulerText),
@@ -112,7 +111,6 @@ impl<'a, W: TransformWarp> TransformBar<'a, W> {
session,
settings,
groups: TransformGroups::ALL,
mode_switch: true,
warp_fields: None,
extra: None,
units: (pixels, pixels),
@@ -126,11 +124,6 @@ impl<'a, W: TransformWarp> TransformBar<'a, W> {
self
}
/// Whether the Free Transform / Warp switch shows; true by default.
pub fn mode_switch(mut self, shown: bool) -> Self {
self.mode_switch = shown;
self
}
/// The Warp phase's group, shown in place of the fields.
pub fn warp_fields(mut self, slot: BarSlot<'a>) -> Self {
@@ -158,7 +151,7 @@ impl<'a, W: TransformWarp> TransformBar<'a, W> {
/// Shows the bar.
pub fn show(self, ui: &mut Ui) -> TransformBarOutput<W> {
let TransformBar { label, session, mut settings, groups, mode_switch, mut warp_fields, mut extra, units, size_units } = self;
let TransformBar { label, session, mut settings, groups, mut warp_fields, mut extra, units, size_units } = self;
let env = Env::of(ui);
let words = env.words::<TransformBarWords>();
let points = env.units().points_per_inch();
@@ -169,13 +162,14 @@ impl<'a, W: TransformWarp> TransformBar<'a, W> {
let mut reset_warp = false;
let mut unit_picked = None;
let mut switched = false;
let warp_allowed = session.allows().warp;
// Reset warp and the mode switch stay in view after commit and cancel while the fields scroll.
let trailing = |ui: &mut Ui, _: &mut BodyCx<'_>| {
if warping {
let reset = IconButton::new(IconId::new("undo")).label(words.reset_warp.clone()).show(ui);
reset_warp = clicked(&reset);
}
if mode_switch {
if warp_allowed {
Divider::vertical().show(ui);
let switch = IconButton::new(IconId::new("grid")).label(words.switch_warp.clone()).selected(warping).show(ui);
switched = clicked(&switch);
@@ -199,6 +193,7 @@ impl<'a, W: TransformWarp> TransformBar<'a, W> {
let mut fields = TransformFields::new(label.clone(), Bind::given(row), session.rect(), Bind::given(current.aspect_linked))
.bar()
.groups(groups)
.relative(Bind::given(current.relative_position))
.units(units.0, units.1)
.size_unit(size_unit_of(unit, units.0, points))
.interpolation(Bind::given(session.interpolation()));
@@ -247,6 +242,9 @@ impl<'a, W: TransformWarp> TransformBar<'a, W> {
if let Some(on) = shown.linked {
settings.aspect_linked = on;
}
if let Some(on) = shown.relative {
settings.relative_position = on;
}
if let Some(choice) = shown.interpolation {
edits.push(TransformEdit::Interpolation(choice));
settings.interpolation = Some(choice);
@@ -13,6 +13,7 @@ use super::session_bar::TransformBarWords;
use craft_behavior::geometry::quad::BoxState;
use craft_behavior::kurbo::Rect;
use craft_behavior::{EditEvent, EditEvents, GestureId, IconId, Mixed, RulerUnits};
use craft_ui::buttons::ToggleButton;
use craft_ui::canvas::RulerText;
use craft_ui::contract::{
Bind, BodyCx, Entry, FieldLayout, GlyphLabel, LabelKind, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing,
@@ -51,7 +52,7 @@ craft_ui::words! {
}
}
/// The groups of cells the options-bar form shows; [`TransformGroups::ALL`] is all of them.
/// The groups of cells the fields show, in either form; [`TransformGroups::ALL`] is all of them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TransformGroups {
@@ -178,10 +179,11 @@ impl Outcome for TransformFieldsOutput {
/// [rulers' units](Self::units) and move the box with it; W and H scale it about the reference point, as a
/// percentage of the box before the transform or as a length ([`size_unit`](Self::size_unit)); the angle and the two
/// skews turn and lean it about the reference point. A flipped box reads as a negative W or H and keeps its sign.
/// With [`relative`](Self::relative) on, X and Y are the reference point's offset instead of its position.
/// Limits: position ±300 000 document units, angle −180° to 180°, skew ±89°, scale as far as the box stays
/// within the position limit.
/// - **Typed text** may carry another unit's spelling ("40px", "2in"); a percentage is read against the box's side
/// before the transform.
/// before the transform, in X and Y against the [`document`](Self::document)'s side when it is given.
/// - **Linked** ([`new`](Self::new)'s binding): W or H also scales the other by the same factor, each kept within its
/// limit.
/// - **One gesture per field gesture.** A scrub or a typing run of a field is one gesture of the row; each value it
@@ -190,9 +192,10 @@ impl Outcome for TransformFieldsOutput {
/// - **W and H unit.** With [`size_units`](Self::size_units), a secondary click, the Menu key or Shift+F10 on W or H
/// opens a menu of the units; a pick is [`TransformFieldsOutput::unit_picked`].
/// - **Panel form** (the default): the compact reference point with X and Y on one row, W, the link and H on the
/// next, the angle, then the H and V skews on one row.
/// next, the angle, then the H and V skews on one row. [`groups`](Self::groups) leaves out the rows of hidden groups.
/// - **Bar form** ([`bar`](Self::bar)): the compact reference point, then captioned fields in Photoshop's order with a
/// divider between the groups, the interpolation select last. [`groups`](Self::groups) narrows the strip.
/// divider between the groups, the Δ toggle between X and Y, the interpolation select last.
/// [`groups`](Self::groups) narrows the strip.
#[must_use = "show the fields with `show`"]
#[derive(craft_ui::contract::Pattern)]
pub struct TransformFields<'a> {
@@ -253,7 +256,7 @@ impl<'a> TransformFields<'a> {
self
}
/// The groups the bar form shows (all by default).
/// The groups shown, in either form (all by default).
pub fn groups(mut self, groups: TransformGroups) -> Self {
self.groups = groups;
self
@@ -293,7 +296,6 @@ impl<'a> TransformFields<'a> {
pub fn show(self, ui: &mut Ui) -> TransformFieldsOutput {
let TransformFields { label, row, start, linked, size_unit, x, y, bar, groups, interpolation, size_units, enabled, relative, document } =
self;
let _ = (relative, document); // P3(panels-w12): tl.R5, pn.C48
let env = Env::of(ui);
let mut cells = Cells {
words: env.words::<TransformFieldWords>(),
@@ -310,6 +312,8 @@ impl<'a> TransformFields<'a> {
y,
groups,
enabled,
relative,
document,
out: Out::default(),
};
let response = if bar {
@@ -317,8 +321,8 @@ impl<'a> TransformFields<'a> {
} else {
FieldGroup::new(label).enabled(enabled).show(ui, |ui, cx| cells.rows(ui, cx)).output
};
let Out { events, unit_picked, linked, interpolation } = cells.out;
TransformFieldsOutput { response, events, unit_picked, linked, interpolation, relative: None }
let Out { events, unit_picked, linked, interpolation, relative } = cells.out;
TransformFieldsOutput { response, events, unit_picked, linked, interpolation, relative }
}
}
@@ -329,6 +333,7 @@ struct Out {
unit_picked: Option<UnitKind>,
linked: Option<bool>,
interpolation: Option<Interpolation>,
relative: Option<bool>,
}
/// The pass's state while the cells are shown.
@@ -347,6 +352,8 @@ struct Cells<'a> {
y: RulerText,
groups: TransformGroups,
enabled: bool,
relative: Option<Bind<'a, bool>>,
document: Option<craft_behavior::kurbo::Size>,
out: Out,
}
@@ -365,7 +372,8 @@ impl Cells<'_> {
_ => start,
};
let linked = matches!(self.linked.reborrow().read(cx), Some(Mixed::Same(true)));
let conversion = Conversion { rect: self.start, x: self.x, y: self.y, size: self.size_unit.clone(), linked };
let relative = self.relative.as_mut().is_some_and(|on| matches!(on.reborrow().read(cx), Some(Mixed::Same(true))));
let conversion = Conversion { rect: self.start, x: self.x, y: self.y, size: self.size_unit.clone(), linked, document: self.document, relative };
Pass { before, conversion, bases: cx.memory::<Bases>().clone() }
}
@@ -462,6 +470,15 @@ impl Cells<'_> {
}
}
/// The Δ toggle between X and Y; shown when the host gave the `relative` binding.
fn relative_toggle(&mut self, ui: &mut Ui) {
let Some(bind) = self.relative.as_mut() else { return };
let toggled = ToggleButton::new(self.words.relative.clone(), bind.reborrowed()).icon(IconId::new("triangle")).icon_only().enabled(self.enabled).show(ui);
if let Some(on) = toggled.value().copied() {
self.out.relative = Some(on);
}
}
/// W, the link and H in one row.
fn size(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>, pass: &mut Pass) {
Row::new().show(ui, |ui, _| {
@@ -495,17 +512,30 @@ impl Cells<'_> {
/// The panel form: the compact reference point with X and Y, W with the link and H, the angle, the two skews.
fn rows(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
let mut pass = self.pass(cx);
Row::new().id_salt("position").show(ui, |ui, _| {
self.reference(ui, cx, &pass, true);
self.field(ui, cx, &mut pass, TransformField::X);
self.field(ui, cx, &mut pass, TransformField::Y);
});
self.size(ui, cx, &mut pass);
self.field(ui, cx, &mut pass, TransformField::Angle);
Row::new().id_salt("skew").show(ui, |ui, _| {
self.field(ui, cx, &mut pass, TransformField::SkewH);
self.field(ui, cx, &mut pass, TransformField::SkewV);
});
let groups = self.groups;
if groups.reference || groups.position {
Row::new().id_salt("position").show(ui, |ui, _| {
if groups.reference {
self.reference(ui, cx, &pass, true);
}
if groups.position {
self.field(ui, cx, &mut pass, TransformField::X);
self.field(ui, cx, &mut pass, TransformField::Y);
}
});
}
if groups.size {
self.size(ui, cx, &mut pass);
}
if groups.angle {
self.field(ui, cx, &mut pass, TransformField::Angle);
}
if groups.skew {
Row::new().id_salt("skew").show(ui, |ui, _| {
self.field(ui, cx, &mut pass, TransformField::SkewH);
self.field(ui, cx, &mut pass, TransformField::SkewV);
});
}
*cx.memory::<Bases>() = pass.bases;
}
@@ -526,6 +556,7 @@ impl Cells<'_> {
}
if groups.position {
self.field(ui, cx, &mut pass, TransformField::X);
self.relative_toggle(ui);
self.field(ui, cx, &mut pass, TransformField::Y);
any.set(true);
}
@@ -1,8 +1,8 @@
//! Stories of the transform fields: the panel form, and the options-bar form in percent and in a length unit.
use super::{TransformFields, TransformRow, size_unit_of};
use super::{TransformFields, TransformGroups, TransformRow, size_unit_of};
use craft_behavior::geometry::quad::BoxState;
use craft_behavior::kurbo::Rect;
use craft_behavior::kurbo::{Rect, Size};
use craft_behavior::{RulerUnits, Ticks};
use craft_ui::bars::{Bar, BarKind};
use craft_ui::canvas::RulerText;
@@ -39,6 +39,36 @@ fn panel_form(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1)).show(ui).into()
}
/// The panel form of a layer's properties: position and size only, percentages read against the document.
#[story(TransformFields<'static>, covers = [], drive = Drive::Never)]
fn panel_form_with_document(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = data.value("state", sample());
let mut groups = TransformGroups::NONE;
groups.reference = true;
groups.position = true;
groups.size = true;
TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1))
.groups(groups)
.document(Size::new(1000.0, 400.0))
.show(ui)
.into()
}
/// The bar form with the Δ toggle on: X and Y show the reference point's offset.
#[story(TransformFields<'static>, covers = [], drive = Drive::Never)]
fn bar_form_relative(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = data.value("state", (sample().0, true, true));
Bar::new("Options", BarKind::Options)
.show(ui, |ui, _| {
TransformFields::new("Transform", Bind::bound(&mut state.0), START, Bind::bound(&mut state.1))
.bar()
.relative(Bind::bound(&mut state.2))
.show(ui);
})
.output
.into()
}
#[story(TransformFields<'static>, covers = [], drive = Drive::Never)]
fn bar_form_in_percent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = data.value("state", sample());
@@ -2,7 +2,7 @@
use super::{TransformField, TransformRow};
use craft_behavior::geometry::quad::{BoxState, SKEW_LIMIT};
use craft_behavior::kurbo::{Rect, Vec2};
use craft_behavior::kurbo::{Rect, Size, Vec2};
use craft_behavior::{NumberCodec, RulerUnits};
use craft_ui::canvas::RulerText;
use craft_ui::runtime::env::{UnitKind, Units};
@@ -60,8 +60,8 @@ impl Default for SizeUnit {
}
}
/// How the fields read and write a box: the box before the transform (`rect`), the units, and whether W and H are
/// linked.
/// How the fields read and write a box: the box before the transform (`rect`), the units, whether W and H are
/// linked, the document a typed X or Y percentage reads against and whether X and Y show the reference point's offset.
#[derive(Clone, Debug)]
pub(super) struct Conversion {
pub(super) rect: Rect,
@@ -69,6 +69,10 @@ pub(super) struct Conversion {
pub(super) y: RulerText,
pub(super) size: SizeUnit,
pub(super) linked: bool,
/// The document's size; without it X and Y read a typed percentage against the box's side.
pub(super) document: Option<Size>,
/// X and Y are the reference point's offset from where the box's origin point maps.
pub(super) relative: bool,
}
impl Conversion {
@@ -77,6 +81,18 @@ impl Conversion {
(if axis == 0 { self.rect.width() } else { self.rect.height() }).abs()
}
/// The reference point's coordinate along `axis` (0: x, 1: y) in document units: its position, or while
/// `relative` its offset from the point the inverse map gives it in the box before the transform.
fn position(&self, state: &BoxState, axis: usize) -> f64 {
let (pivot, origin) = if self.relative {
let origin = state.origin_of_pivot(self.rect);
(state.pivot, origin)
} else {
(state.pivot, craft_behavior::kurbo::Point::ORIGIN)
};
if axis == 0 { pivot.x - origin.x } else { pivot.y - origin.y }
}
/// Field units of the size fields per unit of scale factor.
fn per_factor(&self, axis: usize) -> f64 {
match &self.size {
@@ -120,8 +136,8 @@ impl Conversion {
pub(super) fn shown(&self, state: &BoxState, skew_v: f64, field: TransformField) -> f64 {
let parts = state.parts(self.rect, skew_v);
match field {
TransformField::X => state.pivot.x * self.x.units.per_doc,
TransformField::Y => state.pivot.y * self.y.units.per_doc,
TransformField::X => self.position(state, 0) * self.x.units.per_doc,
TransformField::Y => self.position(state, 1) * self.y.units.per_doc,
TransformField::W => parts.w * self.per_factor(0),
TransformField::H => parts.h * self.per_factor(1),
TransformField::Angle => parts.angle,
@@ -137,8 +153,8 @@ impl Conversion {
let now = state.parts(self.rect, skew_v);
let mut to = now;
match field {
TransformField::X => return (state.moved(Vec2::new(value / self.x.units.per_doc - state.pivot.x, 0.0)), skew_v),
TransformField::Y => return (state.moved(Vec2::new(0.0, value / self.y.units.per_doc - state.pivot.y)), skew_v),
TransformField::X => return (state.moved(Vec2::new(value / self.x.units.per_doc - self.position(state, 0), 0.0)), skew_v),
TransformField::Y => return (state.moved(Vec2::new(0.0, value / self.y.units.per_doc - self.position(state, 1))), skew_v),
TransformField::W | TransformField::H => {
let axis = usize::from(field == TransformField::H);
let factor = value / self.per_factor(axis);
@@ -169,14 +185,19 @@ impl Conversion {
/// The reader of typed text for `field`: the field's own unit spellings, and for lengths and percentages every
/// other pixel and length unit, converted through the document's resolution. A percentage is read against the
/// box's side before the transform.
/// box's side before the transform; for X and Y against the document's side when it is known.
pub(super) fn codec(&self, units: &Units, field: TransformField) -> NumberCodec {
let (kind, decimals) = self.format(field);
let reader = match field {
TransformField::Angle | TransformField::SkewH | TransformField::SkewV => units.reader(Some(kind)),
_ => {
let points = units.points_per_inch();
let side = self.side(usize::from(matches!(field, TransformField::H | TransformField::Y))).max(NO_SIDE);
let axis = usize::from(matches!(field, TransformField::H | TransformField::Y));
let side = match (field, self.document) {
(TransformField::X | TransformField::Y, Some(document)) => (if axis == 0 { document.width } else { document.height }).abs(),
_ => self.side(axis),
}
.max(NO_SIDE);
units.document_reader(kind, side, pixels_per_inch(self.x, points), points)
}
};
+59 -4
View File
@@ -3,7 +3,7 @@
use craft_behavior::EditEvent;
use craft_behavior::geometry::quad::BoxState;
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::kurbo::{Point, Rect, Size};
use craft_draw::ui::transform::{SizeUnit, TransformFields, TransformGroups, TransformRow};
use craft_ui::canvas::RulerText;
use craft_ui::contract::Bind;
@@ -19,6 +19,7 @@ struct Host {
row: TransformRow,
linked: bool,
enabled: bool,
relative: bool,
events: Vec<EditEvent<TransformRow>>,
}
@@ -27,6 +28,8 @@ struct Config {
size_unit: SizeUnit,
units: Option<RulerText>,
groups: TransformGroups,
document: Option<Size>,
relative: bool,
}
struct Harness {
@@ -35,15 +38,15 @@ struct Harness {
}
fn plain() -> Config {
Config { bar: false, size_unit: SizeUnit::default(), units: None, groups: TransformGroups::ALL }
Config { bar: false, size_unit: SizeUnit::default(), units: None, groups: TransformGroups::ALL, document: None, relative: false }
}
fn harness_of(row: TransformRow, config: Config) -> Harness {
let host = Rc::new(RefCell::new(Host { row, linked: true, enabled: true, events: Vec::new() }));
let host = Rc::new(RefCell::new(Host { row, linked: true, enabled: true, relative: config.relative, events: Vec::new() }));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| {
let mut host = shown.borrow_mut();
let Host { row, linked, enabled, events } = &mut *host;
let Host { row, linked, enabled, relative, events } = &mut *host;
let mut fields =
TransformFields::new("Transform", Bind::bound(row), START, Bind::bound(linked)).size_unit(config.size_unit.clone()).enabled(*enabled);
if config.bar {
@@ -52,6 +55,12 @@ fn harness_of(row: TransformRow, config: Config) -> Harness {
if let Some(units) = config.units {
fields = fields.units(units, units);
}
if let Some(document) = config.document {
fields = fields.document(document);
}
if config.relative {
fields = fields.relative(Bind::bound(relative));
}
let output = fields.show(ui);
events.extend(output.events);
});
@@ -102,6 +111,52 @@ fn hostile_typed_lengths_flip_clamp_or_collapse() {
assert!(row.state.quad.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{row:?}");
}
/// A typed percentage in X and Y is read against the document's sides, in W against the box's.
#[trial]
fn x_and_y_read_a_typed_percent_against_the_document() {
let config = Config { document: Some(Size::new(1000.0, 400.0)), ..plain() };
let mut h = harness_of(TransformRow::new(BoxState::from_rect(START), 0.0), config);
h.type_into("X position", "50%");
h.type_into("Y position", "50%");
h.type_into("Width", "50%");
let row = h.row();
assert!((row.state.pivot.x - 500.0).abs() < 1e-6 && (row.state.pivot.y - 200.0).abs() < 1e-6, "{row:?}");
let width = row.state.quad[0].distance(row.state.quad[1]);
assert!((width - 100.0).abs() < 1e-6, "{row:?}");
}
/// With the Δ toggle on, X and Y read and move the reference point's offset.
#[trial]
fn relative_x_and_y_read_and_move_by_the_reference_points_offset() {
let relative = || Config { bar: true, relative: true, ..plain() };
let start = TransformRow::new(BoxState::from_rect(START), 0.0);
let mut h = harness_of(start, relative());
// A fresh box reads 0: typing 0 moves nothing, where an absolute X would move the box to the origin.
h.type_into("X position", "0");
assert_eq!(h.row().state, start.state, "a fresh box reads an offset of 0");
h.type_into("X position", "10");
let moved = h.row();
assert!((moved.state.pivot.x - start.state.pivot.x - 10.0).abs() < 1e-9, "{moved:?}");
assert!(moved.state.quad.iter().zip(&start.state.quad).all(|(p, q)| (p.x - q.x - 10.0).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9), "{moved:?}");
h.type_into("X position", "10");
assert_eq!(h.row().state, moved.state, "the offset now reads 10, so typing 10 moves nothing");
// A fractional Y that the field cannot hold stays exactly where it was when only X is typed.
let shifted = BoxState::new(start.state.quad.map(|p| Point::new(p.x, p.y + 0.1)), Point::new(start.state.pivot.x, start.state.pivot.y + 0.1));
let mut h = harness_of(TransformRow::new(shifted, 0.0), relative());
h.type_into("X position", "20");
let after = h.row();
assert!(after.state.quad.iter().zip(&shifted.quad).all(|(p, q)| p.y == q.y), "{after:?}");
assert_eq!(after.state.pivot.y, shifted.pivot.y);
// A box flattened to zero height still reads a finite offset.
let flat = BoxState::new([Point::new(0.0, 50.0), Point::new(200.0, 50.0), Point::new(200.0, 50.0), Point::new(0.0, 50.0)], Point::new(100.0, 50.0));
let mut h = harness_of(TransformRow::new(flat, 0.0), relative());
h.type_into("X position", "5");
let row = h.row();
assert!(row.state.pivot.x.is_finite() && row.state.quad.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{row:?}");
}
/// Typing 50 into W of a distorted box digit by digit gives the box typing it at once gives.
#[trial]
fn typing_50_into_w_of_a_distorted_box_equals_typing_50_once_from_the_start_box() {
+11
View File
@@ -161,6 +161,17 @@ fn a_held_enter_that_opened_a_modal_does_not_answer_it() {
frames.frame(vec![key_press(Key::Enter, Modifiers::NONE)], &mut show);
frames.idle(3, &mut show);
assert!(!open.get(), "a fresh Enter answers the alert");
// An Enter pressed and released in the pass that opens the alert leaves it open as well: nothing of it is held
// when the alert shows, and a fresh press answers it.
frames.frame(vec![key_release(Key::Enter, Modifiers::NONE)], &mut show);
frames.idle(3, &mut show);
focus(&mut frames, "field", &mut show);
frames.frame(vec![key_press(Key::Enter, Modifiers::NONE), key_release(Key::Enter, Modifiers::NONE)], &mut show);
frames.idle(3, &mut show);
assert!(open.get(), "a press and release in the opening pass leaves the alert open");
frames.frame(vec![key_press(Key::Enter, Modifiers::NONE)], &mut show);
frames.idle(3, &mut show);
assert!(!open.get(), "a fresh Enter answers the alert");
}
/// A search field over a list it drives, inline or in a dialog, and the keys of the rows the list activated.
@@ -576,7 +576,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
columns,
empty: empty_text,
} = self;
let _ = &empty_text; // P3(panels-w12): pn.C50
let env = Env::of(ui);
let words = env.words::<PresetWords>();
let list_id = rows_id(browser_id.unwrap_or_else(|| ui.scope_id()));
@@ -673,7 +673,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
};
let (response, displayed, pass) = if shown.is_empty() && actions.is_empty() {
let message = if query.is_empty() { words.empty.clone() } else { words.no_match.clone() };
let message = if query.is_empty() { empty_text.clone().unwrap_or_else(|| words.empty.clone()) } else { words.no_match.clone() };
let response = Notice::new(Tone::Neutral, message).layout(NoticeLayout::Centred).show(ui).response;
(response, Vec::new(), Pass { seen: Vec::new(), grid: Vec::new() })
} else if view == PresetView::Grid {
+50 -4
View File
@@ -1,6 +1,7 @@
//! The rules of the panels family: an inspector keys its controls by the target and shows the empty notice for no
//! target.
mod history;
mod palette;
mod tour;
@@ -8,21 +9,31 @@ use craft_ui::choice::Checkbox;
use craft_ui::contract::{Bind, Props as _, Show as _};
use craft_ui::patterns::panels::Inspector;
use craft_ui::testing::{Fixture, trial};
use egui::Id;
use std::cell::Cell;
use craft_ui::text::NumberField;
use egui::{Id, Key, Modifiers};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// The values the targets hold and the edits their number fields reported.
struct Values {
a: f64,
b: f64,
landed: Vec<(&'static str, f64)>,
}
/// What the inspector's body showed in the last pass.
struct Rig {
fixture: Fixture,
target: Rc<Cell<Option<&'static str>>>,
field: Rc<Cell<Option<Id>>>,
values: Rc<RefCell<Values>>,
}
fn rig(first: Option<&'static str>) -> Rig {
let target = Rc::new(Cell::new(first));
let field = Rc::new(Cell::new(None));
let (shown_target, shown_field) = (target.clone(), field.clone());
let values = Rc::new(RefCell::new(Values { a: 10.0, b: 77.0, landed: Vec::new() }));
let (shown_target, shown_field, shown_values) = (target.clone(), field.clone(), values.clone());
let mut fixture = Fixture::new(move |ui| {
let mut inspector = Inspector::new("Properties").header("Layer");
if let Some(target) = shown_target.get() {
@@ -30,10 +41,23 @@ fn rig(first: Option<&'static str>) -> Rig {
}
inspector.show(ui, |ui, _| {
shown_field.set(Some(Checkbox::new(Bind::given(false)).label("Visible").show(ui).response.id));
if let Some(target) = shown_target.get() {
let mut values = shown_values.borrow_mut();
let held = if target == "a" { values.a } else { values.b };
let shown = NumberField::new("Value", Bind::given(Some(held))).show(ui);
if let Some(landed) = shown.edit.events.landed().copied().flatten() {
values.landed.push((target, landed));
if target == "a" {
values.a = landed;
} else {
values.b = landed;
}
}
}
});
});
fixture.settle();
Rig { fixture, target, field }
Rig { fixture, target, field, values }
}
impl Rig {
@@ -55,3 +79,25 @@ fn an_inspector_keys_its_controls_by_the_target() {
rig.show(Some("a"));
assert_eq!(rig.field.get(), Some(first), "the first target gets its ids back");
}
/// What a number field typed into under one target does when another target is shown: nothing typed under A reaches B,
/// and A's field never shows B's value.
#[trial]
fn an_inspector_keeps_a_draft_with_its_target() {
let mut rig = rig(Some("a"));
let field = rig.fixture.by_label("Value").expect("the body shows a number field for target a");
rig.fixture.click(&field);
rig.fixture.key(Key::A, Modifiers::COMMAND);
rig.fixture.type_text("+25");
rig.fixture.idle(2);
rig.show(Some("b"));
{
let values = rig.values.borrow();
assert_eq!(values.b, 77.0, "the draft of target a does not land on b");
assert!(values.landed.iter().all(|(target, _)| *target != "b"), "no edit is reported for b: {:?}", values.landed);
}
assert!(rig.fixture.texts().iter().any(|run| run.text.contains("77")), "b's field shows b's value");
rig.show(Some("a"));
assert!(rig.fixture.texts().iter().all(|run| !run.text.contains("77")), "a's field never shows b's value");
assert_eq!(rig.values.borrow().b, 77.0);
}