From 62729b3af641ce57cc94ece2cae49dee69b3271c Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 18:18:25 +0000 Subject: [PATCH] dialogs-w2: net change of 5 commits - dialogs-w2: repair 1 - dialogs-w2: finished by an agent - dialogs-w2: finished by an agent - dialogs-w2: review fixes (review-1) - dialogs-w2: review fixes (review-1b) --- crates/behavior/src/item_layout.rs | 6 + crates/behavior/src/item_source.rs | 4 + crates/behavior/src/nav/step.rs | 11 +- crates/color-ui/src/ui/picker/compact.rs | 7 +- crates/color-ui/src/ui/picker/full.rs | 2 +- crates/color-ui/src/ui/picker/mod.rs | 35 ++- crates/color-ui/src/ui/picker/stories.rs | 44 +++- crates/color-ui/src/ui/picker_dialog.rs | 133 ++++++++-- crates/color-ui/tests/it/picker.rs | 69 ++++- crates/ui-contract/src/primitives/draw.rs | 36 ++- crates/ui-contract/src/primitives/kit.rs | 25 +- crates/ui-widgets/src/choice/swatch.rs | 60 ++++- .../ui-widgets/src/choice/swatch/stories.rs | 8 +- crates/ui-widgets/src/choice/swatch_table.rs | 244 +++++++++++++++++- .../src/choice/swatch_table/stories.rs | 13 +- crates/ui-widgets/tests/it/pickers/mod.rs | 1 + .../tests/it/pickers/swatch_table.rs | 86 ++++++ 17 files changed, 710 insertions(+), 74 deletions(-) create mode 100644 crates/ui-widgets/tests/it/pickers/swatch_table.rs diff --git a/crates/behavior/src/item_layout.rs b/crates/behavior/src/item_layout.rs index 0332d57e8..9c26a1c0e 100644 --- a/crates/behavior/src/item_layout.rs +++ b/crates/behavior/src/item_layout.rs @@ -39,6 +39,12 @@ pub trait ItemLayout { None } + /// `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows + /// are offset against each other; 0 when they line up. + fn column_shift(&self, _from: usize, _to: usize) -> isize { + 0 + } + /// Whether item `at` takes a place in the layout; a hidden item (in a closed group) cannot take the lead. fn shown(&self, _at: usize) -> bool { true diff --git a/crates/behavior/src/item_source.rs b/crates/behavior/src/item_source.rs index 9908e16f6..871e43d4c 100644 --- a/crates/behavior/src/item_source.rs +++ b/crates/behavior/src/item_source.rs @@ -178,6 +178,10 @@ impl NavOutline for Outline<'_, K> { self.layout.and_then(|layout| layout.row_len(row)) } + fn column_shift(&self, from: usize, to: usize) -> isize { + self.layout.map_or(0, |layout| layout.column_shift(from, to)) + } + fn columns(&self) -> usize { self.columns } diff --git a/crates/behavior/src/nav/step.rs b/crates/behavior/src/nav/step.rs index 8b20ca291..bb93f2df4 100644 --- a/crates/behavior/src/nav/step.rs +++ b/crates/behavior/src/nav/step.rs @@ -64,6 +64,12 @@ pub trait NavOutline { None } + /// `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are + /// offset against each other (a honeycomb's). 0 for rows that line up. + fn column_shift(&self, _from: usize, _to: usize) -> isize { + 0 + } + /// `Cell`: the cells of every position (a row of a sheet). fn columns(&self) -> usize { 1 @@ -325,8 +331,9 @@ fn ragged(outline: &dyn NavOutline, state: &NavState, lead: usize, mv: NavMove) let Some((row, column, _)) = locate(outline, lead) else { return NavStep::Unhandled }; let rows = (0..).take_while(|&r| outline.row_len(r).is_some()).count(); // A row without a position that takes the lead (a closed group's) is passed over in the move's direction. - let toward = |rows: Vec| moved(rows.into_iter().find_map(|row| ragged_at(outline, row, column))); - let vertical = |to: Option| moved(to.and_then(|row| ragged_at(outline, row, column))); + let shifted = |to: usize| column.saturating_add_signed(outline.column_shift(row, to)); + let toward = |rows: Vec| moved(rows.into_iter().find_map(|to| ragged_at(outline, to, shifted(to)))); + let vertical = |to: Option| moved(to.and_then(|to| ragged_at(outline, to, shifted(to)))); match mv { NavMove::Back => moved(neighbour(outline, state, lead, false)), NavMove::Forward => moved(neighbour(outline, state, lead, true)), diff --git a/crates/color-ui/src/ui/picker/compact.rs b/crates/color-ui/src/ui/picker/compact.rs index fa1953b14..b084a7a55 100644 --- a/crates/color-ui/src/ui/picker/compact.rs +++ b/crates/color-ui/src/ui/picker/compact.rs @@ -46,7 +46,12 @@ impl<'a> Body<'a> { let words = Env::of(ui).words::(); let model = self.models.iter().copied().find(|m| Some(m.id()) == pass.model); let visible: Vec<&dyn ColorModel> = model.into_iter().chain([pass.mode.model()]).collect(); - self.area_and_strip(ui, pass, &visible, got); + Row::new().show(ui, |ui, _| { + self.area_and_strip(ui, pass, &visible, got); + if let Some(current) = self.compare { + self.compare_swatch(ui, pass, current, &words, got); + } + }); if let Some(model) = model { FieldGroup::new(words.channels.as_str().to_owned()).labels(LabelScheme::Inspector).show(ui, |ui, _| { let values = pass.shown.values_in(model); diff --git a/crates/color-ui/src/ui/picker/full.rs b/crates/color-ui/src/ui/picker/full.rs index 0769f78e2..6a3b9099a 100644 --- a/crates/color-ui/src/ui/picker/full.rs +++ b/crates/color-ui/src/ui/picker/full.rs @@ -214,7 +214,7 @@ impl<'a> Body<'a> { /// The compare swatch: the colour being edited over the current one, with their captions; a click on the current /// half sets it. - fn compare_swatch(&self, ui: &mut Ui, pass: &Pass<'a>, current: Mixed, words: &ColorPickerWords, got: &mut Collected) { + pub(super) fn compare_swatch(&self, ui: &mut Ui, pass: &Pass<'a>, current: Mixed, words: &ColorPickerWords, got: &mut Collected) { let caption = |text: &str| Text::new(text.to_owned()).role(TypeRole::Caption).shade(Shade::Muted); Stack::new().gap(Gap::Tight).show(ui, |ui, _| { caption(words.new_caption.as_str()).show(ui); diff --git a/crates/color-ui/src/ui/picker/mod.rs b/crates/color-ui/src/ui/picker/mod.rs index 9e2ced8e8..6d8c77d2e 100644 --- a/crates/color-ui/src/ui/picker/mod.rs +++ b/crates/color-ui/src/ui/picker/mod.rs @@ -157,7 +157,7 @@ craft_ui::words! { /// What the picker keeps between passes. #[derive(Clone, Default)] struct Memo { - /// The model of the Compact rows. + /// The model of the Compact rows while the host binds none ([`ColorPicker::shown_model`]). model: Option<&'static str>, /// What the area and strip show while the host holds no mode. mode: AreaMode, @@ -298,8 +298,8 @@ pub struct ColorPicker<'a> { /// Whether the Full layout focuses its hex field when it first shows; on by default. #[prop] focus_on_open: bool, - /// The Compact rows' model, bound by the host. - #[allow(dead_code)] // P3(dialogs-w2): dg.F7 + /// The Compact rows' model, held by the host; kept per picker without it. + #[prop] shown_model: Option>>, } @@ -349,12 +349,6 @@ impl<'a> ColorPicker<'a> { self } - /// Binds the model the Compact rows show, so the host holds the model switch; the compare swatch shows in Compact. - pub fn shown_model(mut self, model: Bind<'a, Option<&'static str>>) -> Self { - self.shown_model = Some(model); - self - } - /// The warnings beside the Full layout's compare swatch (out-of-gamut and web-colour warnings); a click on one /// sets its nearest passing colour. The host gives this pass's warnings for the colour it shows. pub fn warnings(mut self, warnings: impl IntoIterator) -> Self { @@ -387,7 +381,7 @@ impl<'a> ColorPicker<'a> { constrain, sampled, focus_on_open, - shown_model: _, // P3(dialogs-w2): dg.F7 + mut shown_model, } = self; let full = layout == ColorPickerLayout::Full; let models: Vec<&'a dyn ColorModel> = models @@ -410,6 +404,7 @@ impl<'a> ColorPicker<'a> { value: value.reborrow(), mode: mode.as_mut().map(|held| held.reborrow()), web: web_colors.as_mut().map(|held| held.reborrow()), + shown_model: shown_model.as_mut().map(|held| held.reborrow()), constrain, sampled, focus_on_open, @@ -434,6 +429,8 @@ struct Run<'s, 'a> { value: BindMut<'s, PickedColor>, mode: Option>, web: Option>, + /// The host's model of the Compact rows; without it `Memo.model` holds it. + shown_model: Option>>, constrain: Option>, sampled: Option, focus_on_open: bool, @@ -465,11 +462,15 @@ impl<'a> Run<'_, 'a> { } let first_show = !memo.opened; - let model = memo.model.filter(|id| self.models.iter().any(|m| m.id() == *id)).or_else(|| self.models.first().map(|m| m.id())); + let held_model = self.shown_model.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied()).flatten(); + let wanted = if self.shown_model.is_some() { held_model } else { memo.model }; + let model = wanted.filter(|id| self.models.iter().any(|m| m.id() == *id)).or_else(|| self.models.first().map(|m| m.id())); { let memo = body.memory::(); memo.mode = mode; - memo.model = model; + if self.shown_model.is_none() { + memo.model = model; + } memo.opened = true; } let focus_hex = self.full && self.focus_on_open && first_show && body.resolved.enabled; @@ -510,8 +511,14 @@ impl<'a> Run<'_, 'a> { } } } - if let Some(model) = got.model_pick { - body.memory::().model = Some(model); + if let Some(next) = got.model_pick { + match self.shown_model.as_mut() { + Some(held) => { + let event = EditEvent::set(Mixed::Same(model), Some(next), Arc::from("Color model"), None); + let _ = held.write(&mut *body, &event); + } + None => body.memory::().model = Some(next), + } } (std::mem::take(&mut self.events), got.screen_pick) } diff --git a/crates/color-ui/src/ui/picker/stories.rs b/crates/color-ui/src/ui/picker/stories.rs index 9169d119c..8da0cabc6 100644 --- a/crates/color-ui/src/ui/picker/stories.rs +++ b/crates/color-ui/src/ui/picker/stories.rs @@ -3,13 +3,55 @@ use craft_theme::{Channel, ColorModel, DefaultOn, HsbModel, LabModel, MAX_CHANNELS, ModelValues, OklchModel, RgbModel, Srgba}; use craft_ui::contract::{Bind, Props as _, Show as _}; +use craft_ui::dialog::stories::hosted; +use craft_ui::runtime::env::Label; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use super::channel::{ChannelRow, ChannelRule, TrackRamp}; use super::screen_pick::ScreenPickButton; use super::{ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorWarning, ColorWarningChip, PickedColor}; -use crate::ui::AreaMode; +use crate::ui::{AreaMode, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerTab}; + +/// A colour of full brightness and saturation at `hue` (0 to 1). +fn hue_color(hue: f32) -> Srgba { + let channel = |n: f32| (((hue * 6.0 + n) % 6.0 - 3.0).abs() - 1.0).clamp(0.0, 1.0); + Srgba::rgb(channel(5.0), channel(3.0), channel(1.0)) +} + +/// The Standard tab's honeycomb of 19 hues and its row of greys. +fn standard_colors() -> (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>) { + let cells = (0..19).map(|i| (Label::from(format!("Color {}", i + 1)), hue_color(i as f32 / 19.0))).collect(); + let greys = (0..8) + .map(|i| { + let level = i as f32 / 7.0; + (Label::from(format!("Gray {}", i + 1)), Srgba::rgb(level, level, level)) + }) + .collect(); + (cells, greys) +} + +/// The tabbed dialog on the story's dialog host, opened from a button, on `tab`. +fn tabbed(ui: &mut Ui, data: &mut StoryData, tab: ColorPickerTab) -> StoryOutput { + hosted(ui, data, (), || { + let (cells, greys) = standard_colors(); + ColorPickerDialog::new("story", "Colors", Srgba::rgb(0.2, 0.5, 0.8)) + .layout(ColorPickerDialogLayout::Tabbed) + .standard(cells, greys) + .tab(tab) + .web_colors_remembered(false) + }) +} + +#[story(ColorPickerDialog, covers = [], drive = Drive::Never)] +fn color_picker_dialog_tabbed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + tabbed(ui, data, ColorPickerTab::Standard) +} + +#[story(ColorPickerDialog, covers = [], drive = Drive::Never)] +fn color_picker_dialog_tabbed_custom(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + tabbed(ui, data, ColorPickerTab::Custom) +} /// A naive CMYK in percent, without a working space: a host's model for the stories. A real host converts through its /// CMYK profile. diff --git a/crates/color-ui/src/ui/picker_dialog.rs b/crates/color-ui/src/ui/picker_dialog.rs index 56c8b545b..5a3189854 100644 --- a/crates/color-ui/src/ui/picker_dialog.rs +++ b/crates/color-ui/src/ui/picker_dialog.rs @@ -9,23 +9,27 @@ //! } //! ``` -use craft_behavior::Mixed; +use craft_behavior::{Mixed, Selection, SelectionChange, keyed}; use craft_cms::convert::CmykConverter; use craft_host::Host; use craft_host::target::Caps; use craft_settings::Remembered; use craft_theme::{ColorModel, Srgba, builtin_models}; -use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _}; +use craft_ui::choice::{SwatchArrangement, SwatchTable}; +use craft_ui::contract::{Bind, CanvasGesture, CollectionEvent, Props as _, Sampler as _, ShowCollection as _, ShowContainer as _}; use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field}; use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter}; +use craft_ui::layout_components::Stack; use craft_ui::runtime::env::{Env, Label}; use craft_ui::runtime::focus::Initial; use craft_ui::runtime::overlay::CloseReason; use craft_ui::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer}; use craft_ui::runtime::words::CommonWords; use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::tabs::{Tab, TabKind, TabStrip}; use egui::{Context, Id, Ui}; use serde::{Deserialize, Serialize}; +use std::borrow::Cow; use std::sync::Arc; use super::{ColorPicker, ColorPickerLayout, ColorWarning, PickedColor, ScreenPickGesture}; @@ -43,6 +47,10 @@ craft_ui::words! { add_to_swatches: "colorPickerDialog.addToSwatches" = "Add to Swatches"; out_of_gamut: "colorPickerDialog.outOfGamut" = "Out of gamut for printing: click for the nearest printable color"; not_web_color: "colorPickerDialog.notWebColor" = "Not a web color: click for the nearest web color"; + standard_tab: "colorPickerDialog.standardTab" = "Standard"; + custom_tab: "colorPickerDialog.customTab" = "Custom"; + standard_colors: "colorPickerDialog.standardColors" = "Standard colors"; + greys: "colorPickerDialog.greys" = "Shades of gray"; } } @@ -87,7 +95,7 @@ pub enum ColorPickerDialogLayout { } /// The tab a tabbed [`ColorPickerDialog`] shows. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPickerTab { @@ -156,11 +164,94 @@ pub struct ColorPickerDialog { host: Option>, started: bool, open: bool, - #[allow(dead_code)] // P3(dialogs-w2): dg.F6 layout: ColorPickerDialogLayout, - #[allow(dead_code)] // P3(dialogs-w2): dg.F6 + /// The Standard tab's honeycomb cells and grey row. standard: Option<(Vec<(Label, Srgba)>, Vec<(Label, Srgba)>)>, - tab: ColorPickerTab, + /// The tab the app asked to open on; it wins over the remembered one, once. + tab: Option, +} + +/// What the tabbed body shows besides the memory and the colour it edits. +struct TabbedBody<'a> { + title: &'a Label, + words: &'a ColorPickerDialogWords, + standard: Option<&'a (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>)>, + compare: Option>, +} + +/// The selection of the entry whose colour is exactly `current`. +fn chosen(entries: &[(Label, Srgba)], current: Option) -> Selection { + current.and_then(|color| entries.iter().position(|(_, entry)| *entry == color)).map_or_else(Selection::default, Selection::single) +} + +impl TabbedBody<'_> { + /// The tab strip over the page of `memory.tab`: the honeycomb and the greys, or the compact picker with the compare + /// swatch. A pick on either page sets `held`. + fn show(&self, ui: &mut Ui, memory: &mut ColorPickerMemory, held: &mut Mixed) { + let words = self.words; + Stack::new().show(ui, |ui, _| { + let tabs = [(ColorPickerTab::Standard, words.standard_tab.clone()), (ColorPickerTab::Custom, words.custom_tab.clone())]; + let source = keyed(&tabs[..], |tab: &(ColorPickerTab, Label)| tab.0).with_text(|tab| Cow::Borrowed(tab.1.as_str())); + let out = TabStrip::new(self.title.clone()).kind(TabKind::Text).shown(memory.tab).natural_height(true).show_items( + ui, + &source, + &mut |key, _| Tab::new(tabs.iter().find(|tab| tab.0 == *key).map_or_else(Label::default, |tab| tab.1.clone())), + ); + for event in out.response.events { + if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event + && let Some(picked) = keys.last() + { + memory.tab = *picked; + } + } + match memory.tab { + ColorPickerTab::Standard => self.standard_page(ui, held), + ColorPickerTab::Custom => self.custom_page(ui, memory, held), + } + }); + } + + /// The honeycomb over the row of greys; the selection follows the colour by exact match. + fn standard_page(&self, ui: &mut Ui, held: &mut Mixed) { + let (cells, greys) = self.standard.map_or((&[][..], &[][..]), |(cells, greys)| (cells.as_slice(), greys.as_slice())); + let current = held.same().map(|picked| picked.color); + let mut pick = None; + Stack::new().show(ui, |ui, _| { + let honeycomb = SwatchTable::new(self.words.standard_colors.clone(), cells) + .arrangement(SwatchArrangement::Honeycomb) + .tips(true) + .selection(Bind::given(chosen(cells, current))) + .show_all(ui); + if let Some(at) = honeycomb.selected { + pick = cells.get(at).map(|(_, color)| *color); + } + let row = SwatchTable::new(self.words.greys.clone(), greys) + .per_row(greys.len().max(1)) + .tips(true) + .selection(Bind::given(chosen(greys, current))) + .show_all(ui); + if let Some(at) = row.selected { + pick = greys.get(at).map(|(_, color)| *color); + } + }); + if let Some(color) = pick { + *held = Mixed::Same(PickedColor::rgb(color)); + } + } + + /// The compact picker over the colour, the compare swatch beside its area; the model switch is the memory's. + fn custom_page(&self, ui: &mut Ui, memory: &mut ColorPickerMemory, held: &mut Mixed) { + let models: Vec<&dyn ColorModel> = builtin_models().into_iter().filter(|model| model.default_on().compact).collect(); + let mut model: Option<&'static str> = memory.model.as_deref().and_then(|id| models.iter().map(|known| known.id()).find(|known| *known == id)); + let mut picker = ColorPicker::new(self.title.clone(), Bind::bound_mixed(held)) + .layout(ColorPickerLayout::Compact) + .shown_model(Bind::bound(&mut model)); + if let Some(compare) = self.compare { + picker = picker.compare(compare); + } + let _ = picker.show(ui); + memory.model = model.map(str::to_owned); + } } impl ColorPickerDialog { @@ -217,7 +308,7 @@ impl ColorPickerDialog { open: true, layout: ColorPickerDialogLayout::default(), standard: None, - tab: ColorPickerTab::default(), + tab: None, } } @@ -238,7 +329,7 @@ impl ColorPickerDialog { /// Sets the tab a tabbed dialog shows. #[must_use] pub fn tab(mut self, t: ColorPickerTab) -> ColorPickerDialog { - self.tab = t; + self.tab = Some(t); self } @@ -396,7 +487,11 @@ impl ColorPickerDialog { { self.memory = memory; } + if let Some(tab) = self.tab.take() { + self.memory.tab = tab; + } if self.memory.web_colors + && self.layout == ColorPickerDialogLayout::Full && let Some(opening) = self.opening { let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]); @@ -407,7 +502,7 @@ impl ColorPickerDialog { /// Files or withdraws the canvas eyedropper request as the dialog gains or loses the top. fn follow_top(&mut self, top: bool) { - let sampling = self.canvas_samples && top; + let sampling = self.canvas_samples && top && self.layout == ColorPickerDialogLayout::Full; if sampling && !self.sampling { self.requests.request_eyedropper(EyedropperRequest::new(self.key.clone())); } else if !sampling && self.sampling { @@ -439,16 +534,11 @@ impl StackDialog for ColorPickerDialog { self.instance } - /// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode` and `webColors`. + /// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `tab` and `model`. fn json_fields(&self) -> Option { let mut fields = serde_fields(&self.memory)?; let color = self.current.map_or(serde_json::Value::Null, |picked| picked.color.to_hex().into()); - let tab = serde_json::to_value(self.tab).ok()?; - let model = self.current.and_then(|picked| picked.model).map_or(serde_json::Value::Null, |values| values.model.into()); - let object = fields.as_object_mut()?; - object.insert("color".to_owned(), color); - object.insert("tab".to_owned(), tab); - object.insert("model".to_owned(), model); + fields.as_object_mut()?.insert("color".to_owned(), color); Some(fields) } @@ -501,14 +591,14 @@ impl StackDialog for ColorPickerDialog { let footer = ResetFooter::new(ui, None, true); let changed = self.current != self.opening; let mut buttons = footer.buttons(FooterButton::new(common.ok.clone(), DialogRole::Accept).enabled(self.current.is_some()), changed).to_vec(); - if self.add_to_swatches { + if self.add_to_swatches && self.layout == ColorPickerDialogLayout::Full { buttons.push(FooterButton::new(words.add_to_swatches.clone(), DialogRole::Other).stays_open(true)); } let arm = self.sampling.then_some(self.canvas).flatten(); let keep_open = self.canvas; - let screen = self.eyedropper && env.view().shell().caps.contains(Caps::SCREEN_CAPTURE); - let Self { current, opening, compare, memory, screen_busy, sample, pending_screen, open, .. } = self; + let screen = self.eyedropper && self.layout == ColorPickerDialogLayout::Full && env.view().shell().caps.contains(Caps::SCREEN_CAPTURE); + let Self { current, opening, compare, memory, screen_busy, sample, pending_screen, open, layout, standard, .. } = self; let mut held: Mixed = current.map_or(Mixed::Mixed, Mixed::Same); let (sampled, busy, compare_with) = (sample.take(), *screen_busy, compare.then(|| opening.map_or(Mixed::Mixed, Mixed::Same))); let color = current.map(|current| current.color); @@ -527,6 +617,11 @@ impl StackDialog for ColorPickerDialog { if let Some(canvas) = arm { cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY); } + if *layout == ColorPickerDialogLayout::Tabbed { + let body = TabbedBody { title: &title, words: &words, standard: standard.as_ref(), compare: compare_with }; + body.show(ui, &mut *memory, &mut held); + return; + } let mut models: Vec<&dyn ColorModel> = builtin_models().into_iter().filter(|model| model.default_on().full).collect(); models.push(&cmyk); let mut warnings = Vec::new(); diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 019f1b7d8..aa38193be 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -4,11 +4,14 @@ use std::cell::RefCell; use std::rc::Rc; use craft_behavior::Mixed; -use craft_color_ui::ui::{ColorPicker, ColorPickerDialog, ColorPickerLayout, ColorReadout, PickedColor}; +use craft_color_ui::ui::{ + ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, ColorReadout, PickedColor, +}; use craft_host::{AppInfo, Host}; use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Rgba, Srgba}; use craft_ui::contract::{Bind, Role}; -use craft_ui::dialog::{DialogHost, DialogResult, dialog_id}; +use craft_ui::dialog::{DialogHost, DialogResult, StackDialog, dialog_id}; +use craft_ui::runtime::env::Label; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers, vec2}; @@ -161,3 +164,65 @@ fn the_full_pickers_channel_rows_show_letters_and_align_their_fields() { assert!(degrees.rect.min.x >= hue.rect.max.x - 0.5, "the unit sits after the field, outside it: {:?} against {:?}", degrees.rect, hue.rect); assert!(widest < starts[1] - starts[0], "the fields are short, not the width of the room"); } + +/// A field of the open dialog as automation reads it. +fn dialog_field(dialogs: &Rc>, name: &str) -> Option { + dialogs.borrow().get::().and_then(|dialog| dialog.json_fields()).and_then(|fields| fields.get(name).cloned()) +} + +/// The current colour of the open dialog as `#rrggbb`. +fn dialog_color(dialogs: &Rc>) -> Option { + dialogs.borrow().get::().and_then(|dialog| dialog.current()).map(|picked| picked.color.to_hex()) +} + +/// The tabbed dialog opens on the tab it was given; a hex typed on Custom and a honeycomb cell picked on Standard both +/// reach the answer, and the tab is a field automation reads and sets. +#[trial] +fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() { + let dialogs = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&dialogs); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(vec2(900.0, 700.0)); + fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "picker-test", name: "Picker test", version: "0" }).build())); + let ctx = fixture.ctx().clone(); + let id = dialog_id(("color-picker", "fill")); + let colour = |hex: &str| Srgba::from_hex(hex).expect("a colour"); + let cells: Vec<(Label, Srgba)> = + ["#ff0000", "#00ff00", "#0000ff", "#ffff00"].iter().enumerate().map(|(at, hex)| (Label::from(format!("Standard {at}")), colour(hex))).collect(); + let greys = vec![(Label::from("Gray 1"), colour("#808080"))]; + + dialogs.borrow_mut().open( + ColorPickerDialog::new("fill", "Fill", colour("#123456")) + .layout(ColorPickerDialogLayout::Tabbed) + .standard(cells, greys) + .tab(ColorPickerTab::Custom) + .web_colors_remembered(false), + ); + fixture.idle(6); + assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom")), "the dialog opens on the tab it was given"); + assert!(fixture.by_label("Hex color").is_some(), "the Custom page shows the compact picker"); + assert!(fixture.by_label("Standard 0").is_none(), "and not the honeycomb"); + assert_eq!(dialog_field(&dialogs, "model"), Some(serde_json::Value::Null), "no model is picked yet"); + assert!(fixture.by_label("Red").is_none(), "the first model (HSB) shows no red channel"); + let set = dialogs.borrow_mut().set_json_field(&ctx, id, "model", serde_json::json!(RgbModel.id())); + assert_eq!(set, Ok(()), "the model of the Custom page is a field"); + fixture.idle(6); + assert_eq!(dialog_field(&dialogs, "model"), Some(serde_json::json!(RgbModel.id())), "the field names the model shown"); + assert!(fixture.by_label("Red").is_some(), "and the compact rows show that model's channels"); + + type_into(&mut fixture, "Hex color", "336699"); + assert_eq!(dialog_color(&dialogs).as_deref(), Some("#336699"), "a hex typed on Custom is the colour"); + + let set = dialogs.borrow_mut().set_json_field(&ctx, id, "tab", serde_json::json!("standard")); + assert_eq!(set, Ok(()), "the tab is a field of the dialog"); + fixture.idle(6); + assert!(fixture.by_label("Hex color").is_none(), "Standard shows no hex field"); + let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells"); + fixture.click(&cell); + fixture.idle(4); + assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour"); + + assert!(dialogs.borrow_mut().confirm::(&ctx), "OK answers"); + let answered = dialogs.borrow_mut().take::().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex()); + assert_eq!(answered.as_deref(), Some("#0000ff")); +} diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index febb2e78d..5edddd721 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -523,19 +523,33 @@ impl<'a> Draw<'a> { /// translucent, or for `None` (no colour of its own, or a mixed one) the empty well, `surface.sunken` with a /// `text.muted` dash. `Swatch` and swatch icons paint their wells with it and add their own edges. pub fn swatch_well(&self, well: Rect, radius: CornerRadius, color: Option) { - let shape = PaintShape::Rect(well, radius); + self.well_of(&PaintShape::Rect(well, radius), well, color, |draw| draw.checker(&super::Checker::new(), well, radius)); + } + + /// [`Self::swatch_well`] over the convex polygon `corners` (a honeycomb cell): the same parts, the checkerboard and + /// the dash cut to the polygon. + pub fn swatch_polygon_well(&self, corners: &[Pos2], color: Option) { + let bounds = Rect::from_points(corners); + self.well_of(&PaintShape::Polygon(corners.to_vec()), bounds, color, |draw| { + data_polygon_checker(draw.painter, draw.env.tokens, draw.data, &super::Checker::new(), corners, bounds.min); + }); + } + + /// The parts of a swatch well in `shape` within `bounds`: the colour over the checkerboard `checker` paints where it + /// is translucent, or the empty well with its dash. + fn well_of(&self, shape: &PaintShape, bounds: Rect, color: Option, checker: impl FnOnce(&Self)) { match color { None => { let colors = &self.env.tokens.color; - self.paint(&shape, Some(crate::style::rgba_color(colors.surface.sunken)), None); + self.paint(shape, Some(crate::style::rgba_color(colors.surface.sunken)), None); let dash = Stroke::new(self.width(StrokeWidth::Medium), crate::style::rgba_color(colors.text.muted)); - self.paint(&super::glyph::dash(well), None, Some(dash)); + self.paint(&super::glyph::dash(bounds), None, Some(dash)); } Some(color) => { if color.a < 1.0 { - self.checker(&super::Checker::new(), well, radius); + checker(self); } - self.data_fill(&shape, DataColor::new(Color32::from(color))); + self.data_fill(shape, DataColor::new(Color32::from(color))); } } } @@ -649,6 +663,18 @@ pub(super) fn data_checker(painter: &Painter, tokens: &UiTokens, mode: DataMode, } } +/// The checkerboard over the convex polygon `corners`, as [`data_checker`] paints a rect: for an inactive `mode` the +/// polygon in the theme's disabled fill. +fn data_polygon_checker(painter: &Painter, tokens: &UiTokens, mode: DataMode, checker: &super::Checker, corners: &[Pos2], origin: Pos2) { + if mode == DataMode::Inactive { + painter.add(Shape::convex_polygon(corners.to_vec(), mode.color(tokens, Color32::TRANSPARENT), Stroke::NONE)); + } else { + let mut shape = checker.polygon_shape(painter.ctx(), tokens, corners, origin); + mode.shape(tokens, &mut shape); + painter.add(shape); + } +} + /// `painter` with its opacity multiplied by `share`: the one fade `Draw::faded` and `ContentPainterCx::faded` share. pub(super) fn faded_painter(painter: &Painter, share: f32) -> Painter { let mut painter = painter.clone(); diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index e5cd58ead..f53b7b778 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -94,13 +94,30 @@ impl Checker { self } - /// The checkerboard over `area` as one textured shape: square cells of the light and dark colours, a light cell - /// with its top-left corner at `origin`. A painter's clip cuts it. - pub fn shape(&self, ctx: &Context, tokens: &UiTokens, area: CheckerArea, origin: Pos2) -> Shape { + /// The texture of the two colours and the side of a cell. + fn texture(&self, ctx: &Context, tokens: &UiTokens) -> (TextureId, f32) { let side = self.size.unwrap_or(tokens.size.checker).max(f32::EPSILON); let light = self.light.map_or_else(|| rgba_color(tokens.color.overlay.checker_light), |color| color.0); let dark = self.dark.map_or_else(|| rgba_color(tokens.color.overlay.checker_dark), |color| color.0); - let texture = checker_texture(ctx, light, dark); + (checker_texture(ctx, light, dark), side) + } + + /// The checkerboard over the convex polygon `corners` as one textured mesh, a light cell with its top-left corner at + /// `origin`: the cells follow the polygon's edge, which a rect's clip cannot. + pub fn polygon_shape(&self, ctx: &Context, tokens: &UiTokens, corners: &[Pos2], origin: Pos2) -> Shape { + let (texture, side) = self.texture(ctx, tokens); + let mut mesh = fill_polygon(corners, UNTINTED, 0.0); + mesh.texture_id = texture; + for vertex in &mut mesh.vertices { + vertex.uv = ((vertex.pos - origin) / (2.0 * side)).to_pos2(); + } + Shape::mesh(mesh) + } + + /// The checkerboard over `area` as one textured shape: square cells of the light and dark colours, a light cell + /// with its top-left corner at `origin`. A painter's clip cuts it. + pub fn shape(&self, ctx: &Context, tokens: &UiTokens, area: CheckerArea, origin: Pos2) -> Shape { + let (texture, side) = self.texture(ctx, tokens); // One texel per cell; the texture repeats every two cells. let uv = |p: Pos2| ((p - origin) / (2.0 * side)).to_pos2(); match area { diff --git a/crates/ui-widgets/src/choice/swatch.rs b/crates/ui-widgets/src/choice/swatch.rs index e6634442c..58cfa0ef0 100644 --- a/crates/ui-widgets/src/choice/swatch.rs +++ b/crates/ui-widgets/src/choice/swatch.rs @@ -4,19 +4,23 @@ use super::radio::RadioKind; use super::words::ChoiceWords; use crate::contract::{ - Access, Activation, Common, Component, Cx, DisabledLook, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, Props as _, Role, - Sizing, Styled as _, WordSetCx as _, + Access, Activation, Common, Component, Cx, DisabledLook, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, + Role, Sizing, Styled as _, WordSetCx as _, }; +use crate::runtime::focus::FocusShape; use crate::primitives::{ContentPainterCx, Draw, PaintShape, StrokeWidth}; use crate::runtime::requests::ColorRequest; use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, State, StateMix, StateSet, StyleColor, StyleCx, UiTokens, resolve_style}; -use craft_behavior::{Metrics, Mixed, Sense, Value}; +use craft_behavior::{HitShape, Metrics, Mixed, PartKey, Sense, Value}; use craft_theme::{Rgba, Srgba, Stateful, States, over}; -use egui::{Color32, CornerRadius, Rect, Response, Vec2}; +use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2, pos2}; #[cfg(feature = "testing")] mod stories; +/// The face of a hexagon swatch: the part whose outline the focus ring follows. +const FACE: PartKey = PartKey::new("face"); + /// Opacity of the black or white ring that stands out from a well's colour. const INNER_EDGE_ALPHA: u8 = 0x80; @@ -203,7 +207,7 @@ impl Swatch { impl Component for Swatch { const ROLE: Role = Role::COLOR_WELL; - const PARTS: bool = false; + const PARTS: bool = true; const OVERLAYS: bool = false; const ALT_ROLES: &'static [Role] = &[Role::RADIO_BUTTON, Role::LIST_BOX_OPTION]; const DISABLED: DisabledLook = DisabledLook::Faded; @@ -277,8 +281,16 @@ impl Component for Swatch { } } + /// A hexagon swatch declares its face as the focus stop, so the ring follows the hexagon and not its rect. + fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { + if self.shape == SwatchShape::Hexagon { + let corners = hexagon(rect); + cx.part(FACE, HitShape::Polygon(corners.clone())).focusable().focus_shape(FocusShape::Polygon(corners)); + } + } + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { - paint_face(&ui.draw(), cx.rect, cx.style, cx.state(), self.color, self.marked); + paint_face(&ui.draw(), cx.rect, cx.style, cx.state(), self.color, self.marked, self.shape); } fn finish(self, cx: Cx<'_, Self>) -> SwatchOutput { @@ -290,15 +302,37 @@ impl Component for Swatch { /// The one swatch face painter: the well of `color` in `well` (a checkerboard behind a translucent colour, the dash /// of a mixed one), then the outline ring, the mark when `marked`, and the selection ring, in `state`. -fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed, marked: bool) { - let shape = PaintShape::Rect(well, style.radius); - draw.swatch_well(well, style.radius, color.same().copied()); - draw.stroke(&shape, StrokeWidth::Thin, state.resolve(&style.edge)); +fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed, marked: bool, shape: SwatchShape) { + let outline = |rect: Rect| match shape { + SwatchShape::Square => PaintShape::Rect(rect, style.radius), + SwatchShape::Hexagon => PaintShape::Polygon(hexagon(rect)), + }; + let edge = outline(well); + match shape { + SwatchShape::Square => draw.swatch_well(well, style.radius, color.same().copied()), + SwatchShape::Hexagon => draw.swatch_polygon_well(&hexagon(well), color.same().copied()), + } + draw.stroke(&edge, StrokeWidth::Thin, state.resolve(&style.edge)); if marked { - let inside = PaintShape::Rect(well.shrink(draw.width(StrokeWidth::Thin)), style.radius); + let inside = outline(well.shrink(draw.width(StrokeWidth::Thin))); draw.stroke(&inside, StrokeWidth::Thin, style.mark); } - draw.stroke(&shape, StrokeWidth::Thick, state.resolve(&style.ring)); + draw.stroke(&edge, StrokeWidth::Thick, state.resolve(&style.ring)); +} + +/// The corners of the pointy-top hexagon inscribed in `rect`: the vertices at the middle of the top and bottom edges, +/// the vertical sides spanning the middle half of the height. The honeycomb layout hit-tests against the same points. +pub(super) fn hexagon(rect: Rect) -> Vec { + let quarter = rect.height() / 4.0; + let middle = rect.center().x; + vec![ + pos2(middle, rect.top()), + pos2(rect.right(), rect.top() + quarter), + pos2(rect.right(), rect.bottom() - quarter), + pos2(middle, rect.bottom()), + pos2(rect.left(), rect.bottom() - quarter), + pos2(rect.left(), rect.top() + quarter), + ] } /// The face of a swatch outside a `Swatch`: a preset thumbnail of a colour (`PresetBrowser::thumb`). It paints @@ -330,6 +364,6 @@ impl SwatchFace { let style = resolve_style(&scope, key, cx.painter.ctx(), Swatch::<()>::style); let (flags, on) = if self.selected { (Flags::SELECTED, 1.0) } else { (Flags::empty(), 0.0) }; let state = StateSet::new(State::Rest, flags, StateMix::new(0.0, 0.0, on)); - cx.with_draw(|draw| paint_face(draw, rect, &style, &state, self.color, false)); + cx.with_draw(|draw| paint_face(draw, rect, &style, &state, self.color, false, SwatchShape::Square)); } } diff --git a/crates/ui-widgets/src/choice/swatch/stories.rs b/crates/ui-widgets/src/choice/swatch/stories.rs index 52b79df2d..ddc509de7 100644 --- a/crates/ui-widgets/src/choice/swatch/stories.rs +++ b/crates/ui-widgets/src/choice/swatch/stories.rs @@ -1,6 +1,6 @@ //! Stories of `Swatch`. -use super::Swatch; +use super::{Swatch, SwatchShape}; use crate::choice::RadioGroup; use crate::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _}; use crate::layout_components::{Row, Stack}; @@ -75,6 +75,12 @@ fn swatch_table_cells(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { StoryOutput::default() } +/// A hexagon well, the cell of a honeycomb. +#[story(Swatch, covers = [], drive = Drive::Never)] +fn swatch_hexagon(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + Swatch::new("Hexagon", BLUE).shape(SwatchShape::Hexagon).show(ui).into() +} + /// A well and a line that counts its clicks. #[story(Swatch, covers = [], drive = Drive::Never)] fn swatch_clicks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { diff --git a/crates/ui-widgets/src/choice/swatch_table.rs b/crates/ui-widgets/src/choice/swatch_table.rs index 265251102..fd1f84eeb 100644 --- a/crates/ui-widgets/src/choice/swatch_table.rs +++ b/crates/ui-widgets/src/choice/swatch_table.rs @@ -1,6 +1,7 @@ //! `SwatchTable`: a table of touching cells selected by index, for a colour table whose entries may repeat a colour. -use super::{Swatch, SwatchMetrics}; +use super::swatch::hexagon; +use super::{Swatch, SwatchMetrics, SwatchShape}; use crate::contract::{ ActivateOn, Bind, BindMut, Collection, CollectionEvent, CollectionProps, Common, Component, ContainerProps, Cx, NoValue, Outcome, Props, Role, SelectMode, ShowCollection as _, Sizing, @@ -8,9 +9,9 @@ use crate::contract::{ use crate::list::RowTest; use crate::runtime::env::Label; use crate::style::{ComponentStyle, StyleCx}; -use craft_behavior::{DisplayOrder, ItemSource, Metrics, Selection, TileLayout}; +use craft_behavior::{DisplayOrder, ItemLayout, ItemSource, Metrics, NavShape, ScrollPos, Selection, TileLayout}; use craft_theme::Srgba; -use egui::{Response, Ui, Vec2}; +use egui::{Pos2, Rect, Response, Ui, Vec2}; #[cfg(feature = "testing")] mod stories; @@ -80,6 +81,221 @@ pub enum SwatchArrangement { Honeycomb, } +/// The cells of a honeycomb: pointy-top hexagons, each row offset by half a cell from its neighbours and stacked at +/// three quarters of the cell height, so every cell touches its six neighbours. The rows grow from `n` cells to `2n - 1` +/// and shrink back, `n` being the smallest side whose full hexagon (`3n(n - 1) + 1` cells) holds the count. A row sits +/// where the full hexagon's row of that index sits, so a count short of a full hexagon leaves the last row short and +/// continuing the lattice from its left, never shifted by a whole cell. +/// +/// Arrows: Left and Right step to the neighbour in the row. Down from column `c` goes to column `c` of the next row +/// while it is longer and to column `c - 1` (at least 0) while it is shorter; Up goes the same way, to `c - 1` while the +/// row above is shorter. Both are the lower-left neighbour of the two a hexagon has, as [`column_shift`] says. +/// +/// [`column_shift`]: ItemLayout::column_shift +#[derive(Clone, Debug)] +pub struct HoneycombLayout { + tile: Vec2, + /// The cells of each row. + lens: Vec, + /// The index of each row's first cell. + starts: Vec, + /// The side of the full hexagon: its longest row has `2 * side - 1` cells. + side: usize, +} + +impl HoneycombLayout { + /// `count` cells of width `cell`. + fn new(count: usize, cell: f32) -> Self { + let side = (1usize..).find(|&n| 3 * n * (n - 1) + 1 >= count).unwrap_or(1); + let mut lens = Vec::new(); + let mut left = count; + for row in 0..2 * side - 1 { + let len = (side + row.min(2 * side - 2 - row)).min(left); + if len == 0 { + break; + } + lens.push(len); + left -= len; + } + let starts = lens + .iter() + .scan(0, |start, len| { + let first = *start; + *start += len; + Some(first) + }) + .collect(); + HoneycombLayout { tile: Vec2::new(cell, cell * 2.0 / 3.0_f32.sqrt()), lens, starts, side } + } + + /// The cells of the longest row of the full hexagon: the width of the table. + fn columns(&self) -> usize { + 2 * self.side - 1 + } + + /// The cells of `row` in the full hexagon. + fn full_len(&self, row: usize) -> usize { + self.side + row.min((2 * self.side - 2).saturating_sub(row)) + } + + /// The space before `row`, in half cells. + fn lead(&self, row: usize) -> usize { + self.columns() - self.full_len(row) + } + + /// The space before `row`'s first cell. + fn left(&self, row: usize) -> f32 { + self.lead(row) as f32 * self.tile.x / 2.0 + } + + /// The distance between the tops of two rows. + fn pitch(&self) -> f32 { + self.tile.y * 0.75 + } + + /// The cell `at` in content space. + fn cell_rect(&self, at: usize) -> Option { + let row = self.starts.partition_point(|&start| start <= at).checked_sub(1)?; + let column = at - self.starts[row]; + if column >= self.lens[row] { + return None; + } + let left = self.left(row) + column as f32 * self.tile.x; + Some(Rect::from_min_size(Pos2::new(left, row as f32 * self.pitch()), self.tile)) + } +} + +/// Whether `point` is inside the convex `polygon`, its edge included. +fn inside(polygon: &[Pos2], point: Pos2) -> bool { + let mut side = 0.0_f32; + for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)) { + let cross = (b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x); + if cross == 0.0 { + continue; + } + if side == 0.0 { + side = cross.signum(); + } else if side != cross.signum() { + return false; + } + } + true +} + +impl ItemLayout for HoneycombLayout { + fn content_size(&self) -> ScrollPos { + let height = if self.lens.is_empty() { 0.0 } else { (self.lens.len() - 1) as f64 * f64::from(self.pitch()) + f64::from(self.tile.y) }; + ScrollPos { x: self.columns() as f64 * f64::from(self.tile.x), y: height } + } + + fn visible(&self, offset: ScrollPos, view: Vec2, out: &mut Vec) { + for (row, (start, len)) in self.starts.iter().zip(&self.lens).enumerate() { + let top = f64::from(row as f32 * self.pitch()); + if top + f64::from(self.tile.y) > offset.y && top < offset.y + f64::from(view.y) { + out.extend(*start..start + len); + } + } + } + + fn rect(&self, at: usize, offset: ScrollPos) -> Rect { + let rect = self.cell_rect(at).unwrap_or(Rect::ZERO); + rect.translate(Vec2::new(-(offset.x as f32), -(offset.y as f32))) + } + + /// The cell whose hexagon holds the point; the rows overlap in height, so the row of the point and the one above + /// are tried. + fn hit(&self, point: Pos2, offset: ScrollPos) -> Option { + let at = Pos2::new(point.x + offset.x as f32, point.y + offset.y as f32); + if at.x < 0.0 || at.y < 0.0 { + return None; + } + let row = ((at.y / self.pitch()) as usize).min(self.lens.len().checked_sub(1)?); + [row, row.saturating_sub(1)].into_iter().find_map(|row| { + let left = self.left(row); + let column = ((at.x - left) / self.tile.x).floor(); + if column < 0.0 || column as usize >= self.lens[row] { + return None; + } + let index = self.starts[row] + column as usize; + self.cell_rect(index).filter(|rect| inside(&hexagon(*rect), at)).map(|_| index) + }) + } + + fn nav(&self) -> NavShape { + NavShape::RaggedGrid + } + + fn row_len(&self, row: usize) -> Option { + self.lens.get(row).copied() + } + + /// Half a cell of offset per step between rows, rounded down: a row that starts later (shorter) puts the lower-left + /// neighbour one column earlier, a row that starts earlier (longer) keeps the column. + fn column_shift(&self, from: usize, to: usize) -> isize { + (self.lead(from) as isize - self.lead(to) as isize).div_euclid(2) + } +} + +/// The geometry of a [`SwatchTable`], by its [`SwatchArrangement`]. +#[derive(Clone, Debug)] +pub enum SwatchLayout { + /// Square cells in rows and columns. + Grid(TileLayout), + /// Touching hexagon cells. + Honeycomb(HoneycombLayout), +} + +impl ItemLayout for SwatchLayout { + fn content_size(&self) -> ScrollPos { + match self { + SwatchLayout::Grid(tiles) => tiles.content_size(), + SwatchLayout::Honeycomb(cells) => cells.content_size(), + } + } + + fn visible(&self, offset: ScrollPos, view: Vec2, out: &mut Vec) { + match self { + SwatchLayout::Grid(tiles) => tiles.visible(offset, view, out), + SwatchLayout::Honeycomb(cells) => cells.visible(offset, view, out), + } + } + + fn rect(&self, at: usize, offset: ScrollPos) -> Rect { + match self { + SwatchLayout::Grid(tiles) => tiles.rect(at, offset), + SwatchLayout::Honeycomb(cells) => cells.rect(at, offset), + } + } + + fn hit(&self, point: Pos2, offset: ScrollPos) -> Option { + match self { + SwatchLayout::Grid(tiles) => tiles.hit(point, offset), + SwatchLayout::Honeycomb(cells) => cells.hit(point, offset), + } + } + + fn nav(&self) -> NavShape { + match self { + SwatchLayout::Grid(tiles) => tiles.nav(), + SwatchLayout::Honeycomb(cells) => cells.nav(), + } + } + + fn row_len(&self, row: usize) -> Option { + match self { + SwatchLayout::Grid(tiles) => tiles.row_len(row), + SwatchLayout::Honeycomb(cells) => cells.row_len(row), + } + } + + fn column_shift(&self, from: usize, to: usize) -> isize { + match self { + SwatchLayout::Grid(tiles) => tiles.column_shift(from, to), + SwatchLayout::Honeycomb(cells) => cells.column_shift(from, to), + } + } +} + /// A table of touching colour cells, one per entry, wrapping to the width or to a fixed count per row. Entries are /// told apart by index, so duplicates select one cell. With [`span`](Self::span) and a count per row, the cells share /// the table's width edge to edge; [`marked`](Self::marked) cells draw the swatch mark. @@ -117,7 +333,8 @@ pub struct SwatchTable<'a> { /// Whether the cells are wells at the control height, as a palette's swatches are, instead of small touching cells. #[prop] wells: bool, - /// How the cells lie: a square grid, or touching hexagons. + /// How the cells lie: a square grid, or touching hexagons. A honeycomb ignores `per_row`, `span` and `wells`: its + /// rows follow the count of entries and its cells are `size.icon.md` wide. #[prop] arrangement: SwatchArrangement, } @@ -157,10 +374,11 @@ impl<'a> SwatchTable<'a> { /// Shows the table. pub fn show_all(mut self, ui: &mut Ui) -> SwatchTableOutput { let (swatches, tips, wells) = (self.swatches, self.tips, self.wells); + let shape = if self.arrangement == SwatchArrangement::Honeycomb { SwatchShape::Hexagon } else { SwatchShape::Square }; let marked = self.marked.take(); self.show_items(ui, &SwatchRows::new(swatches), &mut |key, _| { let (name, color) = &swatches[*key]; - let cell = Swatch::new(name.clone(), *color).cell(); + let cell = Swatch::new(name.clone(), *color).cell().shape(shape); let cell = if wells { cell.well() } else { cell }; let cell = if marked.as_ref().is_some_and(|test| test.passes(key)) { cell.marked() } else { cell }; if tips { cell.tooltip(name.clone()) } else { cell } @@ -201,7 +419,7 @@ impl Component for SwatchTable<'_> { impl Collection for SwatchTable<'_> { type Key = usize; - type ItemLayout = TileLayout; + type ItemLayout = SwatchLayout; type Selection = Selection; type Item<'r> = Swatch; type ItemEvent = std::convert::Infallible; @@ -217,15 +435,21 @@ impl Collection for SwatchTable<'_> { /// Where the table takes its width from its content it asks for every cell in one row, or its count per row: the /// room it is offered then wraps the cells, as it does where it is given the width. - fn ideal_width(&self, _item: Option, _rows: usize, cx: &StyleCx<'_>) -> f32 { + fn ideal_width(&self, _item: Option, cx: &StyleCx<'_>) -> f32 { + if self.arrangement == SwatchArrangement::Honeycomb { + return HoneycombLayout::new(self.swatches.len(), self.cell(cx)).columns() as f32 * self.cell(cx) + 0.5; + } let columns = self.per_row.map_or(self.swatches.len(), |columns| columns.max(1).min(self.swatches.len())); // Half a point over, so the division that counts the columns back never rounds below `columns`. columns as f32 * self.cell(cx) + 0.5 } - fn item_layout(&self, source: &dyn ItemSource, width: f32, cx: &StyleCx<'_>) -> TileLayout { + fn item_layout(&self, source: &dyn ItemSource, width: f32, cx: &StyleCx<'_>) -> SwatchLayout { let cell = self.cell(cx); - match self.per_row { + if self.arrangement == SwatchArrangement::Honeycomb { + return SwatchLayout::Honeycomb(HoneycombLayout::new(source.len(), cell)); + } + SwatchLayout::Grid(match self.per_row { Some(columns) => { let columns = columns.max(1); let spans = self.span && width.is_finite() && width > 0.0; @@ -233,6 +457,6 @@ impl Collection for SwatchTable<'_> { TileLayout::new(source, width, tile, 0.0).in_columns(columns) } None => TileLayout::new(source, width, Vec2::splat(cell), 0.0), - } + }) } } diff --git a/crates/ui-widgets/src/choice/swatch_table/stories.rs b/crates/ui-widgets/src/choice/swatch_table/stories.rs index 60268d74c..c7556d680 100644 --- a/crates/ui-widgets/src/choice/swatch_table/stories.rs +++ b/crates/ui-widgets/src/choice/swatch_table/stories.rs @@ -1,6 +1,6 @@ //! Stories of `SwatchTable`. -use super::{SwatchTable, SwatchTableOutput}; +use super::{SwatchArrangement, SwatchTable, SwatchTableOutput}; use crate::contract::Bind; use crate::runtime::env::Label; use crate::testing::{Drive, StoryData, StoryOutput, story}; @@ -50,6 +50,17 @@ fn swatch_table_multiple(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { with_readout(data, shown) } +/// 127 entries, the full honeycomb of side 7. +#[story(SwatchTable<'static>, covers = [], drive = Drive::Never)] +fn swatch_table_honeycomb(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let entries = table_entries().into_iter().take(127).collect::>(); + let shown = SwatchTable::new("Color Table", &entries) + .arrangement(SwatchArrangement::Honeycomb) + .selection(Bind::bound(data.value("selected", Selection::single(5usize)))) + .show_all(ui); + with_readout(data, shown) +} + #[story(SwatchTable<'static>, covers = [Empty], drive = Drive::Never)] fn swatch_table_empty(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { SwatchTable::new("Color Table", &[]).empty("No colors").show_all(ui).into() diff --git a/crates/ui-widgets/tests/it/pickers/mod.rs b/crates/ui-widgets/tests/it/pickers/mod.rs index 8b2fd8a6b..3c6bec4ed 100644 --- a/crates/ui-widgets/tests/it/pickers/mod.rs +++ b/crates/ui-widgets/tests/it/pickers/mod.rs @@ -5,4 +5,5 @@ mod date; mod select_list; mod select_steps; mod select_width; +mod swatch_table; mod tree_list; diff --git a/crates/ui-widgets/tests/it/pickers/swatch_table.rs b/crates/ui-widgets/tests/it/pickers/swatch_table.rs new file mode 100644 index 000000000..75dc4c0d2 --- /dev/null +++ b/crates/ui-widgets/tests/it/pickers/swatch_table.rs @@ -0,0 +1,86 @@ +//! A honeycomb `SwatchTable`: touching hexagon cells in rows that follow the count, picked by click and moved through by +//! the arrows. + +use std::cell::Cell; +use std::rc::Rc; + +use craft_theme::Srgba; +use craft_ui::choice::{SwatchArrangement, SwatchTable}; +use craft_ui::runtime::env::Label; +use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers, Rect, vec2}; + +/// Fifteen cells: the hexagon of side 3 (19 cells) cut short, rows of 3, 4, 5 and a short last row of 3 where the full +/// row has 4. +const CELLS: usize = 15; + +fn honeycomb(picked: Rc>>) -> Fixture { + let entries: Vec<(Label, Srgba)> = + (0..CELLS).map(|i| (Label::from(format!("Cell {i}")), Srgba::rgb(i as f32 / CELLS as f32, 0.4, 0.6))).collect(); + let mut fixture = Fixture::new(move |ui| { + let out = SwatchTable::new("Colors", &entries).arrangement(SwatchArrangement::Honeycomb).show_all(ui); + if let Some(at) = out.selected { + picked.set(Some(at)); + } + }); + fixture.room(vec2(400.0, 300.0)); + fixture.settle(); + fixture +} + +fn rects(fixture: &Fixture) -> Vec { + (0..CELLS).map(|i| fixture.by_label(&format!("Cell {i}")).expect("every entry is a cell").rect).collect() +} + +/// The entry Space selects after `key`, from the lead the last move left. +fn after(fixture: &mut Fixture, picked: &Cell>, key: Key) -> Option { + fixture.key(key, Modifiers::NONE); + fixture.settle(); + picked.set(None); + fixture.key(Key::Space, Modifiers::NONE); + fixture.settle(); + picked.get() +} + +#[trial] +fn honeycomb_cells_touch_without_overlap_and_arrows_follow_neighbours() { + let picked = Rc::new(Cell::new(None)); + let mut fixture = honeycomb(Rc::clone(&picked)); + let rects = rects(&fixture); + let width = rects[0].width(); + + let mut rows: Vec> = Vec::new(); + for (at, rect) in rects.iter().enumerate() { + match rows.last_mut() { + Some(row) if (rects[row[0]].center().y - rect.center().y).abs() < 0.5 => row.push(at), + _ => rows.push(vec![at]), + } + } + assert_eq!(rows.iter().map(Vec::len).collect::>(), [3, 4, 5, 3], "the rows follow the count: {rects:?}"); + for row in &rows { + for pair in row.windows(2) { + assert!((rects[pair[1]].min.x - rects[pair[0]].max.x).abs() < 0.5, "cells of a row touch: {:?}", rects[pair[0]]); + } + } + let first = |row: usize| rects[rows[row][0]].center().x; + assert!((first(0) - first(1) - width / 2.0).abs() < 0.5, "a longer row starts half a cell earlier: {} against {}", first(0), first(1)); + assert!((first(1) - first(2) - width / 2.0).abs() < 0.5, "the middle row starts half a cell earlier again"); + assert!((first(3) - first(2) - width / 2.0).abs() < 0.5, "the short last row continues the lattice, half a cell after the row above"); + for (at, rect) in rects.iter().enumerate() { + let distances: Vec = rects.iter().enumerate().filter(|(other, _)| *other != at).map(|(_, o)| (o.center() - rect.center()).length()).collect(); + let nearest = distances.iter().copied().fold(f32::MAX, f32::min); + assert!(distances.iter().all(|d| *d >= width - 0.5), "no two cells overlap: cell {at}"); + assert!((nearest - width).abs() < 0.5, "every cell touches a neighbour: cell {at} is {nearest} from the nearest"); + } + + let target = fixture.by_label("Cell 9").expect("a cell"); + fixture.click(&target); + assert_eq!(picked.get(), Some(9), "a click picks the cell under the pointer"); + assert_eq!(after(&mut fixture, &picked, Key::ArrowRight), Some(10), "Right lands on the cell beside"); + assert_eq!(after(&mut fixture, &picked, Key::ArrowLeft), Some(9), "Left returns"); + assert_eq!(after(&mut fixture, &picked, Key::ArrowDown), Some(13), "Down into a shorter row goes to column c - 1"); + assert_eq!(after(&mut fixture, &picked, Key::ArrowUp), Some(8), "Up into a longer row keeps the column"); + assert_eq!(after(&mut fixture, &picked, Key::ArrowUp), Some(3), "Up into a shorter row goes to column c - 1"); + assert_eq!(after(&mut fixture, &picked, Key::ArrowUp), Some(0), "Up from the first column stays in it"); + assert_eq!(after(&mut fixture, &picked, Key::ArrowDown), Some(3), "Down from the first cell lands on the first cell of the next row"); +}