1use std::collections::{HashMap, HashSet};
19use std::fmt;
20use std::hash::Hash;
21use std::ops::Range;
22use std::rc::Rc;
23
24use iced::advanced::layout::{self, Layout};
25use iced::advanced::widget::operation;
26use iced::advanced::widget::{Operation, Tree, Widget, tree};
27use iced::advanced::{Clipboard, Shell, overlay, renderer};
28use iced::keyboard::key::Named;
29use iced::widget::{self, Space, column, container, mouse_area, responsive, row};
30use iced::{
31 Alignment, Background, Border, Color, Element, Length, Padding, Rectangle, Renderer, Size,
32 Task, Theme, Vector, mouse,
33};
34
35use crate::data::ellipsis::ellipsis;
36use crate::data::interaction::{
37 Look, RowMenu, match_count_label, pressable, ringed, row_menu, scope, search_count, search_keys,
38};
39use crate::data::rows::rows;
40use crate::forms::select::select;
41use crate::icon::{opacity, themed};
42use crate::keys::{self, Chord, Keymap};
43use crate::overlay::context_menu;
44use crate::overlay::dropdown_menu::item;
45use crate::overlay::tooltip::tooltip;
46use crate::primitives::button;
47use crate::primitives::checkbox::checkbox;
48use crate::primitives::icon_button::icon_button;
49use crate::primitives::input::{self, Shortcuts, input};
50use crate::primitives::switch::switch;
51use crate::theme::{self, Tokens, fade, mix, radius, space, text_size};
52
53pub const ROW_HEIGHT: f32 = 36.0;
55pub const NAME_WIDTH: f32 = 160.0;
57pub const MIN_NAME_WIDTH: f32 = 64.0;
59pub const MIN_VALUE_WIDTH: f32 = 88.0;
61pub const VALUE_WIDTH: f32 = 112.0;
64pub const HANDLE_WIDTH: f32 = 9.0;
66pub const RESET_WIDTH: f32 = 24.0;
68pub const DESCRIPTION_HEIGHT: f32 = 64.0;
71pub const SEARCH: widget::Id = widget::Id::new("iced-cube-property-grid-filter");
73pub const EDITOR_ID: widget::Id = widget::Id::new("iced-cube-property-grid-editor");
75
76pub const NOTHING_SELECTED: &str = "Select a property to see its description.";
78
79const MARK_WIDTH: f32 = 14.0;
81const MARK_SIZE: f32 = 6.0;
82const SWATCH_SIZE: f32 = 16.0;
83const ICON_SIZE: f32 = 16.0;
84const RESET_ICON_SIZE: f32 = 14.0;
85
86#[derive(Debug, Clone, PartialEq)]
88pub enum Value {
89 Text(String),
91 Number(f64),
92 Bool(bool),
93 Colour(Color),
94}
95
96impl Value {
97 pub fn as_text(&self) -> Option<&str> {
98 match self {
99 Value::Text(value) => Some(value),
100 _ => None,
101 }
102 }
103
104 pub fn as_number(&self) -> Option<f64> {
105 match self {
106 Value::Number(value) => Some(*value),
107 _ => None,
108 }
109 }
110
111 pub fn as_bool(&self) -> Option<bool> {
112 match self {
113 Value::Bool(value) => Some(*value),
114 _ => None,
115 }
116 }
117
118 pub fn as_colour(&self) -> Option<Color> {
119 match self {
120 Value::Colour(value) => Some(*value),
121 _ => None,
122 }
123 }
124}
125
126impl From<&str> for Value {
127 fn from(value: &str) -> Self {
128 Value::Text(value.to_owned())
129 }
130}
131
132impl From<String> for Value {
133 fn from(value: String) -> Self {
134 Value::Text(value)
135 }
136}
137
138impl From<f64> for Value {
139 fn from(value: f64) -> Self {
140 Value::Number(value)
141 }
142}
143
144impl From<f32> for Value {
145 fn from(value: f32) -> Self {
146 Value::Number(f64::from(value))
147 }
148}
149
150impl From<i32> for Value {
151 fn from(value: i32) -> Self {
152 Value::Number(f64::from(value))
153 }
154}
155
156impl From<bool> for Value {
157 fn from(value: bool) -> Self {
158 Value::Bool(value)
159 }
160}
161
162impl From<Color> for Value {
163 fn from(value: Color) -> Self {
164 Value::Colour(value)
165 }
166}
167
168#[derive(Debug, Clone, PartialEq, Default)]
170pub struct Number {
171 pub min: Option<f64>,
172 pub max: Option<f64>,
173 pub step: Option<f64>,
176 pub decimals: Option<usize>,
179 pub unit: Option<String>,
181}
182
183impl Number {
184 pub fn precision(&self) -> Option<usize> {
186 self.decimals.or_else(|| self.step.map(decimals_of))
187 }
188
189 pub fn format(&self, value: f64) -> String {
191 let value = if value == 0.0 { 0.0 } else { value };
192 match self.precision() {
193 Some(decimals) => format!("{value:.decimals$}"),
194 None => format!("{value}"),
195 }
196 }
197
198 pub fn display(&self, value: f64) -> String {
200 match &self.unit {
201 Some(unit) => format!("{}{unit}", self.format(value)),
202 None => self.format(value),
203 }
204 }
205
206 pub fn parse(&self, input: &str) -> Result<f64, String> {
208 let mut input = input.trim();
209 if let Some(unit) = self.unit.as_deref().filter(|unit| !unit.is_empty()) {
210 input = input.strip_suffix(unit).unwrap_or(input).trim_end();
211 }
212 let value: f64 = input.parse().map_err(|_| "Enter a number".to_owned())?;
213 if !value.is_finite() {
214 return Err("Enter a number".to_owned());
215 }
216 self.check(value)
217 }
218
219 pub fn check(&self, value: f64) -> Result<f64, String> {
221 if let Some(min) = self.min
222 && value < min
223 {
224 return Err(format!("Must be at least {}", self.display(min)));
225 }
226 if let Some(max) = self.max
227 && value > max
228 {
229 return Err(format!("Must be at most {}", self.display(max)));
230 }
231 let Some(step) = self.step.filter(|step| *step > 0.0 && step.fract() == 0.0) else {
232 return Ok(value);
233 };
234 let steps = (value - self.min.unwrap_or(0.0)) / step;
235 if (steps - steps.round()).abs() > 1e-9 {
236 if step == 1.0 {
237 return Err("Must be a whole number".to_owned());
238 }
239 return Err(format!("Must be a multiple of {}", self.format(step)));
240 }
241 Ok(value)
242 }
243
244 pub fn stepped(&self, value: f64, up: bool) -> f64 {
246 let step = self.step.filter(|step| *step > 0.0).unwrap_or(1.0);
247 let next = if up { value + step } else { value - step };
248 let next = match self.precision() {
249 Some(decimals) => {
250 let scale = 10f64.powi(i32::try_from(decimals).unwrap_or(i32::MAX).min(15));
251 (next * scale).round() / scale
252 }
253 None => next,
254 };
255 let next = self.min.map_or(next, |min| next.max(min));
256 self.max.map_or(next, |max| next.min(max))
257 }
258}
259
260fn decimals_of(step: f64) -> usize {
262 let text = format!("{step}");
263 text.split_once('.')
264 .map_or(0, |(_, fraction)| fraction.len())
265}
266
267pub fn hex(colour: Color) -> String {
269 let [r, g, b, a] = colour.into_rgba8();
270 if a == u8::MAX {
271 format!("#{r:02X}{g:02X}{b:02X}")
272 } else {
273 format!("#{r:02X}{g:02X}{b:02X}{a:02X}")
274 }
275}
276
277pub fn parse_hex(input: &str) -> Result<Color, String> {
280 let error = || "Enter a hex colour, such as #3B82F6".to_owned();
281 let input = input.trim();
282 let digits = input.strip_prefix('#').unwrap_or(input);
283 if !digits.chars().all(|digit| digit.is_ascii_hexdigit()) {
284 return Err(error());
285 }
286 let digits: String = match digits.len() {
287 3 | 4 => digits.chars().flat_map(|digit| [digit, digit]).collect(),
288 6 | 8 => digits.to_owned(),
289 _ => return Err(error()),
290 };
291 let bytes = (0..digits.len())
292 .step_by(2)
293 .map(|start| {
294 digits
295 .get(start..start + 2)
296 .and_then(|pair| u8::from_str_radix(pair, 16).ok())
297 })
298 .collect::<Option<Vec<u8>>>()
299 .ok_or_else(error)?;
300 match bytes.as_slice() {
301 [r, g, b] => Ok(Color::from_rgb8(*r, *g, *b)),
302 [r, g, b, a] => Ok(Color::from_rgba8(*r, *g, *b, f32::from(*a) / 255.0)),
303 _ => Err(error()),
304 }
305}
306
307pub type Validate = fn(&str) -> Result<(), String>;
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
312pub enum Toggle {
313 #[default]
314 Checkbox,
315 Switch,
316}
317
318impl Toggle {
319 pub const ALL: [Toggle; 2] = [Toggle::Checkbox, Toggle::Switch];
320}
321
322#[derive(Debug, Clone)]
324pub enum Kind {
325 Text(Option<Validate>),
327 Number(Number),
328 Toggle(Toggle),
329 Choice(Vec<String>),
331 Colour,
333 ReadOnly,
335 Custom,
337}
338
339#[derive(Debug, Clone)]
341pub struct Property<Id> {
342 pub id: Id,
343 pub name: String,
344 pub category: Option<String>,
346 pub description: Option<String>,
348 pub kind: Kind,
349 pub value: Value,
350 pub default: Option<Value>,
352 pub disabled: bool,
353}
354
355fn property<Id>(id: Id, name: impl Into<String>, kind: Kind, value: Value) -> Property<Id> {
356 Property {
357 id,
358 name: name.into(),
359 category: None,
360 description: None,
361 kind,
362 value,
363 default: None,
364 disabled: false,
365 }
366}
367
368pub fn text<Id>(id: Id, name: impl Into<String>, value: impl Into<String>) -> Property<Id> {
370 property(id, name, Kind::Text(None), Value::Text(value.into()))
371}
372
373pub fn number<Id>(id: Id, name: impl Into<String>, value: f64) -> Property<Id> {
377 property(
378 id,
379 name,
380 Kind::Number(Number::default()),
381 Value::Number(value),
382 )
383}
384
385pub fn toggle<Id>(id: Id, name: impl Into<String>, value: bool) -> Property<Id> {
388 property(id, name, Kind::Toggle(Toggle::Checkbox), Value::Bool(value))
389}
390
391pub fn choice<Id>(
393 id: Id,
394 name: impl Into<String>,
395 options: impl IntoIterator<Item = impl Into<String>>,
396 selected: impl Into<String>,
397) -> Property<Id> {
398 property(
399 id,
400 name,
401 Kind::Choice(options.into_iter().map(Into::into).collect()),
402 Value::Text(selected.into()),
403 )
404}
405
406pub fn colour<Id>(id: Id, name: impl Into<String>, value: Color) -> Property<Id> {
408 property(id, name, Kind::Colour, Value::Colour(value))
409}
410
411pub fn read_only<Id>(id: Id, name: impl Into<String>, value: impl Into<String>) -> Property<Id> {
413 property(id, name, Kind::ReadOnly, Value::Text(value.into()))
414}
415
416pub fn custom<Id>(id: Id, name: impl Into<String>, value: impl Into<Value>) -> Property<Id> {
419 property(id, name, Kind::Custom, value.into())
420}
421
422impl<Id> Property<Id> {
423 pub fn category(mut self, category: impl Into<String>) -> Self {
424 self.category = Some(category.into());
425 self
426 }
427
428 pub fn description(mut self, description: impl Into<String>) -> Self {
429 self.description = Some(description.into());
430 self
431 }
432
433 pub fn default(mut self, value: impl Into<Value>) -> Self {
436 self.default = Some(value.into());
437 self
438 }
439
440 pub fn disabled(mut self, disabled: bool) -> Self {
442 self.disabled = disabled;
443 self
444 }
445
446 pub fn min(mut self, min: f64) -> Self {
448 if let Kind::Number(number) = &mut self.kind {
449 number.min = Some(min);
450 }
451 self
452 }
453
454 pub fn max(mut self, max: f64) -> Self {
456 if let Kind::Number(number) = &mut self.kind {
457 number.max = Some(max);
458 }
459 self
460 }
461
462 pub fn range(self, min: f64, max: f64) -> Self {
463 self.min(min).max(max)
464 }
465
466 pub fn step(mut self, step: f64) -> Self {
469 if let Kind::Number(number) = &mut self.kind {
470 number.step = Some(step);
471 }
472 self
473 }
474
475 pub fn decimals(mut self, decimals: usize) -> Self {
477 if let Kind::Number(number) = &mut self.kind {
478 number.decimals = Some(decimals);
479 }
480 self
481 }
482
483 pub fn unit(mut self, unit: impl Into<String>) -> Self {
485 if let Kind::Number(number) = &mut self.kind {
486 number.unit = Some(unit.into());
487 }
488 self
489 }
490
491 pub fn switch(mut self) -> Self {
493 if let Kind::Toggle(toggle) = &mut self.kind {
494 *toggle = Toggle::Switch;
495 }
496 self
497 }
498
499 pub fn validate(mut self, validate: Validate) -> Self {
501 if let Kind::Text(check) = &mut self.kind {
502 *check = Some(validate);
503 }
504 self
505 }
506
507 pub fn is_modified(&self) -> bool {
509 self.default
510 .as_ref()
511 .is_some_and(|default| *default != self.value)
512 }
513
514 pub fn is_typed(&self) -> bool {
516 matches!(self.kind, Kind::Text(_) | Kind::Number(_) | Kind::Colour)
517 }
518
519 pub fn is_editable(&self) -> bool {
521 !self.disabled && !matches!(self.kind, Kind::ReadOnly | Kind::Custom)
522 }
523
524 pub fn display(&self) -> String {
526 match (&self.kind, &self.value) {
527 (Kind::Number(number), Value::Number(value)) => number.display(*value),
528 _ => display(&self.value),
529 }
530 }
531
532 pub fn edit_text(&self) -> String {
534 match (&self.kind, &self.value) {
535 (Kind::Number(number), Value::Number(value)) => number.format(*value),
536 _ => display(&self.value),
537 }
538 }
539
540 pub fn parse(&self, input: &str) -> Result<Value, String> {
542 match &self.kind {
543 Kind::Number(number) => number.parse(input).map(Value::Number),
544 Kind::Colour => parse_hex(input).map(Value::Colour),
545 Kind::Text(Some(validate)) => validate(input).map(|()| Value::Text(input.to_owned())),
546 Kind::Choice(options) if !options.iter().any(|option| option == input) => {
547 Err("Choose one of the options".to_owned())
548 }
549 _ => Ok(Value::Text(input.to_owned())),
550 }
551 }
552
553 pub fn accepts(&self, value: &Value) -> bool {
555 match (&self.kind, value) {
556 (Kind::Text(validate), Value::Text(text)) => {
557 validate.is_none_or(|validate| validate(text).is_ok())
558 }
559 (Kind::Number(number), Value::Number(value)) => number.check(*value).is_ok(),
560 (Kind::Toggle(_), Value::Bool(_)) | (Kind::Colour, Value::Colour(_)) => true,
561 (Kind::Choice(options), Value::Text(text)) => options.contains(text),
562 (Kind::ReadOnly, Value::Text(_)) | (Kind::Custom, _) => true,
563 _ => false,
564 }
565 }
566}
567
568fn display(value: &Value) -> String {
569 match value {
570 Value::Text(text) => text.clone(),
571 Value::Number(number) => Number::default().format(*number),
572 Value::Bool(true) => "On".to_owned(),
573 Value::Bool(false) => "Off".to_owned(),
574 Value::Colour(colour) => hex(*colour),
575 }
576}
577
578#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
580pub enum Sort {
581 #[default]
584 Categorised,
585 Alphabetical,
587}
588
589impl Sort {
590 pub const ALL: [Sort; 2] = [Sort::Categorised, Sort::Alphabetical];
591}
592
593#[derive(Debug, Clone, PartialEq, Eq, Hash)]
595pub enum Entry<Id> {
596 Category(String),
598 Property(Id),
599}
600
601#[derive(Debug, Clone, PartialEq, Eq, Default)]
603pub struct Draft {
604 pub text: String,
605 pub error: Option<String>,
606}
607
608#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
610enum Target {
611 Filter,
612 Editor,
613}
614
615#[derive(Debug, Clone, PartialEq)]
616struct Editing<Id> {
617 id: Id,
618 original: Value,
620}
621
622#[derive(Debug, Clone, PartialEq)]
624pub enum Event<Id> {
625 Press(Entry<Id>),
627 ToggleCategory(String),
628 Expand(String),
629 Collapse(String),
630 Next,
631 Previous,
632 First,
633 Last,
634 ExpandOrEnter,
636 CollapseOrLeave,
639 Edit(Id),
642 EditHighlighted,
645 Input(Id, String),
647 Submit,
649 Cancel,
652 Increment,
654 Decrement,
656 Set(Id, Value),
658 Reset(Id),
660 ResetHighlighted,
661 Search(String),
663 NextMatch,
665 PreviousMatch,
668 FocusSearch,
670 CopyValue(Id),
672 Sort(Sort),
673 ResizeStart,
675 Resize(f32),
677 ResizeEnd,
678 Focus(bool),
680}
681
682#[derive(Debug, Clone, PartialEq)]
684pub enum Output<Id> {
685 Changed { id: Id, value: Value },
687 Reset { id: Id, value: Value },
689 CopyValue(String),
692}
693
694#[derive(Debug, Clone)]
697pub struct State<Id> {
698 properties: Vec<Property<Id>>,
699 index: HashMap<Id, usize>,
700 categories: Vec<String>,
701 collapsed: HashSet<String>,
702 sort: Sort,
703 query: String,
704 highlighted: Option<Entry<Id>>,
705 editing: Option<Editing<Id>>,
706 drafts: HashMap<Id, Draft>,
707 name_width: Option<f32>,
708 resizing: bool,
709 focused: bool,
710 focus: (u64, Option<Target>),
712}
713
714impl<Id: Copy + Eq + Hash> State<Id> {
715 pub fn new(properties: impl IntoIterator<Item = Property<Id>>) -> Self {
718 let mut list: Vec<Property<Id>> = Vec::new();
719 let mut index = HashMap::new();
720 for property in properties {
721 match index.get(&property.id) {
722 Some(&position) => {
723 if let Some(slot) = list.get_mut(position) {
724 *slot = property;
725 }
726 }
727 None => {
728 let _ = index.insert(property.id, list.len());
729 list.push(property);
730 }
731 }
732 }
733 let mut categories: Vec<String> = Vec::new();
734 for category in list
735 .iter()
736 .filter_map(|property| property.category.as_ref())
737 {
738 if !categories.contains(category) {
739 categories.push(category.clone());
740 }
741 }
742 Self {
743 properties: list,
744 index,
745 categories,
746 collapsed: HashSet::new(),
747 sort: Sort::default(),
748 query: String::new(),
749 highlighted: None,
750 editing: None,
751 drafts: HashMap::new(),
752 name_width: None,
753 resizing: false,
754 focused: false,
755 focus: (0, None),
756 }
757 }
758
759 pub fn with_sort(mut self, sort: Sort) -> Self {
760 self.sort = sort;
761 self
762 }
763
764 pub fn with_collapsed(
766 mut self,
767 categories: impl IntoIterator<Item = impl Into<String>>,
768 ) -> Self {
769 self.collapsed
770 .extend(categories.into_iter().map(Into::into));
771 self
772 }
773
774 pub fn with_name_width(mut self, width: f32) -> Self {
777 self.name_width = Some(width.max(MIN_NAME_WIDTH));
778 self
779 }
780
781 pub fn properties(&self) -> &[Property<Id>] {
783 &self.properties
784 }
785
786 pub fn property(&self, id: Id) -> Option<&Property<Id>> {
787 self.index
788 .get(&id)
789 .and_then(|&position| self.properties.get(position))
790 }
791
792 fn property_mut(&mut self, id: Id) -> Option<&mut Property<Id>> {
793 self.index
794 .get(&id)
795 .and_then(|&position| self.properties.get_mut(position))
796 }
797
798 pub fn value(&self, id: Id) -> Option<&Value> {
799 self.property(id).map(|property| &property.value)
800 }
801
802 pub fn set(&mut self, id: Id, value: impl Into<Value>) -> bool {
805 let value = value.into();
806 let _ = self.drafts.remove(&id);
807 if self.editing_id() == Some(id) {
808 self.editing = None;
809 }
810 let Some(property) = self.property_mut(id) else {
811 return false;
812 };
813 if property.value == value {
814 return false;
815 }
816 property.value = value;
817 true
818 }
819
820 pub fn categories(&self) -> &[String] {
822 &self.categories
823 }
824
825 pub fn is_expanded(&self, category: &str) -> bool {
826 !self.collapsed.contains(category)
827 }
828
829 pub fn sort(&self) -> Sort {
830 self.sort
831 }
832
833 pub fn query(&self) -> &str {
835 &self.query
836 }
837
838 pub fn highlighted(&self) -> Option<&Entry<Id>> {
840 self.highlighted.as_ref()
841 }
842
843 pub fn highlighted_property(&self) -> Option<&Property<Id>> {
846 match self.highlighted {
847 Some(Entry::Property(id)) => self.property(id),
848 _ => None,
849 }
850 }
851
852 pub fn editing(&self) -> Option<Id> {
854 self.editing_id()
855 }
856
857 fn editing_id(&self) -> Option<Id> {
858 self.editing.as_ref().map(|editing| editing.id)
859 }
860
861 pub fn draft(&self, id: Id) -> Option<&Draft> {
864 self.drafts.get(&id)
865 }
866
867 pub fn error(&self, id: Id) -> Option<&str> {
869 self.drafts
870 .get(&id)
871 .and_then(|draft| draft.error.as_deref())
872 }
873
874 pub fn can_reset(&self, id: Id) -> bool {
877 self.property(id).is_some_and(|property| {
878 !property.disabled
879 && property.default.is_some()
880 && (property.is_modified() || self.draft(id).is_some())
881 })
882 }
883
884 pub fn is_focused(&self) -> bool {
885 self.focused
886 }
887
888 pub fn is_resizing(&self) -> bool {
890 self.resizing
891 }
892
893 pub fn name_width(&self) -> Option<f32> {
895 self.name_width
896 }
897
898 pub fn matches(&self, id: Id) -> bool {
900 self.property(id)
901 .is_some_and(|property| self.passes(property))
902 }
903
904 fn passes(&self, property: &Property<Id>) -> bool {
905 let query = self.query.trim();
906 query.is_empty() || property.name.to_lowercase().contains(&query.to_lowercase())
907 }
908
909 pub fn count(&self, category: &str) -> usize {
911 self.properties
912 .iter()
913 .filter(|property| property.category.as_deref() == Some(category))
914 .filter(|property| self.passes(property))
915 .count()
916 }
917
918 pub fn entries(&self) -> Vec<Entry<Id>> {
921 let passing = self
922 .properties
923 .iter()
924 .filter(|property| self.passes(property));
925 if self.sort == Sort::Alphabetical {
926 let mut sorted: Vec<&Property<Id>> = passing.collect();
927 sorted.sort_by_cached_key(|property| property.name.to_lowercase());
928 return sorted
929 .into_iter()
930 .map(|property| Entry::Property(property.id))
931 .collect();
932 }
933 let mut entries: Vec<Entry<Id>> = passing
934 .clone()
935 .filter(|property| property.category.is_none())
936 .map(|property| Entry::Property(property.id))
937 .collect();
938 for category in &self.categories {
939 let members: Vec<Id> = passing
940 .clone()
941 .filter(|property| property.category.as_ref() == Some(category))
942 .map(|property| property.id)
943 .collect();
944 if members.is_empty() {
945 continue;
946 }
947 entries.push(Entry::Category(category.clone()));
948 if self.is_expanded(category) {
949 entries.extend(members.into_iter().map(Entry::Property));
950 }
951 }
952 entries
953 }
954
955 pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>> {
957 match event {
958 Event::Press(entry) => {
959 let same = matches!(&entry, Entry::Property(id) if self.editing_id() == Some(*id));
960 if !same {
961 self.finish();
962 }
963 if let Entry::Category(name) = &entry {
964 self.toggle(name);
965 }
966 self.highlighted = Some(entry);
967 }
968 Event::ToggleCategory(name) => self.toggle(&name),
969 Event::Expand(name) => {
970 let _ = self.collapsed.remove(&name);
971 }
972 Event::Collapse(name) => self.collapse(&name),
973 Event::Next => self.step(Step::Next),
974 Event::Previous => self.step(Step::Previous),
975 Event::First => self.step(Step::First),
976 Event::Last => self.step(Step::Last),
977 Event::ExpandOrEnter => self.expand_or_enter(),
978 Event::CollapseOrLeave => self.collapse_or_leave(),
979 Event::Edit(id) => return self.edit(id),
980 Event::EditHighlighted => match self.highlighted.clone() {
981 Some(Entry::Property(id)) => return self.edit(id),
982 Some(Entry::Category(name)) => self.toggle(&name),
983 None => {}
984 },
985 Event::Input(id, input) => return self.input(id, input),
986 Event::Submit => self.submit(),
987 Event::Cancel => return self.cancel(),
988 Event::Increment => return self.nudge(true),
989 Event::Decrement => return self.nudge(false),
990 Event::Set(id, value) => {
991 if self.editing_id() != Some(id) {
992 self.finish();
993 }
994 return self.choose(id, value);
995 }
996 Event::Reset(id) => return self.reset(id),
997 Event::ResetHighlighted => {
998 if let Some(Entry::Property(id)) = self.highlighted {
999 return self.reset(id);
1000 }
1001 }
1002 Event::Search(query) => {
1003 self.finish();
1004 self.query = query;
1005 self.highlight_nearest_shown();
1006 }
1007 Event::NextMatch => self.step_match(true),
1008 Event::PreviousMatch => self.step_match(false),
1009 Event::FocusSearch => {
1010 self.finish();
1011 self.request(Target::Filter);
1012 }
1013 Event::CopyValue(id) => {
1014 let value = self.property(id)?.display();
1015 if self.editing_id() != Some(id) {
1016 self.finish();
1017 }
1018 self.highlighted = Some(Entry::Property(id));
1019 return Some(Output::CopyValue(value));
1020 }
1021 Event::Sort(sort) => {
1022 self.finish();
1023 self.sort = sort;
1024 self.keep_highlight_visible();
1025 }
1026 Event::ResizeStart => self.resizing = true,
1027 Event::Resize(width) => {
1028 if self.resizing {
1029 self.name_width = Some(width.max(MIN_NAME_WIDTH));
1030 }
1031 }
1032 Event::ResizeEnd => self.resizing = false,
1033 Event::Focus(focused) => {
1034 self.focused = focused;
1035 if !focused {
1036 self.finish();
1037 self.resizing = false;
1038 self.focus.1 = None;
1039 } else if self.highlighted.is_none() {
1040 self.highlighted = self.first_property();
1041 }
1042 }
1043 }
1044 None
1045 }
1046
1047 pub fn key_event(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event<Id>> {
1049 keymap
1050 .resolve_event(key)
1051 .and_then(|action| action.event(self))
1052 }
1053
1054 fn focus_request(&self) -> Option<(u64, Target)> {
1056 let (count, target) = self.focus;
1057 target.map(|target| (count, target))
1058 }
1059
1060 fn request(&mut self, target: Target) {
1061 self.focus = (self.focus.0.wrapping_add(1), Some(target));
1062 }
1063
1064 fn first_property(&self) -> Option<Entry<Id>> {
1065 let entries = self.entries();
1066 entries
1067 .iter()
1068 .find(|entry| matches!(entry, Entry::Property(_)))
1069 .or(entries.first())
1070 .cloned()
1071 }
1072
1073 fn display_order(&self) -> Vec<Id> {
1075 if self.sort == Sort::Alphabetical {
1076 let mut sorted: Vec<&Property<Id>> = self.properties.iter().collect();
1077 sorted.sort_by_cached_key(|property| property.name.to_lowercase());
1078 return sorted.into_iter().map(|property| property.id).collect();
1079 }
1080 let mut order: Vec<Id> = Vec::with_capacity(self.properties.len());
1081 for category in std::iter::once(None).chain(self.categories.iter().map(Some)) {
1082 order.extend(
1083 self.properties
1084 .iter()
1085 .filter(|property| property.category.as_ref() == category)
1086 .map(|property| property.id),
1087 );
1088 }
1089 order
1090 }
1091
1092 fn highlight_nearest_shown(&mut self) {
1096 let shown = self.entries();
1097 if self.highlighted.is_none() && !self.query.trim().is_empty() {
1098 self.highlighted = self.first_property();
1099 return;
1100 }
1101 let Some(highlighted) = self.highlighted.clone() else {
1102 return;
1103 };
1104 if shown.contains(&highlighted) {
1105 return;
1106 }
1107 let order = self.display_order();
1108 let start = match &highlighted {
1109 Entry::Property(id) => order.iter().position(|other| other == id),
1110 Entry::Category(name) => order.iter().position(|&id| {
1111 self.property(id)
1112 .is_some_and(|property| property.category.as_ref() == Some(name))
1113 }),
1114 }
1115 .unwrap_or(0);
1116 let (before, after) = order.split_at(start.min(order.len()));
1117 let is_shown = |id: &&Id| shown.contains(&Entry::Property(**id));
1118 let nearest = after
1119 .iter()
1120 .find(is_shown)
1121 .or_else(|| before.iter().rev().find(is_shown));
1122 self.highlighted = match nearest {
1123 Some(&id) => Some(Entry::Property(id)),
1124 None => self.first_property(),
1125 };
1126 }
1127
1128 fn keep_highlight_visible(&mut self) {
1129 let Some(highlighted) = &self.highlighted else {
1130 return;
1131 };
1132 if !self.entries().contains(highlighted) {
1133 self.highlighted = self.first_property();
1134 }
1135 }
1136
1137 fn toggle(&mut self, name: &str) {
1138 if self.collapsed.contains(name) {
1139 let _ = self.collapsed.remove(name);
1140 } else {
1141 self.collapse(name);
1142 }
1143 }
1144
1145 fn collapse(&mut self, name: &str) {
1146 if !self.categories.iter().any(|category| category == name) {
1147 return;
1148 }
1149 let _ = self.collapsed.insert(name.to_owned());
1150 if self.sort == Sort::Alphabetical {
1151 return;
1152 }
1153 let inside = |id: Option<Id>| {
1154 id.and_then(|id| self.property(id))
1155 .is_some_and(|property| property.category.as_deref() == Some(name))
1156 };
1157 let highlighted = match self.highlighted {
1158 Some(Entry::Property(id)) => Some(id),
1159 _ => None,
1160 };
1161 let hides_highlight = inside(highlighted);
1162 let hides_edit = inside(self.editing_id());
1163 if hides_highlight {
1164 self.highlighted = Some(Entry::Category(name.to_owned()));
1165 }
1166 if hides_edit {
1167 self.finish();
1168 }
1169 }
1170
1171 fn step(&mut self, step: Step) {
1172 self.finish();
1173 let entries = self.entries();
1174 let current = self
1175 .highlighted
1176 .as_ref()
1177 .and_then(|highlighted| entries.iter().position(|entry| entry == highlighted));
1178 let target = match (step, current) {
1179 (Step::First, _) | (Step::Next, None) => entries.first(),
1180 (Step::Last, _) | (Step::Previous, None) => entries.last(),
1181 (Step::Next, Some(index)) => entries.get(index + 1).or(entries.get(index)),
1182 (Step::Previous, Some(index)) => entries.get(index.saturating_sub(1)),
1183 };
1184 if let Some(target) = target {
1185 self.highlighted = Some(target.clone());
1186 }
1187 }
1188
1189 fn shown_properties(&self) -> Vec<Entry<Id>> {
1191 self.entries()
1192 .into_iter()
1193 .filter(|entry| matches!(entry, Entry::Property(_)))
1194 .collect()
1195 }
1196
1197 fn step_match(&mut self, forward: bool) {
1200 self.finish();
1201 let properties = self.shown_properties();
1202 let count = properties.len();
1203 if count == 0 {
1204 return;
1205 }
1206 let current = self
1207 .highlighted
1208 .as_ref()
1209 .and_then(|highlighted| properties.iter().position(|entry| entry == highlighted));
1210 let index = match (current, forward) {
1211 (None, true) => 0,
1212 (None, false) => count - 1,
1213 (Some(index), true) => (index + 1) % count,
1214 (Some(index), false) => (index + count - 1) % count,
1215 };
1216 self.highlighted = properties.get(index).cloned();
1217 }
1218
1219 fn expand_or_enter(&mut self) {
1220 let Some(Entry::Category(name)) = self.highlighted.clone() else {
1221 return;
1222 };
1223 if !self.is_expanded(&name) {
1224 let _ = self.collapsed.remove(&name);
1225 return;
1226 }
1227 let entries = self.entries();
1228 let first = entries
1229 .iter()
1230 .skip_while(|entry| **entry != Entry::Category(name.clone()))
1231 .nth(1)
1232 .filter(|entry| matches!(entry, Entry::Property(_)));
1233 if let Some(first) = first {
1234 self.highlighted = Some(first.clone());
1235 }
1236 }
1237
1238 fn collapse_or_leave(&mut self) {
1239 match self.highlighted.clone() {
1240 Some(Entry::Category(name)) => self.collapse(&name),
1241 Some(Entry::Property(id)) if self.sort == Sort::Categorised => {
1242 let category = self
1243 .property(id)
1244 .and_then(|property| property.category.clone());
1245 if let Some(category) = category {
1246 self.finish();
1247 self.highlighted = Some(Entry::Category(category));
1248 }
1249 }
1250 _ => {}
1251 }
1252 }
1253
1254 fn finish(&mut self) {
1257 let Some(editing) = self.editing.take() else {
1258 return;
1259 };
1260 if self.error(editing.id).is_none() {
1261 let _ = self.drafts.remove(&editing.id);
1262 }
1263 }
1264
1265 fn assign(&mut self, id: Id, value: Value) -> Option<Output<Id>> {
1267 let property = self.property_mut(id)?;
1268 if property.value == value {
1269 return None;
1270 }
1271 property.value = value.clone();
1272 Some(Output::Changed { id, value })
1273 }
1274
1275 fn edit(&mut self, id: Id) -> Option<Output<Id>> {
1276 let property = self.property(id)?;
1277 if property.disabled {
1278 self.highlighted = Some(Entry::Property(id));
1279 return None;
1280 }
1281 let kind = property.kind.clone();
1282 let value = property.value.clone();
1283 let typed = property.is_typed();
1284 let text = property.edit_text();
1285 if self.editing_id() != Some(id) {
1286 self.finish();
1287 }
1288 self.highlighted = Some(Entry::Property(id));
1289 match (kind, value) {
1290 (Kind::Toggle(_), Value::Bool(on)) => self.assign(id, Value::Bool(!on)),
1291 (Kind::Choice(options), Value::Text(current)) => {
1292 let next = options
1293 .iter()
1294 .position(|option| *option == current)
1295 .map_or(0, |index| (index + 1) % options.len().max(1));
1296 let option = options.get(next)?.clone();
1297 self.assign(id, Value::Text(option))
1298 }
1299 (_, value) if typed => {
1300 if self.editing_id() != Some(id) {
1301 let _ = self.drafts.entry(id).or_insert(Draft { text, error: None });
1302 self.editing = Some(Editing {
1303 id,
1304 original: value,
1305 });
1306 }
1307 self.request(Target::Editor);
1308 None
1309 }
1310 _ => None,
1311 }
1312 }
1313
1314 fn input(&mut self, id: Id, input: String) -> Option<Output<Id>> {
1315 let property = self.property(id).filter(|property| property.is_typed())?;
1316 if property.disabled {
1317 return None;
1318 }
1319 let parsed = property.parse(&input);
1320 let value = property.value.clone();
1321 if self.editing_id() != Some(id) {
1322 self.finish();
1323 self.editing = Some(Editing {
1324 id,
1325 original: value,
1326 });
1327 self.highlighted = Some(Entry::Property(id));
1328 }
1329 match parsed {
1330 Ok(value) => {
1331 let _ = self.drafts.insert(
1332 id,
1333 Draft {
1334 text: input,
1335 error: None,
1336 },
1337 );
1338 self.assign(id, value)
1339 }
1340 Err(error) => {
1341 let _ = self.drafts.insert(
1342 id,
1343 Draft {
1344 text: input,
1345 error: Some(error),
1346 },
1347 );
1348 None
1349 }
1350 }
1351 }
1352
1353 fn submit(&mut self) {
1354 let Some(id) = self.editing_id() else {
1355 return;
1356 };
1357 if self.error(id).is_some() {
1358 return;
1359 }
1360 let _ = self.drafts.remove(&id);
1361 self.editing = None;
1362 }
1363
1364 fn cancel(&mut self) -> Option<Output<Id>> {
1365 let Some(editing) = self.editing.take() else {
1366 self.query.clear();
1367 return None;
1368 };
1369 let _ = self.drafts.remove(&editing.id);
1370 self.assign(editing.id, editing.original)
1371 }
1372
1373 fn nudge(&mut self, up: bool) -> Option<Output<Id>> {
1374 let id = self.editing_id()?;
1375 let property = self.property(id)?;
1376 let (Kind::Number(number), Value::Number(current)) = (&property.kind, &property.value)
1377 else {
1378 return None;
1379 };
1380 let base = self
1381 .drafts
1382 .get(&id)
1383 .and_then(|draft| number.parse(&draft.text).ok())
1384 .unwrap_or(*current);
1385 let next = number.stepped(base, up);
1386 let text = number.format(next);
1387 let _ = self.drafts.insert(id, Draft { text, error: None });
1388 self.assign(id, Value::Number(next))
1389 }
1390
1391 fn choose(&mut self, id: Id, value: Value) -> Option<Output<Id>> {
1392 let property = self.property(id)?;
1393 if !property.is_editable() || !property.accepts(&value) {
1394 return None;
1395 }
1396 self.highlighted = Some(Entry::Property(id));
1397 self.assign(id, value)
1398 }
1399
1400 fn reset(&mut self, id: Id) -> Option<Output<Id>> {
1401 let property = self.property(id)?;
1402 if property.disabled {
1403 return None;
1404 }
1405 let default = property.default.clone()?;
1406 let _ = self.drafts.remove(&id);
1407 if self.editing_id() == Some(id) {
1408 self.editing = None;
1409 }
1410 let property = self.property_mut(id)?;
1411 if property.value == default {
1412 return None;
1413 }
1414 property.value = default.clone();
1415 Some(Output::Reset { id, value: default })
1416 }
1417}
1418
1419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1420enum Step {
1421 Next,
1422 Previous,
1423 First,
1424 Last,
1425}
1426
1427#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1429pub enum Action {
1430 Next,
1431 Previous,
1432 First,
1433 Last,
1434 Expand,
1435 Collapse,
1436 Edit,
1437 Cancel,
1438 Reset,
1439 CopyValue,
1440 FocusSearch,
1441}
1442
1443impl Action {
1444 pub fn event<Id: Copy + Eq + Hash>(self, state: &State<Id>) -> Option<Event<Id>> {
1447 let number = state
1448 .editing()
1449 .and_then(|id| state.property(id))
1450 .is_some_and(|property| matches!(property.kind, Kind::Number(_)));
1451 let highlighted = state.highlighted();
1452 let property = state.highlighted_property();
1453 match self {
1454 Action::Next if number => Some(Event::Decrement),
1455 Action::Next => Some(Event::Next),
1456 Action::Previous if number => Some(Event::Increment),
1457 Action::Previous => Some(Event::Previous),
1458 Action::First => Some(Event::First),
1459 Action::Last => Some(Event::Last),
1460 Action::Expand => {
1461 matches!(highlighted, Some(Entry::Category(_))).then_some(Event::ExpandOrEnter)
1462 }
1463 Action::Collapse => {
1464 let leaves = property.is_some_and(|property| property.category.is_some())
1465 && state.sort() == Sort::Categorised;
1466 (matches!(highlighted, Some(Entry::Category(_))) || leaves)
1467 .then_some(Event::CollapseOrLeave)
1468 }
1469 Action::Edit => {
1470 let editable = property.is_some_and(Property::is_editable);
1471 (matches!(highlighted, Some(Entry::Category(_))) || editable)
1472 .then_some(Event::EditHighlighted)
1473 }
1474 Action::Cancel => {
1475 (state.editing().is_some() || !state.query().is_empty()).then_some(Event::Cancel)
1476 }
1477 Action::Reset => property
1478 .filter(|property| state.can_reset(property.id))
1479 .map(|_| Event::ResetHighlighted),
1480 Action::CopyValue => property.map(|property| Event::CopyValue(property.id)),
1481 Action::FocusSearch => Some(Event::FocusSearch),
1482 }
1483 }
1484}
1485
1486impl keys::Action for Action {
1487 const ALL: &'static [Self] = &[
1488 Action::Next,
1489 Action::Previous,
1490 Action::First,
1491 Action::Last,
1492 Action::Expand,
1493 Action::Collapse,
1494 Action::Edit,
1495 Action::Cancel,
1496 Action::Reset,
1497 Action::CopyValue,
1498 Action::FocusSearch,
1499 ];
1500
1501 fn defaults() -> Keymap<Self> {
1502 default_keymap()
1503 }
1504
1505 fn name(self) -> &'static str {
1506 match self {
1507 Action::Next => "Next",
1508 Action::Previous => "Previous",
1509 Action::First => "First",
1510 Action::Last => "Last",
1511 Action::Expand => "Expand",
1512 Action::Collapse => "Collapse",
1513 Action::Edit => "Edit",
1514 Action::Cancel => "Cancel",
1515 Action::Reset => "Reset",
1516 Action::CopyValue => "CopyValue",
1517 Action::FocusSearch => "FocusSearch",
1518 }
1519 }
1520
1521 fn description(self) -> &'static str {
1522 match self {
1523 Action::Next => "Highlights the next row, or steps a number being edited down.",
1524 Action::Previous => "Highlights the previous row, or steps a number being edited up.",
1525 Action::First => "Highlights the first row.",
1526 Action::Last => "Highlights the last row.",
1527 Action::Expand => {
1528 "Opens the highlighted category, or moves to its first property when it is open."
1529 }
1530 Action::Collapse => {
1531 "Closes the highlighted category, or moves from a property to its category."
1532 }
1533 Action::Edit => {
1534 "Edits the highlighted property: types into text, flips a toggle or picks the next option."
1535 }
1536 Action::Cancel => "Cancels the edit and puts back the old value, or clears the filter.",
1537 Action::Reset => "Puts the highlighted property back to its default.",
1538 Action::CopyValue => "Copies the highlighted value as it is shown.",
1539 Action::FocusSearch => "Moves the keyboard to the filter box.",
1540 }
1541 }
1542}
1543
1544pub fn default_keymap() -> Keymap<Action> {
1567 Keymap::new()
1568 .bind(Chord::named(Named::ArrowDown), Action::Next)
1569 .bind(Chord::named(Named::ArrowUp), Action::Previous)
1570 .bind(Chord::named(Named::Home), Action::First)
1571 .bind(Chord::named(Named::End), Action::Last)
1572 .bind(Chord::named(Named::ArrowRight), Action::Expand)
1573 .bind(Chord::named(Named::ArrowLeft), Action::Collapse)
1574 .bind(Chord::named(Named::Enter), Action::Edit)
1575 .bind(Chord::named(Named::F2), Action::Edit)
1576 .bind(Chord::named(Named::Escape), Action::Cancel)
1577 .bind(Chord::named(Named::Delete), Action::Reset)
1578 .bind(Chord::character('c').command(), Action::CopyValue)
1579 .bind(Chord::character('f').command(), Action::FocusSearch)
1580}
1581
1582pub fn focus_search<Id, Message>(_state: &State<Id>) -> Task<Message> {
1586 widget::operation::focus(SEARCH)
1587}
1588
1589pub fn match_label<Id: Copy + Eq + Hash>(state: &State<Id>) -> String {
1594 let shown = state.shown_properties();
1595 let current = state
1596 .highlighted
1597 .as_ref()
1598 .and_then(|highlighted| shown.iter().position(|entry| entry == highlighted))
1599 .map(|index| index + 1);
1600 match_count_label(state.query(), shown.len(), current)
1601}
1602
1603#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1605pub enum MenuItem {
1606 CopyValue,
1607 Reset,
1608}
1609
1610impl MenuItem {
1611 pub const ALL: [MenuItem; 2] = [MenuItem::CopyValue, MenuItem::Reset];
1612
1613 pub fn event<Id>(self, id: Id) -> Event<Id> {
1615 match self {
1616 MenuItem::CopyValue => Event::CopyValue(id),
1617 MenuItem::Reset => Event::Reset(id),
1618 }
1619 }
1620
1621 pub fn is_enabled<Id: Copy + Eq + Hash>(self, state: &State<Id>, id: Id) -> bool {
1623 match self {
1624 MenuItem::CopyValue => state.property(id).is_some(),
1625 MenuItem::Reset => state.can_reset(id),
1626 }
1627 }
1628}
1629
1630pub fn menu<Id: Clone + PartialEq>() -> context_menu::State<MenuItem, Id> {
1635 context_menu::State::new([
1636 item(MenuItem::CopyValue, "Copy value").icon(crate::lucide!(Copy)),
1637 item(MenuItem::Reset, "Reset to default").icon(crate::lucide!(RotateCcw)),
1638 ])
1639}
1640
1641pub fn sync_menu<Id: Copy + Eq + Hash>(
1645 menu: &mut context_menu::State<MenuItem, Id>,
1646 state: &State<Id>,
1647) {
1648 let Some(&id) = menu.target() else {
1649 return;
1650 };
1651 for item in MenuItem::ALL {
1652 menu.set_disabled(item, !item.is_enabled(state, id));
1653 }
1654}
1655
1656#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1658pub struct Status {
1659 pub highlighted: bool,
1661 pub focused: bool,
1663 pub hovered: bool,
1664 pub disabled: bool,
1665 pub heading: bool,
1667}
1668
1669#[derive(Debug, Clone, Copy, PartialEq)]
1671pub struct RowStyle {
1672 pub background: Option<Color>,
1673 pub text: Color,
1674 pub icon: Color,
1675 pub ring: Option<Color>,
1677}
1678
1679pub fn row_style(tokens: &Tokens, status: Status) -> RowStyle {
1683 let hovered = status.hovered && !status.disabled;
1684 let background = match (hovered, status.heading) {
1685 (true, true) => Some(tokens.muted),
1686 (true, false) => Some(fade(tokens.accent, 0.6)),
1687 (false, true) => Some(fade(tokens.muted, 0.6)),
1688 (false, false) => None,
1689 };
1690 let text = if status.disabled {
1691 tokens.muted_foreground
1692 } else {
1693 tokens.foreground
1694 };
1695 RowStyle {
1696 background,
1697 text,
1698 icon: tokens.muted_foreground,
1699 ring: (status.highlighted && status.focused).then_some(tokens.ring),
1700 }
1701}
1702
1703pub fn value_colour(tokens: &Tokens, editable: bool) -> Color {
1705 if editable {
1706 tokens.foreground
1707 } else {
1708 tokens.muted_foreground
1709 }
1710}
1711
1712pub fn mark_colour(tokens: &Tokens) -> Color {
1714 tokens.primary
1715}
1716
1717pub fn divider_colour(tokens: &Tokens, active: bool) -> Color {
1720 if active {
1721 tokens.ring
1722 } else {
1723 fade(tokens.border, 0.7)
1724 }
1725}
1726
1727pub fn frame_style(tokens: &Tokens) -> container::Style {
1729 container::Style {
1730 border: Border {
1731 color: tokens.border,
1732 width: 1.0,
1733 radius: radius::MD.into(),
1734 },
1735 ..container::Style::default()
1736 }
1737}
1738
1739pub fn swatch_ring(tokens: &Tokens) -> Color {
1742 if tokens.is_dark {
1743 mix(tokens.border, tokens.foreground, 0.4)
1744 } else {
1745 tokens.border
1746 }
1747}
1748
1749pub fn swatch_style(tokens: &Tokens, colour: Color) -> container::Style {
1751 container::Style {
1752 background: Some(Background::Color(colour)),
1753 border: Border {
1754 color: swatch_ring(tokens),
1755 width: 1.0,
1756 radius: radius::SM.into(),
1757 },
1758 ..container::Style::default()
1759 }
1760}
1761
1762pub fn name_width(requested: Option<f32>, width: f32) -> f32 {
1768 let room = width - HANDLE_WIDTH - RESET_WIDTH;
1769 let max = (room - MIN_VALUE_WIDTH).max(MIN_NAME_WIDTH);
1770 let wanted = requested.unwrap_or_else(|| NAME_WIDTH.min(room - VALUE_WIDTH));
1771 wanted.clamp(MIN_NAME_WIDTH, max)
1772}
1773
1774type OnEvent<'a, Id, Message> = dyn Fn(Event<Id>) -> Message + 'a;
1775type Render<'a, Id, Message> = dyn Fn(&'a Property<Id>) -> Element<'a, Message> + 'a;
1776type BuildMenu<'a, Id, Message> =
1777 dyn FnOnce(Keymap<context_menu::Action>) -> RowMenu<'a, Id, Message> + 'a;
1778
1779pub struct PropertyGrid<'a, Id, Message> {
1781 state: &'a State<Id>,
1782 customs: Vec<(Id, Box<Render<'a, Id, Message>>)>,
1783 toolbar: bool,
1784 description: bool,
1785 placeholder: String,
1786 width: Length,
1787 height: Length,
1788 keymap: Keymap<Action>,
1789 shortcuts: Shortcuts,
1790 menu: Option<Box<BuildMenu<'a, Id, Message>>>,
1791 menu_keymap: Keymap<context_menu::Action>,
1792 on_event: Option<Box<OnEvent<'a, Id, Message>>>,
1793}
1794
1795pub fn property_grid<Id, Message>(state: &State<Id>) -> PropertyGrid<'_, Id, Message> {
1798 PropertyGrid {
1799 state,
1800 customs: Vec::new(),
1801 toolbar: true,
1802 description: true,
1803 placeholder: "Filter".to_owned(),
1804 width: Length::Fill,
1805 height: Length::Shrink,
1806 keymap: default_keymap(),
1807 shortcuts: Shortcuts::all(),
1808 menu: None,
1809 menu_keymap: context_menu::default_keymap(),
1810 on_event: None,
1811 }
1812}
1813
1814impl<Id: fmt::Debug, Message> fmt::Debug for PropertyGrid<'_, Id, Message> {
1815 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1816 f.debug_struct("PropertyGrid")
1817 .field("state", self.state)
1818 .field("toolbar", &self.toolbar)
1819 .field("description", &self.description)
1820 .field("placeholder", &self.placeholder)
1821 .field("width", &self.width)
1822 .field("height", &self.height)
1823 .field("keymap", &self.keymap)
1824 .finish_non_exhaustive()
1825 }
1826}
1827
1828impl<'a, Id, Message> PropertyGrid<'a, Id, Message> {
1829 pub fn toolbar(mut self, toolbar: bool) -> Self {
1832 self.toolbar = toolbar;
1833 self
1834 }
1835
1836 pub fn description(mut self, description: bool) -> Self {
1839 self.description = description;
1840 self
1841 }
1842
1843 pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
1845 self.placeholder = placeholder.into();
1846 self
1847 }
1848
1849 pub fn width(mut self, width: impl Into<Length>) -> Self {
1850 self.width = width.into();
1851 self
1852 }
1853
1854 pub fn height(mut self, height: impl Into<Length>) -> Self {
1857 self.height = height.into();
1858 self
1859 }
1860
1861 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
1863 self.keymap = keymap;
1864 self
1865 }
1866
1867 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
1870 self.shortcuts = shortcuts;
1871 self
1872 }
1873
1874 pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
1875 self.on_event = Some(Box::new(on_event));
1876 self
1877 }
1878
1879 pub fn custom(
1883 mut self,
1884 id: Id,
1885 render: impl Fn(&'a Property<Id>) -> Element<'a, Message> + 'a,
1886 ) -> Self
1887 where
1888 Id: PartialEq,
1889 {
1890 self.customs.retain(|(custom, _)| *custom != id);
1891 self.customs.push((id, Box::new(render)));
1892 self
1893 }
1894
1895 pub fn context_menu<MenuId>(
1900 mut self,
1901 menu: &'a context_menu::State<MenuId, Id>,
1902 on_event: impl Fn(context_menu::Event<MenuId, Id>) -> Message + 'a,
1903 ) -> Self
1904 where
1905 MenuId: Copy + PartialEq + 'a,
1906 Id: Clone + PartialEq + 'a,
1907 Message: Clone + 'a,
1908 {
1909 let on_event: Rc<dyn Fn(context_menu::Event<MenuId, Id>) -> Message + 'a> =
1910 Rc::new(on_event);
1911 self.menu = Some(Box::new(move |keymap| row_menu(menu, keymap, on_event)));
1912 self
1913 }
1914
1915 pub fn context_menu_keymap(mut self, keymap: Keymap<context_menu::Action>) -> Self {
1917 self.menu_keymap = keymap;
1918 self
1919 }
1920
1921 pub fn is_enabled(&self) -> bool {
1922 self.on_event.is_some()
1923 }
1924}
1925
1926impl<'a, Id, Message> From<PropertyGrid<'a, Id, Message>> for Element<'a, Message>
1927where
1928 Id: Copy + Eq + Hash + 'a,
1929 Message: Clone + 'a,
1930{
1931 fn from(grid: PropertyGrid<'a, Id, Message>) -> Self {
1932 let PropertyGrid {
1933 state,
1934 customs,
1935 toolbar,
1936 description,
1937 placeholder,
1938 width,
1939 height,
1940 keymap,
1941 shortcuts,
1942 menu,
1943 menu_keymap,
1944 on_event,
1945 } = grid;
1946 let menu = menu
1947 .filter(|_| on_event.is_some())
1948 .map(|build| build(menu_keymap));
1949 let view = Rc::new(View {
1950 state,
1951 customs,
1952 toolbar,
1953 description,
1954 placeholder,
1955 height,
1956 keymap,
1957 shortcuts,
1958 menu,
1959 entries: state.entries(),
1960 on_event: on_event.map(Rc::from),
1961 });
1962 responsive(move |size| view.body(size.width))
1963 .width(width)
1964 .height(height)
1965 .into()
1966 }
1967}
1968
1969struct View<'a, Id, Message> {
1971 state: &'a State<Id>,
1972 customs: Vec<(Id, Box<Render<'a, Id, Message>>)>,
1973 toolbar: bool,
1974 description: bool,
1975 placeholder: String,
1976 height: Length,
1977 keymap: Keymap<Action>,
1978 shortcuts: Shortcuts,
1979 menu: Option<RowMenu<'a, Id, Message>>,
1980 entries: Vec<Entry<Id>>,
1981 on_event: Option<Rc<OnEvent<'a, Id, Message>>>,
1982}
1983
1984fn muted(theme: &Theme) -> Color {
1985 Tokens::of(theme).muted_foreground
1986}
1987
1988impl<'a, Id, Message> View<'a, Id, Message>
1989where
1990 Id: Copy + Eq + Hash + 'a,
1991 Message: Clone + 'a,
1992{
1993 fn send(&self, event: Event<Id>) -> Option<Message> {
1994 self.on_event.as_ref().map(|on_event| on_event(event))
1995 }
1996
1997 fn body(self: &Rc<Self>, width: f32) -> Element<'a, Message> {
1998 let state = self.state;
1999 let inner = width - 2.0 - space::SM * 2.0;
2001 let names = name_width(state.name_width(), inner);
2002
2003 let highlight = state
2004 .highlighted()
2005 .and_then(|highlighted| self.entries.iter().position(|entry| entry == highlighted));
2006 let list = {
2007 let view = Rc::clone(self);
2008 rows(self.entries.len(), ROW_HEIGHT, move |range| {
2009 view.lines(range, names)
2010 })
2011 .highlight(highlight)
2012 .height(if self.height == Length::Shrink {
2013 Length::Shrink
2014 } else {
2015 Length::Fill
2016 })
2017 };
2018
2019 let mut inside = column![list];
2020 if let Some(footer) = self.footer() {
2021 inside = inside.push(container(Space::new()).width(Length::Fill).height(1).style(
2022 |theme| container::Style {
2023 background: Some(Background::Color(Tokens::of(theme).border)),
2024 ..container::Style::default()
2025 },
2026 ));
2027 inside = inside.push(footer);
2028 }
2029 let mut inside: Element<'a, Message> = inside.into();
2030 if state.is_resizing()
2031 && let Some(on_event) = self.on_event.clone()
2032 {
2033 let end = on_event(Event::ResizeEnd);
2034 inside = mouse_area(inside)
2035 .on_move(move |point| {
2036 on_event(Event::Resize(point.x - space::SM - HANDLE_WIDTH / 2.0))
2037 })
2038 .on_release(end.clone())
2039 .on_exit(end)
2040 .interaction(mouse::Interaction::ResizingHorizontally)
2041 .into();
2042 }
2043 let frame = container(inside)
2044 .padding(1)
2045 .width(Length::Fill)
2046 .height(if self.height == Length::Shrink {
2047 Length::Shrink
2048 } else {
2049 Length::Fill
2050 })
2051 .clip(true)
2052 .style(|theme| frame_style(&Tokens::of(theme)));
2053 #[cfg(feature = "icedwright")]
2054 let frame = icedwright_probe::semantic(frame)
2055 .role(icedwright_probe::role::Table)
2056 .component("iced_cube::property_grid");
2057
2058 let mut parts = column![].spacing(space::SM);
2059 if self.toolbar {
2060 parts = parts.push(self.toolbar());
2061 }
2062 parts = parts.push(frame);
2063 let parts: Element<'a, Message> = parts.into();
2064
2065 let Some(on_event) = self.on_event.clone() else {
2066 return parts;
2067 };
2068 let request = state.focus_request().map(|(count, target)| match target {
2069 Target::Filter => (count, SEARCH, false),
2070 Target::Editor => (count, EDITOR_ID, true),
2071 });
2072 let focuser = Focuser {
2073 content: parts,
2074 request,
2075 };
2076 let cancel = state.editing().map(|_| on_event(Event::Cancel));
2077 let on_focus = on_event.clone();
2078 let keymap = self.keymap.clone();
2079 let view = Rc::clone(self);
2080 scope(focuser)
2081 .escape(EDITOR_ID, cancel)
2082 .on_focus(move |focused| on_focus(Event::Focus(focused)))
2083 .on_key(move |key| {
2084 let opened = view
2085 .menu
2086 .as_ref()
2087 .zip(state.highlighted_property())
2088 .and_then(|(menu, property)| menu.key(key, property.id));
2089 opened.or_else(|| state.key_event(&keymap, key).map(|event| on_event(event)))
2090 })
2091 .into()
2092 }
2093
2094 fn toolbar(&self) -> Element<'a, Message> {
2095 let state = self.state;
2096 let on_event = self.on_event.clone();
2097 let field = input(&self.placeholder, state.query())
2098 .id(SEARCH)
2099 .icon(crate::lucide!(Search))
2100 .shortcuts(self.shortcuts)
2101 .size(input::Size::Sm)
2102 .width(Length::Fill)
2103 .on_input_maybe(on_event.map(|on_event| move |query| on_event(Event::Search(query))));
2104 let searching = !state.query().is_empty();
2105 let filter = search_keys(field, SEARCH)
2106 .on_clear(
2107 self.send(Event::Search(String::new()))
2108 .filter(|_| searching),
2109 )
2110 .on_next(self.send(Event::NextMatch).filter(|_| searching))
2111 .on_previous(self.send(Event::PreviousMatch).filter(|_| searching));
2112 let sort = |sort: Sort, glyph, label| {
2113 icon_button(glyph)
2114 .label(label)
2115 .size(button::Size::Sm)
2116 .pressed(state.sort() == sort)
2117 .on_press_maybe(self.send(Event::Sort(sort)))
2118 };
2119 row![
2120 filter,
2121 search_count(match_label(state)),
2122 sort(Sort::Categorised, crate::lucide!(ListTree), "Categorised"),
2123 sort(
2124 Sort::Alphabetical,
2125 crate::lucide!(ArrowDownAZ),
2126 "Alphabetical"
2127 ),
2128 ]
2129 .spacing(space::XS)
2130 .align_y(Alignment::Center)
2131 .into()
2132 }
2133
2134 fn footer(&self) -> Option<Element<'a, Message>> {
2136 let state = self.state;
2137 let property = state.highlighted_property();
2138 let error = state
2139 .editing()
2140 .and_then(|id| state.error(id))
2141 .or_else(|| property.and_then(|property| state.error(property.id)));
2142 if !self.description && error.is_none() {
2143 return None;
2144 }
2145 let (title, body) = match state.highlighted() {
2146 Some(Entry::Property(_)) => (
2147 property
2148 .map(|property| property.name.as_str())
2149 .unwrap_or_default(),
2150 property.and_then(|property| property.description.as_deref()),
2151 ),
2152 Some(Entry::Category(name)) => (name.as_str(), None),
2153 None => ("", None),
2154 };
2155 let mut content = column![].spacing(2).width(Length::Fill);
2156 if self.description && title.is_empty() {
2157 content = content.push(widget::text(NOTHING_SELECTED).size(text_size::SM).style(
2158 |theme: &Theme| widget::text::Style {
2159 color: Some(muted(theme)),
2160 },
2161 ));
2162 } else if self.description {
2163 content = content.push(ellipsis(title).font(theme::semibold()));
2164 }
2165 match (error, body) {
2166 (Some(error), _) => {
2167 content = content.push(widget::text(error.to_owned()).size(text_size::XS).style(
2168 |theme: &Theme| widget::text::Style {
2169 color: Some(Tokens::of(theme).destructive_text),
2170 },
2171 ));
2172 }
2173 (None, Some(body)) if self.description => {
2174 content = content.push(widget::text(body).size(text_size::XS).style(
2175 |theme: &Theme| widget::text::Style {
2176 color: Some(muted(theme)),
2177 },
2178 ));
2179 }
2180 _ => {}
2181 }
2182 let least = if self.description {
2183 DESCRIPTION_HEIGHT
2184 } else {
2185 DESCRIPTION_HEIGHT / 2.0
2186 };
2187 let strut = Space::new().height(least - space::SM * 2.0);
2189 Some(
2190 container(row![content, strut])
2191 .padding([space::SM, space::MD])
2192 .width(Length::Fill)
2193 .into(),
2194 )
2195 }
2196
2197 fn lines(&self, range: Range<usize>, names: f32) -> Element<'a, Message> {
2198 let entries = self.entries.get(range).unwrap_or_default();
2199 column(entries.iter().map(|entry| match entry {
2200 Entry::Category(name) => {
2201 let row = self.heading(name);
2202 #[cfg(feature = "icedwright")]
2203 let row = icedwright_probe::semantic(row)
2204 .role(icedwright_probe::role::Row)
2205 .name(name.clone())
2206 .expanded(self.state.is_expanded(name))
2207 .component("iced_cube::property_grid")
2208 .into();
2209 row
2210 }
2211 Entry::Property(id) => {
2212 let row = self.property(*id, names);
2213 let row = match &self.menu {
2214 Some(menu) => menu.wrap(*id, row),
2215 None => row,
2216 };
2217 #[cfg(feature = "icedwright")]
2218 let row = match self.state.property(*id) {
2219 Some(property) => {
2220 let mut annotated = icedwright_probe::semantic(row)
2221 .role(icedwright_probe::role::Row)
2222 .name(property.name.clone())
2223 .click_clock(icedwright_probe::ClickClock::Probe)
2224 .component("iced_cube::property_grid");
2225 if property.disabled || self.on_event.is_none() {
2226 annotated = annotated.disabled(true);
2227 }
2228 if property.is_modified() {
2229 annotated = annotated.prop("modified", "true");
2230 }
2231 annotated.into()
2232 }
2233 None => row,
2234 };
2235 row
2236 }
2237 }))
2238 .into()
2239 }
2240
2241 fn status(&self, entry: &Entry<Id>, disabled: bool) -> Status {
2242 let state = self.state;
2243 let target = self
2244 .menu
2245 .as_ref()
2246 .and_then(RowMenu::target)
2247 .map(Entry::Property);
2248 let menu_open_here = target.as_ref() == Some(entry);
2249 Status {
2250 highlighted: ringed(target.as_ref(), entry, state.highlighted() == Some(entry)),
2251 focused: state.is_focused() || menu_open_here,
2252 hovered: false,
2253 disabled,
2254 heading: matches!(entry, Entry::Category(_)),
2255 }
2256 }
2257
2258 fn heading(&self, name: &str) -> Element<'a, Message> {
2259 let state = self.state;
2260 let entry = Entry::Category(name.to_owned());
2261 let status = self.status(&entry, self.on_event.is_none());
2262 let enabled = self.on_event.is_some();
2263 let glyph = if state.is_expanded(name) {
2264 crate::lucide!(ChevronDown)
2265 } else {
2266 crate::lucide!(ChevronRight)
2267 };
2268 let colours = move |theme: &Theme| row_style(&Tokens::of(theme), status);
2269 let count = state.count(name);
2270 let body = row![
2271 themed(glyph, ICON_SIZE, opacity(enabled), move |theme| colours(
2272 theme
2273 )
2274 .icon),
2275 ellipsis(name.to_owned())
2276 .font(theme::semibold())
2277 .colour(move |theme| colours(theme).text),
2278 widget::text(count.to_string())
2279 .size(text_size::XS)
2280 .wrapping(widget::text::Wrapping::None)
2281 .style(|theme: &Theme| widget::text::Style {
2282 color: Some(muted(theme)),
2283 }),
2284 ]
2285 .spacing(space::SM)
2286 .align_y(Alignment::Center)
2287 .padding(Padding::ZERO.left(space::SM).right(space::SM))
2288 .height(ROW_HEIGHT);
2289 let row = pressable(body, move |theme, hovered| {
2290 look(row_style(&Tokens::of(theme), Status { hovered, ..status }))
2291 });
2292 match self.send(Event::Press(entry)) {
2293 Some(message) => row.on_press(move |_| message.clone()).into(),
2294 None => row.into(),
2295 }
2296 }
2297
2298 fn property(&self, id: Id, names: f32) -> Element<'a, Message> {
2299 let state = self.state;
2300 let Some(property) = state.property(id) else {
2301 return Space::new().height(ROW_HEIGHT).into();
2302 };
2303 let entry = Entry::Property(id);
2304 let on_event = self.on_event.clone().filter(|_| !property.disabled);
2305 let enabled = on_event.is_some();
2306 let status = self.status(&entry, !enabled);
2307 let colours = move |theme: &Theme| row_style(&Tokens::of(theme), status);
2308 let modified = property.is_modified();
2309
2310 let mark: Element<'a, Message> = if modified {
2311 container(
2312 container(Space::new())
2313 .width(MARK_SIZE)
2314 .height(MARK_SIZE)
2315 .style(|theme| container::Style {
2316 background: Some(Background::Color(mark_colour(&Tokens::of(theme)))),
2317 border: Border {
2318 radius: radius::FULL.into(),
2319 ..Border::default()
2320 },
2321 ..container::Style::default()
2322 }),
2323 )
2324 .width(MARK_WIDTH)
2325 .into()
2326 } else {
2327 Space::new().width(MARK_WIDTH).into()
2328 };
2329 let name = ellipsis(property.name.as_str())
2330 .font(if modified {
2331 theme::semibold()
2332 } else {
2333 theme::font()
2334 })
2335 .colour(move |theme| colours(theme).text);
2336 let name = container(row![mark, name].align_y(Alignment::Center))
2337 .width(names)
2338 .height(Length::Fill)
2339 .align_y(Alignment::Center);
2340 #[cfg(feature = "icedwright")]
2341 let name = icedwright_probe::semantic(name)
2342 .role(icedwright_probe::role::RowHeader)
2343 .name(property.name.as_str())
2344 .component("iced_cube::property_grid");
2345
2346 let handle = self.handle();
2347 let value = container(self.value(property))
2348 .width(Length::Fill)
2349 .height(Length::Fill)
2350 .align_y(Alignment::Center);
2351 #[cfg(feature = "icedwright")]
2352 let value = icedwright_probe::semantic(value)
2353 .role(icedwright_probe::role::Cell)
2354 .name(display(&property.value))
2355 .component("iced_cube::property_grid");
2356
2357 let reset: Element<'a, Message> = match &on_event {
2358 Some(on_event) if state.can_reset(id) => {
2359 let icon = themed(crate::lucide!(RotateCcw), RESET_ICON_SIZE, 1.0, muted);
2360 let button = mouse_area(container(icon).center(RESET_WIDTH))
2361 .on_press(on_event(Event::Reset(id)))
2362 .interaction(mouse::Interaction::Pointer);
2363 #[cfg(feature = "icedwright")]
2364 let button = icedwright_probe::semantic(button)
2365 .role(icedwright_probe::role::Button)
2366 .name("Reset to default")
2367 .component("iced_cube::property_grid");
2368 tooltip(button, "Reset to default").into()
2369 }
2370 _ => Space::new().width(RESET_WIDTH).into(),
2371 };
2372
2373 let body = row![name, handle, value, reset]
2374 .align_y(Alignment::Center)
2375 .padding(Padding::ZERO.left(space::SM).right(space::SM))
2376 .height(ROW_HEIGHT);
2377 let row = pressable(body, move |theme, hovered| {
2378 look(row_style(&Tokens::of(theme), Status { hovered, ..status }))
2379 });
2380 let Some(on_event) = self.on_event.clone() else {
2381 return row.into();
2382 };
2383 let press = on_event(Event::Press(entry));
2384 let edit = property.is_editable().then(|| on_event(Event::Edit(id)));
2385 row.on_press(move |_| press.clone())
2386 .on_double_click(edit)
2387 .into()
2388 }
2389
2390 fn handle(&self) -> Element<'a, Message> {
2392 let resizing = self.state.is_resizing();
2393 let line = container(container(Space::new()).width(1).height(Length::Fill).style(
2394 move |theme| container::Style {
2395 background: Some(Background::Color(divider_colour(
2396 &Tokens::of(theme),
2397 resizing,
2398 ))),
2399 ..container::Style::default()
2400 },
2401 ))
2402 .center_x(HANDLE_WIDTH)
2403 .height(Length::Fill);
2404 match self.send(Event::ResizeStart) {
2405 Some(start) => mouse_area(line)
2406 .on_press(start)
2407 .interaction(mouse::Interaction::ResizingHorizontally)
2408 .into(),
2409 None => line.into(),
2410 }
2411 }
2412
2413 fn value(&self, property: &'a Property<Id>) -> Element<'a, Message> {
2414 let state = self.state;
2415 let id = property.id;
2416 if let Some((_, render)) = self.customs.iter().find(|(custom, _)| *custom == id) {
2417 return render(property);
2418 }
2419 let on_event = self.on_event.clone().filter(|_| !property.disabled);
2420 let editable = on_event.is_some() && property.is_editable();
2421
2422 match (&property.kind, &property.value) {
2423 (Kind::Toggle(toggle), Value::Bool(on)) => {
2424 let set =
2425 on_event.map(|on_event| move |on| on_event(Event::Set(id, Value::Bool(on))));
2426 let control: Element<'a, Message> = match toggle {
2427 Toggle::Checkbox => checkbox(*on).on_toggle_maybe(set).into(),
2428 Toggle::Switch => switch(*on).on_toggle_maybe(set).into(),
2429 };
2430 container(control)
2431 .padding(Padding::ZERO.left(space::SM))
2432 .into()
2433 }
2434 (Kind::Choice(options), Value::Text(current)) => {
2435 select(options.as_slice(), Some(current.clone()))
2436 .width(Length::Fill)
2437 .on_select_maybe(on_event.map(|on_event| {
2438 move |option: String| on_event(Event::Set(id, Value::Text(option)))
2439 }))
2440 .into()
2441 }
2442 _ if property.is_typed() && editable => match state.draft(id) {
2443 Some(draft) => self.field(property, draft),
2444 None => self.shown(property, true),
2445 },
2446 _ => self.shown(property, editable),
2447 }
2448 }
2449
2450 fn shown(&self, property: &'a Property<Id>, editable: bool) -> Element<'a, Message> {
2452 let label = ellipsis(property.display())
2453 .colour(move |theme| value_colour(&Tokens::of(theme), editable));
2454 let content: Element<'a, Message> = match property.value {
2455 Value::Colour(colour) => row![swatch(colour), label]
2456 .spacing(space::SM)
2457 .align_y(Alignment::Center)
2458 .into(),
2459 _ => label.into(),
2460 };
2461 let content = container(content)
2462 .padding(Padding::ZERO.left(space::SM))
2463 .width(Length::Fill)
2464 .height(Length::Fill)
2465 .align_y(Alignment::Center);
2466 match self
2467 .send(Event::Edit(property.id))
2468 .filter(|_| editable && property.is_typed())
2469 {
2470 Some(edit) => mouse_area(content)
2471 .on_press(edit)
2472 .interaction(mouse::Interaction::Text)
2473 .into(),
2474 None => content.into(),
2475 }
2476 }
2477
2478 fn field(&self, property: &'a Property<Id>, draft: &'a Draft) -> Element<'a, Message> {
2480 let id = property.id;
2481 let mut field = input("", &draft.text)
2482 .shortcuts(self.shortcuts)
2483 .size(input::Size::Sm)
2484 .invalid(draft.error.is_some())
2485 .on_input_maybe(
2486 self.on_event
2487 .clone()
2488 .map(|on_event| move |text| on_event(Event::Input(id, text))),
2489 )
2490 .on_submit_maybe(self.send(Event::Submit));
2491 if self.state.editing() == Some(id) {
2492 field = field.id(EDITOR_ID);
2493 }
2494 let Value::Colour(current) = property.value else {
2495 return field.into();
2496 };
2497 let colour = parse_hex(&draft.text).unwrap_or(current);
2498 row![swatch(colour), field]
2499 .spacing(space::SM)
2500 .align_y(Alignment::Center)
2501 .padding(Padding::ZERO.left(space::SM))
2502 .into()
2503 }
2504}
2505
2506fn swatch<'a, Message: 'a>(colour: Color) -> Element<'a, Message> {
2507 container(Space::new())
2508 .width(SWATCH_SIZE)
2509 .height(SWATCH_SIZE)
2510 .style(move |theme| swatch_style(&Tokens::of(theme), colour))
2511 .into()
2512}
2513
2514fn look(style: RowStyle) -> Look {
2515 Look {
2516 background: style.background,
2517 border: Border {
2518 color: style.ring.unwrap_or(Color::TRANSPARENT),
2519 width: if style.ring.is_some() { 1.0 } else { 0.0 },
2520 radius: radius::SM.into(),
2521 },
2522 divider: None,
2523 }
2524}
2525
2526struct Focuser<'a, Message> {
2529 content: Element<'a, Message>,
2530 request: Option<(u64, widget::Id, bool)>,
2531}
2532
2533#[derive(Debug, Default)]
2535struct Handled(u64);
2536
2537impl<Message: Clone> Widget<Message, Theme, Renderer> for Focuser<'_, Message> {
2538 fn tag(&self) -> tree::Tag {
2539 tree::Tag::of::<Handled>()
2540 }
2541
2542 fn state(&self) -> tree::State {
2543 tree::State::new(Handled::default())
2544 }
2545
2546 fn children(&self) -> Vec<Tree> {
2547 vec![Tree::new(&self.content)]
2548 }
2549
2550 fn diff(&self, tree: &mut Tree) {
2551 tree.diff_children(std::slice::from_ref(&self.content));
2552 }
2553
2554 fn size(&self) -> Size<Length> {
2555 self.content.as_widget().size()
2556 }
2557
2558 fn size_hint(&self) -> Size<Length> {
2559 self.content.as_widget().size_hint()
2560 }
2561
2562 fn layout(
2563 &mut self,
2564 tree: &mut Tree,
2565 renderer: &Renderer,
2566 limits: &layout::Limits,
2567 ) -> layout::Node {
2568 let Tree {
2569 state, children, ..
2570 } = tree;
2571 let Some(child) = children.first_mut() else {
2572 return layout::Node::new(Size::ZERO);
2573 };
2574 let node = self.content.as_widget_mut().layout(child, renderer, limits);
2575 let handled = state.downcast_mut::<Handled>();
2576 if let Some((count, id, select_all)) = &self.request
2579 && handled.0 != *count
2580 {
2581 handled.0 = *count;
2582 let layout = Layout::new(&node);
2583 let mut focus = operation::focusable::focus(id.clone());
2584 self.content
2585 .as_widget_mut()
2586 .operate(child, layout, renderer, &mut focus);
2587 if *select_all {
2588 let mut select = operation::text_input::select_all(id.clone());
2589 self.content
2590 .as_widget_mut()
2591 .operate(child, layout, renderer, &mut select);
2592 }
2593 }
2594 node
2595 }
2596
2597 fn draw(
2598 &self,
2599 tree: &Tree,
2600 renderer: &mut Renderer,
2601 theme: &Theme,
2602 style: &renderer::Style,
2603 layout: Layout<'_>,
2604 cursor: mouse::Cursor,
2605 viewport: &Rectangle,
2606 ) {
2607 if let Some(child) = tree.children.first() {
2608 self.content
2609 .as_widget()
2610 .draw(child, renderer, theme, style, layout, cursor, viewport);
2611 }
2612 }
2613
2614 fn operate(
2615 &mut self,
2616 tree: &mut Tree,
2617 layout: Layout<'_>,
2618 renderer: &Renderer,
2619 operation: &mut dyn Operation,
2620 ) {
2621 if let Some(child) = tree.children.first_mut() {
2622 self.content
2623 .as_widget_mut()
2624 .operate(child, layout, renderer, operation);
2625 }
2626 }
2627
2628 fn update(
2629 &mut self,
2630 tree: &mut Tree,
2631 event: &iced::Event,
2632 layout: Layout<'_>,
2633 cursor: mouse::Cursor,
2634 renderer: &Renderer,
2635 clipboard: &mut dyn Clipboard,
2636 shell: &mut Shell<'_, Message>,
2637 viewport: &Rectangle,
2638 ) {
2639 let Some(child) = tree.children.first_mut() else {
2640 return;
2641 };
2642 self.content.as_widget_mut().update(
2643 child, event, layout, cursor, renderer, clipboard, shell, viewport,
2644 );
2645 }
2646
2647 fn mouse_interaction(
2648 &self,
2649 tree: &Tree,
2650 layout: Layout<'_>,
2651 cursor: mouse::Cursor,
2652 viewport: &Rectangle,
2653 renderer: &Renderer,
2654 ) -> mouse::Interaction {
2655 tree.children
2656 .first()
2657 .map_or(mouse::Interaction::None, |child| {
2658 self.content
2659 .as_widget()
2660 .mouse_interaction(child, layout, cursor, viewport, renderer)
2661 })
2662 }
2663
2664 fn overlay<'b>(
2665 &'b mut self,
2666 tree: &'b mut Tree,
2667 layout: Layout<'b>,
2668 renderer: &Renderer,
2669 viewport: &Rectangle,
2670 translation: Vector,
2671 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
2672 let child = tree.children.first_mut()?;
2673 self.content
2674 .as_widget_mut()
2675 .overlay(child, layout, renderer, viewport, translation)
2676 }
2677}
2678
2679impl<'a, Message: Clone + 'a> From<Focuser<'a, Message>> for Element<'a, Message> {
2680 fn from(focuser: Focuser<'a, Message>) -> Self {
2681 Element::new(focuser)
2682 }
2683}
2684
2685#[cfg(test)]
2686mod tests {
2687 use iced::keyboard::{Key, Modifiers};
2688
2689 use super::*;
2690 use crate::theme::{dark, light};
2691
2692 fn even(text: &str) -> Result<(), String> {
2693 if text.len().is_multiple_of(2) {
2694 Ok(())
2695 } else {
2696 Err("Needs an even length".to_owned())
2697 }
2698 }
2699
2700 fn sample() -> State<u32> {
2706 State::new([
2707 read_only(1, "Id", "rect-1"),
2708 number(2, "Width", 120.0)
2709 .category("Layout")
2710 .range(0.0, 400.0)
2711 .step(1.0)
2712 .unit("px")
2713 .default(100.0),
2714 number(3, "Height", 0.5)
2715 .category("Layout")
2716 .range(0.0, 1.0)
2717 .step(0.25),
2718 toggle(4, "Visible", true).category("Layout").default(true),
2719 colour(5, "Fill", Color::from_rgb8(0x3b, 0x82, 0xf6))
2720 .category("Appearance")
2721 .default(Color::WHITE),
2722 choice(6, "Blend", ["Normal", "Multiply", "Screen"], "Normal")
2723 .category("Appearance")
2724 .description("How the layer mixes with what is under it."),
2725 text(7, "Label", "Box")
2726 .category("Appearance")
2727 .validate(even),
2728 toggle(8, "Locked", false)
2729 .category("Appearance")
2730 .disabled(true)
2731 .default(true),
2732 ])
2733 }
2734
2735 fn property_entries(ids: &[u32]) -> Vec<Entry<u32>> {
2736 ids.iter().map(|&id| Entry::Property(id)).collect()
2737 }
2738
2739 fn category(name: &str) -> Entry<u32> {
2740 Entry::Category(name.to_owned())
2741 }
2742
2743 fn key(key: Key, modifiers: Modifiers) -> keys::Event {
2744 keys::Event { key, modifiers }
2745 }
2746
2747 fn named(named: Named) -> keys::Event {
2748 key(Key::Named(named), Modifiers::empty())
2749 }
2750
2751 fn changed(id: u32, value: impl Into<Value>) -> Option<Output<u32>> {
2752 Some(Output::Changed {
2753 id,
2754 value: value.into(),
2755 })
2756 }
2757
2758 #[test]
2759 fn lists_uncategorised_properties_first_then_each_category() {
2760 let state = sample();
2761 assert_eq!(state.categories(), ["Layout", "Appearance"]);
2762 let mut expected = vec![Entry::Property(1), category("Layout")];
2763 expected.extend(property_entries(&[2, 3, 4]));
2764 expected.push(category("Appearance"));
2765 expected.extend(property_entries(&[5, 6, 7, 8]));
2766 assert_eq!(state.entries(), expected);
2767 assert_eq!(state.count("Layout"), 3);
2768 }
2769
2770 #[test]
2771 fn alphabetical_lists_every_property_by_name() {
2772 let state = sample().with_sort(Sort::Alphabetical);
2773 assert_eq!(state.entries(), property_entries(&[6, 5, 3, 1, 7, 8, 4, 2]));
2774 assert_eq!(Sort::ALL.len(), 2);
2775 assert_eq!(Sort::default(), Sort::Categorised);
2776 }
2777
2778 #[test]
2779 fn a_repeated_id_replaces_the_earlier_property() {
2780 let state = State::new([text(1, "Old", "a"), text(1, "New", "b")]);
2781 assert_eq!(state.properties().len(), 1);
2782 assert_eq!(state.property(1).map(|p| p.name.as_str()), Some("New"));
2783 assert!(State::<u8>::new([]).entries().is_empty());
2784 }
2785
2786 #[test]
2787 fn the_filter_matches_names_and_drops_empty_categories() {
2788 let mut state = sample();
2789 let _ = state.update(Event::Press(Entry::Property(2)));
2790 let _ = state.update(Event::Search("FI".into()));
2791 assert_eq!(
2792 state.entries(),
2793 vec![category("Appearance"), Entry::Property(5)]
2794 );
2795 assert!(state.matches(5) && !state.matches(2));
2796 assert_eq!(state.count("Layout"), 0);
2797 assert_eq!(
2798 state.highlighted(),
2799 Some(&Entry::Property(5)),
2800 "a hidden highlight moves to the nearest match after it"
2801 );
2802 let _ = state.update(Event::Search("nothing".into()));
2803 assert!(state.entries().is_empty());
2804 assert_eq!(state.highlighted(), None);
2805 }
2806
2807 #[test]
2808 fn searching_keeps_the_highlight_on_the_nearest_shown_property() {
2809 let mut state = sample();
2810 let _ = state.update(Event::Press(Entry::Property(6)));
2811 let _ = state.update(Event::Search("ab".into()));
2812 assert_eq!(
2813 state.highlighted(),
2814 Some(&Entry::Property(7)),
2815 "Label follows Blend"
2816 );
2817 let _ = state.update(Event::Search("la".into()));
2818 assert_eq!(state.highlighted(), Some(&Entry::Property(7)), "stays put");
2819 let _ = state.update(Event::Search("wid".into()));
2820 assert_eq!(
2821 state.highlighted(),
2822 Some(&Entry::Property(2)),
2823 "the last before it when nothing follows"
2824 );
2825
2826 let mut fresh = sample();
2827 let _ = fresh.update(Event::Search("e".into()));
2828 assert_eq!(
2829 fresh.highlighted(),
2830 Some(&Entry::Property(3)),
2831 "typing highlights the first shown property"
2832 );
2833 }
2834
2835 #[test]
2836 fn stepping_through_matches_skips_headings_and_wraps() {
2837 let mut state = sample();
2838 let _ = state.update(Event::Search("e".into()));
2839 let mut visited = Vec::new();
2840 for _ in 0..5 {
2841 let _ = state.update(Event::NextMatch);
2842 visited.push(state.highlighted().cloned());
2843 }
2844 assert_eq!(
2845 visited,
2846 [4, 6, 7, 8, 3].map(|id| Some(Entry::Property(id))),
2847 "Height, Visible, Blend, Label and Locked, then back to Height"
2848 );
2849 let _ = state.update(Event::PreviousMatch);
2850 assert_eq!(state.highlighted(), Some(&Entry::Property(8)), "wraps back");
2851
2852 let mut none = sample();
2853 let _ = none.update(Event::Search("nothing".into()));
2854 let _ = none.update(Event::NextMatch);
2855 assert_eq!(none.highlighted(), None);
2856 }
2857
2858 #[test]
2859 fn pressing_a_heading_toggles_it_and_collapsing_lifts_the_highlight() {
2860 let mut state = sample();
2861 let _ = state.update(Event::Press(Entry::Property(3)));
2862 let _ = state.update(Event::Collapse("Layout".into()));
2863 assert!(!state.is_expanded("Layout"));
2864 assert_eq!(state.highlighted(), Some(&category("Layout")));
2865 assert!(!state.entries().contains(&Entry::Property(3)));
2866 let _ = state.update(Event::Press(category("Layout")));
2867 assert!(state.is_expanded("Layout"));
2868 let _ = state.update(Event::ToggleCategory("Layout".into()));
2869 assert!(!state.is_expanded("Layout"));
2870 let _ = state.update(Event::Expand("Layout".into()));
2871 assert!(state.is_expanded("Layout"));
2872 let _ = state.update(Event::Collapse("Missing".into()));
2873 assert!(
2874 state.is_expanded("Missing"),
2875 "unknown categories are ignored"
2876 );
2877 }
2878
2879 #[test]
2880 fn with_collapsed_starts_closed() {
2881 let state = sample().with_collapsed(["Appearance"]);
2882 assert!(!state.is_expanded("Appearance"));
2883 assert_eq!(state.entries().last(), Some(&category("Appearance")));
2884 }
2885
2886 #[test]
2887 fn arrows_walk_the_rows_without_wrapping() {
2888 let mut state = sample();
2889 let _ = state.update(Event::Next);
2890 assert_eq!(state.highlighted(), Some(&Entry::Property(1)));
2891 let _ = state.update(Event::Next);
2892 assert_eq!(state.highlighted(), Some(&category("Layout")));
2893 let _ = state.update(Event::Last);
2894 assert_eq!(state.highlighted(), Some(&Entry::Property(8)));
2895 let _ = state.update(Event::Next);
2896 assert_eq!(state.highlighted(), Some(&Entry::Property(8)));
2897 let _ = state.update(Event::First);
2898 let _ = state.update(Event::Previous);
2899 assert_eq!(state.highlighted(), Some(&Entry::Property(1)));
2900 }
2901
2902 #[test]
2903 fn right_opens_then_enters_and_left_closes_then_leaves() {
2904 let mut state = sample().with_collapsed(["Layout"]);
2905 let _ = state.update(Event::Press(category("Layout")));
2906 assert!(state.is_expanded("Layout"));
2907 let _ = state.update(Event::CollapseOrLeave);
2908 assert!(!state.is_expanded("Layout"));
2909 let _ = state.update(Event::ExpandOrEnter);
2910 assert!(state.is_expanded("Layout"));
2911 let _ = state.update(Event::ExpandOrEnter);
2912 assert_eq!(state.highlighted(), Some(&Entry::Property(2)));
2913 let _ = state.update(Event::CollapseOrLeave);
2914 assert_eq!(state.highlighted(), Some(&category("Layout")));
2915 assert!(state.is_expanded("Layout"), "leaving does not close");
2916 }
2917
2918 #[test]
2919 fn editing_text_starts_a_draft_and_asks_for_focus() {
2920 let mut state = sample();
2921 assert!(state.update(Event::Edit(2)).is_none());
2922 assert_eq!(state.editing(), Some(2));
2923 assert_eq!(state.draft(2).map(|d| d.text.as_str()), Some("120"));
2924 assert_eq!(state.highlighted(), Some(&Entry::Property(2)));
2925 assert_eq!(state.focus_request(), Some((1, Target::Editor)));
2926 let _ = state.update(Event::Edit(2));
2927 assert_eq!(state.focus_request(), Some((2, Target::Editor)));
2928 }
2929
2930 #[test]
2931 fn a_valid_edit_changes_the_value_as_it_is_typed() {
2932 let mut state = sample();
2933 let _ = state.update(Event::Edit(2));
2934 assert_eq!(state.update(Event::Input(2, "12".into())), changed(2, 12.0));
2935 assert_eq!(state.update(Event::Input(2, "12px".into())), None);
2936 assert_eq!(state.value(2), Some(&Value::Number(12.0)));
2937 let _ = state.update(Event::Submit);
2938 assert_eq!(state.editing(), None);
2939 assert!(state.draft(2).is_none());
2940 }
2941
2942 #[test]
2943 fn an_invalid_edit_keeps_its_draft_and_error() {
2944 let mut state = sample();
2945 let _ = state.update(Event::Edit(2));
2946 assert_eq!(state.update(Event::Input(2, "9000".into())), None);
2947 assert_eq!(state.error(2), Some("Must be at most 400px"));
2948 assert_eq!(state.value(2), Some(&Value::Number(120.0)));
2949 let _ = state.update(Event::Submit);
2950 assert_eq!(
2951 state.editing(),
2952 Some(2),
2953 "Enter does not leave an invalid edit"
2954 );
2955
2956 let _ = state.update(Event::Press(Entry::Property(3)));
2957 assert_eq!(state.editing(), None);
2958 assert_eq!(
2959 state.draft(2).map(|d| d.text.as_str()),
2960 Some("9000"),
2961 "the invalid draft stays after leaving"
2962 );
2963 assert_eq!(state.update(Event::Input(2, "40".into())), changed(2, 40.0));
2964 assert_eq!(state.editing(), Some(2), "typing again resumes the edit");
2965 assert_eq!(state.error(2), None);
2966 }
2967
2968 #[test]
2969 fn leaving_a_valid_edit_drops_its_draft() {
2970 let mut state = sample();
2971 let _ = state.update(Event::Edit(7));
2972 let _ = state.update(Event::Input(7, "Card".into()));
2973 let _ = state.update(Event::Focus(false));
2974 assert_eq!(state.editing(), None);
2975 assert!(state.draft(7).is_none());
2976 assert_eq!(state.value(7), Some(&Value::from("Card")));
2977 }
2978
2979 #[test]
2980 fn cancel_puts_back_the_value_from_before_the_edit() {
2981 let mut state = sample();
2982 let _ = state.update(Event::Edit(7));
2983 let _ = state.update(Event::Input(7, "Card".into()));
2984 let _ = state.update(Event::Input(7, "Car".into()));
2985 assert_eq!(state.error(7), Some("Needs an even length"));
2986 assert_eq!(state.update(Event::Cancel), changed(7, "Box"));
2987 assert_eq!(state.editing(), None);
2988 assert!(state.draft(7).is_none());
2989
2990 let _ = state.update(Event::Edit(7));
2991 assert_eq!(state.update(Event::Cancel), None, "nothing changed");
2992 }
2993
2994 #[test]
2995 fn cancel_without_an_edit_clears_the_search() {
2996 let mut state = sample();
2997 let _ = state.update(Event::Search("wid".into()));
2998 let _ = state.update(Event::Cancel);
2999 assert_eq!(state.query(), "");
3000 }
3001
3002 #[test]
3003 fn edit_flips_toggles_and_steps_choices() {
3004 let mut state = sample();
3005 assert_eq!(state.update(Event::Edit(4)), changed(4, false));
3006 assert_eq!(state.editing(), None);
3007 assert_eq!(state.update(Event::Edit(6)), changed(6, "Multiply"));
3008 let _ = state.update(Event::Edit(6));
3009 assert_eq!(
3010 state.update(Event::Edit(6)),
3011 changed(6, "Normal"),
3012 "wraps round"
3013 );
3014 }
3015
3016 #[test]
3017 fn read_only_and_disabled_properties_do_not_edit() {
3018 let mut state = sample();
3019 assert_eq!(state.update(Event::Edit(1)), None);
3020 assert_eq!(state.editing(), None);
3021 assert_eq!(state.update(Event::Edit(8)), None);
3022 assert_eq!(state.update(Event::Set(8, Value::Bool(true))), None);
3023 assert_eq!(state.update(Event::Input(8, "x".into())), None);
3024 assert_eq!(state.update(Event::Reset(8)), None);
3025 assert_eq!(state.highlighted(), Some(&Entry::Property(8)));
3026 }
3027
3028 #[test]
3029 fn set_accepts_only_values_that_suit_the_property() {
3030 let mut state = sample();
3031 assert_eq!(
3032 state.update(Event::Set(6, "Screen".into())),
3033 changed(6, "Screen")
3034 );
3035 assert_eq!(state.update(Event::Set(6, "Overlay".into())), None);
3036 assert_eq!(state.update(Event::Set(6, Value::Bool(true))), None);
3037 assert_eq!(
3038 state.update(Event::Set(4, Value::Bool(true))),
3039 None,
3040 "unchanged"
3041 );
3042 assert_eq!(state.update(Event::Set(99, Value::Bool(true))), None);
3043 }
3044
3045 #[test]
3046 fn the_menu_disables_reset_on_a_property_at_its_default() {
3047 let disabled = |menu: &context_menu::State<MenuItem, u32>, item| {
3048 menu.menu().item(item).is_some_and(|item| item.disabled)
3049 };
3050 let mut state = sample();
3051 let mut menu = menu();
3052 let _ = menu.update(context_menu::Event::OpenFromKeyboard(2));
3053 sync_menu(&mut menu, &state);
3054 assert!(state.can_reset(2));
3055 assert!(!disabled(&menu, MenuItem::Reset));
3056 assert!(!disabled(&menu, MenuItem::CopyValue));
3057
3058 let _ = state.update(Event::Reset(2));
3059 sync_menu(&mut menu, &state);
3060 assert!(!state.can_reset(2));
3061 assert!(disabled(&menu, MenuItem::Reset));
3062 assert!(!disabled(&menu, MenuItem::CopyValue));
3063 assert!(!state.can_reset(8), "disabled");
3064 }
3065
3066 #[test]
3067 fn reset_puts_back_the_default() {
3068 let mut state = sample();
3069 assert!(state.property(2).is_some_and(Property::is_modified));
3070 assert_eq!(
3071 state.update(Event::Reset(2)),
3072 Some(Output::Reset {
3073 id: 2,
3074 value: Value::Number(100.0)
3075 })
3076 );
3077 assert!(!state.property(2).is_some_and(Property::is_modified));
3078 assert_eq!(state.update(Event::Reset(2)), None, "already the default");
3079 assert_eq!(state.update(Event::Reset(3)), None, "no default");
3080 }
3081
3082 #[test]
3083 fn reset_drops_an_invalid_draft() {
3084 let mut state = sample();
3085 let _ = state.update(Event::Edit(2));
3086 let _ = state.update(Event::Input(2, "abc".into()));
3087 let _ = state.update(Event::Press(Entry::Property(2)));
3088 let _ = state.update(Event::ResetHighlighted);
3089 assert!(state.draft(2).is_none());
3090 assert_eq!(state.editing(), None);
3091 assert_eq!(state.value(2), Some(&Value::Number(100.0)));
3092 }
3093
3094 #[test]
3095 fn up_and_down_step_the_number_being_edited() {
3096 let mut state = sample();
3097 let _ = state.update(Event::Edit(3));
3098 assert_eq!(state.update(Event::Increment), changed(3, 0.75));
3099 assert_eq!(state.update(Event::Increment), changed(3, 1.0));
3100 assert_eq!(state.update(Event::Increment), None, "clamped to the max");
3101 assert_eq!(state.draft(3).map(|d| d.text.as_str()), Some("1.00"));
3102 assert_eq!(state.update(Event::Decrement), changed(3, 0.75));
3103 let _ = state.update(Event::Submit);
3104 assert_eq!(state.update(Event::Increment), None, "only while editing");
3105 }
3106
3107 #[test]
3108 fn numbers_parse_with_their_unit_and_limits() {
3109 let number = Number {
3110 min: Some(0.0),
3111 max: Some(100.0),
3112 step: Some(5.0),
3113 decimals: None,
3114 unit: Some("%".into()),
3115 };
3116 assert_eq!(number.parse(" 25% "), Ok(25.0));
3117 assert_eq!(number.parse("25"), Ok(25.0));
3118 assert_eq!(number.parse("-5"), Err("Must be at least 0%".into()));
3119 assert_eq!(number.parse("105"), Err("Must be at most 100%".into()));
3120 assert_eq!(number.parse("12"), Err("Must be a multiple of 5".into()));
3121 assert_eq!(number.parse("abc"), Err("Enter a number".into()));
3122 assert_eq!(number.parse("inf"), Err("Enter a number".into()));
3123 assert_eq!(number.display(25.0), "25%");
3124 assert_eq!(number.stepped(98.0, true), 100.0);
3125
3126 let whole = Number {
3127 step: Some(1.0),
3128 ..Number::default()
3129 };
3130 assert_eq!(whole.parse("1.5"), Err("Must be a whole number".into()));
3131 let fine = Number {
3132 step: Some(0.1),
3133 ..Number::default()
3134 };
3135 assert_eq!(
3136 fine.parse("0.15"),
3137 Ok(0.15),
3138 "fractional steps do not validate"
3139 );
3140 assert_eq!(fine.format(0.15), "0.1");
3141 assert_eq!(fine.stepped(0.2, true), 0.3);
3142 assert_eq!(Number::default().format(-0.0), "0");
3143 assert_eq!(Number::default().format(2.5), "2.5");
3144 let fixed = Number {
3145 decimals: Some(2),
3146 ..Number::default()
3147 };
3148 assert_eq!(fixed.format(1.0), "1.00");
3149 }
3150
3151 #[test]
3152 fn hex_colours_round_trip() {
3153 let blue = Color::from_rgb8(0x3b, 0x82, 0xf6);
3154 assert_eq!(hex(blue), "#3B82F6");
3155 assert_eq!(parse_hex("#3b82f6"), Ok(blue));
3156 assert_eq!(parse_hex("3B82F6"), Ok(blue));
3157 assert_eq!(parse_hex("#fff"), Ok(Color::WHITE));
3158 assert_eq!(parse_hex(" #000 "), Ok(Color::BLACK));
3159 let faded = parse_hex("#00000080").map(hex);
3160 assert_eq!(faded, Ok("#00000080".to_owned()));
3161 assert_eq!(parse_hex("#0008").map(hex), Ok("#00000088".to_owned()));
3162 for bad in ["", "#", "#12", "#12345", "#ggg", "blue", "#3B82F6F6F6"] {
3163 assert!(parse_hex(bad).is_err(), "{bad}");
3164 }
3165 }
3166
3167 #[test]
3168 fn colour_edits_parse_hex() {
3169 let mut state = sample();
3170 let _ = state.update(Event::Edit(5));
3171 assert_eq!(state.draft(5).map(|d| d.text.as_str()), Some("#3B82F6"));
3172 assert_eq!(state.update(Event::Input(5, "#zz".into())), None);
3173 assert!(state.error(5).is_some());
3174 assert_eq!(
3175 state.update(Event::Input(5, "#fff".into())),
3176 changed(5, Color::WHITE)
3177 );
3178 assert!(!state.property(5).is_some_and(Property::is_modified));
3179 }
3180
3181 #[test]
3182 fn property_text_and_parsing_follow_the_kind() {
3183 let state = sample();
3184 let show = |id| {
3185 state
3186 .property(id)
3187 .map(Property::display)
3188 .unwrap_or_default()
3189 };
3190 assert_eq!(show(2), "120px");
3191 assert_eq!(show(3), "0.50");
3192 assert_eq!(show(4), "On");
3193 assert_eq!(show(5), "#3B82F6");
3194 assert_eq!(
3195 state.property(2).map(Property::edit_text),
3196 Some("120".into())
3197 );
3198 let blend = state.property(6).map(|p| p.parse("Screen"));
3199 assert_eq!(blend, Some(Ok(Value::from("Screen"))));
3200 assert!(state.property(6).is_some_and(|p| p.parse("Nope").is_err()));
3201 assert!(state.property(1).is_some_and(|p| !p.is_editable()));
3202 assert!(state.property(8).is_some_and(|p| !p.is_editable()));
3203 assert!(state.property(4).is_some_and(|p| !p.is_typed()));
3204 let shown = custom::<u8>(1, "Opacity", 0.5);
3205 assert_eq!(shown.display(), "0.5");
3206 assert!(shown.accepts(&Value::Bool(true)));
3207 assert_eq!(Toggle::ALL.len(), 2);
3208 }
3209
3210 #[test]
3211 fn number_settings_only_apply_to_numbers() {
3212 let label = text::<u8>(1, "Label", "a").min(1.0).unit("px").switch();
3213 assert!(matches!(label.kind, Kind::Text(None)));
3214 let flag = toggle::<u8>(2, "Flag", true).switch();
3215 assert!(matches!(flag.kind, Kind::Toggle(Toggle::Switch)));
3216 let size = number::<u8>(3, "Size", 1.0).decimals(1).validate(even);
3217 assert!(matches!(
3218 size.kind,
3219 Kind::Number(Number {
3220 decimals: Some(1),
3221 ..
3222 })
3223 ));
3224 }
3225
3226 #[test]
3227 fn values_convert_and_read_back() {
3228 assert_eq!(Value::from(2).as_number(), Some(2.0));
3229 assert_eq!(Value::from(0.5f32).as_number(), Some(0.5));
3230 assert_eq!(Value::from("a").as_text(), Some("a"));
3231 assert_eq!(Value::from(String::from("b")).as_text(), Some("b"));
3232 assert_eq!(Value::from(true).as_bool(), Some(true));
3233 assert_eq!(Value::from(Color::BLACK).as_colour(), Some(Color::BLACK));
3234 assert_eq!(Value::from(true).as_text(), None);
3235 assert_eq!(Value::from("a").as_number(), None);
3236 assert_eq!(Value::from("a").as_bool(), None);
3237 assert_eq!(Value::from("a").as_colour(), None);
3238 }
3239
3240 #[test]
3241 fn set_from_the_app_drops_the_edit() {
3242 let mut state = sample();
3243 let _ = state.update(Event::Edit(7));
3244 assert!(state.set(7, "Card"));
3245 assert_eq!(state.editing(), None);
3246 assert!(state.draft(7).is_none());
3247 assert!(!state.set(7, "Card"));
3248 assert!(!state.set(99, "Card"));
3249 }
3250
3251 #[test]
3252 fn the_name_column_drags_only_while_resizing() {
3253 let mut state = sample().with_name_width(10.0);
3254 assert_eq!(state.name_width(), Some(MIN_NAME_WIDTH));
3255 let _ = state.update(Event::Resize(150.0));
3256 assert_eq!(state.name_width(), Some(MIN_NAME_WIDTH));
3257 let _ = state.update(Event::ResizeStart);
3258 assert!(state.is_resizing());
3259 let _ = state.update(Event::Resize(150.0));
3260 assert_eq!(state.name_width(), Some(150.0));
3261 let _ = state.update(Event::Resize(2.0));
3262 assert_eq!(state.name_width(), Some(MIN_NAME_WIDTH));
3263 let _ = state.update(Event::ResizeEnd);
3264 assert!(!state.is_resizing());
3265 }
3266
3267 #[test]
3268 fn the_name_column_keeps_room_for_values() {
3269 assert_eq!(name_width(None, 600.0), NAME_WIDTH);
3270 let narrow = name_width(None, 260.0);
3271 let room = 260.0 - HANDLE_WIDTH - RESET_WIDTH;
3272 assert_eq!(narrow, room - VALUE_WIDTH, "the values give way first");
3273 assert!(narrow > room * 0.45, "names keep a fair share");
3274 assert_eq!(
3275 name_width(None, 300.0 + NAME_WIDTH),
3276 NAME_WIDTH,
3277 "values only give way when room runs short"
3278 );
3279 assert_eq!(
3280 name_width(Some(500.0), 300.0),
3281 300.0 - HANDLE_WIDTH - RESET_WIDTH - MIN_VALUE_WIDTH
3282 );
3283 assert_eq!(name_width(Some(10.0), 300.0), MIN_NAME_WIDTH);
3284 assert_eq!(
3285 name_width(None, 100.0),
3286 MIN_NAME_WIDTH,
3287 "never below the minimum"
3288 );
3289 }
3290
3291 #[test]
3292 fn focus_highlights_the_first_property_and_losing_it_ends_edits() {
3293 let mut state = sample();
3294 let _ = state.update(Event::Focus(true));
3295 assert!(state.is_focused());
3296 assert_eq!(state.highlighted(), Some(&Entry::Property(1)));
3297 let _ = state.update(Event::Edit(2));
3298 let _ = state.update(Event::ResizeStart);
3299 let _ = state.update(Event::Focus(false));
3300 assert_eq!(state.editing(), None);
3301 assert!(!state.is_resizing());
3302 }
3303
3304 #[test]
3305 fn focus_search_asks_for_the_filter_box() {
3306 let mut state = sample();
3307 let _ = state.update(Event::Edit(7));
3308 let _ = state.update(Event::FocusSearch);
3309 assert_eq!(state.editing(), None);
3310 assert_eq!(state.focus_request(), Some((2, Target::Filter)));
3311 let _ = state.update(Event::Sort(Sort::Alphabetical));
3312 assert_eq!(state.sort(), Sort::Alphabetical);
3313 }
3314
3315 #[test]
3316 fn copying_gives_the_value_as_shown_and_highlights_it() {
3317 let mut state = sample();
3318 assert_eq!(
3319 state.update(Event::CopyValue(2)),
3320 Some(Output::CopyValue("120px".into()))
3321 );
3322 assert_eq!(state.highlighted(), Some(&Entry::Property(2)));
3323 assert_eq!(
3324 state.update(Event::CopyValue(5)),
3325 Some(Output::CopyValue("#3B82F6".into()))
3326 );
3327 assert_eq!(state.update(Event::CopyValue(99)), None);
3328 }
3329
3330 #[test]
3331 fn menu_items_map_to_events() {
3332 assert_eq!(MenuItem::ALL.len(), 2);
3333 assert_eq!(MenuItem::CopyValue.event(4), Event::CopyValue(4));
3334 assert_eq!(MenuItem::Reset.event(4), Event::Reset(4));
3335 assert!(!menu::<u32>().is_open());
3336 }
3337
3338 #[test]
3339 fn the_match_label_counts_what_passes_the_search() {
3340 let mut state = sample();
3341 assert_eq!(match_label(&state), "");
3342 let _ = state.update(Event::Search("i".into()));
3343 assert_eq!(
3344 match_label(&state),
3345 "1 of 5",
3346 "Id, Width, Height, Visible, Fill, with Id highlighted"
3347 );
3348 let _ = state.update(Event::NextMatch);
3349 assert_eq!(match_label(&state), "2 of 5");
3350 let _ = state.update(Event::PreviousMatch);
3351 let _ = state.update(Event::PreviousMatch);
3352 assert_eq!(match_label(&state), "5 of 5", "wraps to Fill");
3353 let _ = state.update(Event::ToggleCategory("Layout".into()));
3354 assert_eq!(
3355 match_label(&state),
3356 "2 of 2",
3357 "a closed category's properties are not shown"
3358 );
3359 let _ = state.update(Event::Search("zebra".into()));
3360 assert_eq!(match_label(&state), "None");
3361 }
3362
3363 #[test]
3364 fn default_keymap_resolves_each_action() {
3365 let keymap = default_keymap();
3366 let cases = [
3367 (named(Named::ArrowDown), Action::Next),
3368 (named(Named::ArrowUp), Action::Previous),
3369 (named(Named::Home), Action::First),
3370 (named(Named::End), Action::Last),
3371 (named(Named::ArrowRight), Action::Expand),
3372 (named(Named::ArrowLeft), Action::Collapse),
3373 (named(Named::Enter), Action::Edit),
3374 (named(Named::F2), Action::Edit),
3375 (named(Named::Escape), Action::Cancel),
3376 (named(Named::Delete), Action::Reset),
3377 (
3378 key(Key::Character("c".into()), Modifiers::COMMAND),
3379 Action::CopyValue,
3380 ),
3381 (
3382 key(Key::Character("f".into()), Modifiers::COMMAND),
3383 Action::FocusSearch,
3384 ),
3385 ];
3386 for (press, action) in cases {
3387 assert_eq!(keymap.resolve_event(&press), Some(action), "{press:?}");
3388 }
3389 for action in <Action as keys::Action>::ALL {
3390 assert!(!keymap.chords(action).is_empty(), "{action:?} unbound");
3391 assert!(keys::Action::description(*action).ends_with('.'));
3392 assert!(!keys::Action::name(*action).is_empty());
3393 }
3394 }
3395
3396 #[test]
3397 fn keymaps_can_be_changed() {
3398 let keymap = default_keymap()
3399 .bind(Chord::character('j'), Action::Next)
3400 .unbind(&Chord::named(Named::Delete));
3401 let mut state = sample();
3402 let _ = state.update(Event::Focus(true));
3403 let j = key(Key::Character("j".into()), Modifiers::empty());
3404 assert_eq!(state.key_event(&keymap, &j), Some(Event::Next));
3405 let _ = state.update(Event::Press(Entry::Property(2)));
3406 assert_eq!(state.key_event(&keymap, &named(Named::Delete)), None);
3407 assert_eq!(
3408 state.key_event(&default_keymap(), &named(Named::Delete)),
3409 Some(Event::ResetHighlighted)
3410 );
3411 }
3412
3413 #[test]
3414 fn actions_leave_keys_they_cannot_use() {
3415 let mut state = sample();
3416 assert_eq!(Action::Edit.event(&state), None, "nothing highlighted");
3417 assert_eq!(Action::Cancel.event(&state), None);
3418 assert_eq!(Action::FocusSearch.event(&state), Some(Event::FocusSearch));
3419 assert_eq!(Action::CopyValue.event(&state), None);
3420
3421 let _ = state.update(Event::Press(Entry::Property(1)));
3422 assert_eq!(Action::CopyValue.event(&state), Some(Event::CopyValue(1)));
3423 assert_eq!(Action::Edit.event(&state), None, "read-only");
3424 assert_eq!(Action::Expand.event(&state), None);
3425 assert_eq!(Action::Collapse.event(&state), None, "no category");
3426 assert_eq!(Action::Reset.event(&state), None);
3427
3428 let _ = state.update(Event::Press(Entry::Property(3)));
3429 assert_eq!(Action::Collapse.event(&state), Some(Event::CollapseOrLeave));
3430 assert_eq!(Action::Reset.event(&state), None, "no default");
3431 assert_eq!(Action::Edit.event(&state), Some(Event::EditHighlighted));
3432 let _ = state.update(Event::EditHighlighted);
3433 assert_eq!(Action::Next.event(&state), Some(Event::Decrement));
3434 assert_eq!(Action::Previous.event(&state), Some(Event::Increment));
3435 assert_eq!(Action::Cancel.event(&state), Some(Event::Cancel));
3436
3437 let _ = state.update(Event::Press(Entry::Property(2)));
3438 assert_eq!(Action::Next.event(&state), Some(Event::Next));
3439 assert_eq!(Action::Reset.event(&state), Some(Event::ResetHighlighted));
3440
3441 let _ = state.update(Event::Press(category("Layout")));
3442 assert_eq!(Action::Expand.event(&state), Some(Event::ExpandOrEnter));
3443 assert_eq!(Action::Edit.event(&state), Some(Event::EditHighlighted));
3444 let _ = state.update(Event::EditHighlighted);
3445 assert!(state.is_expanded("Layout"), "Enter toggles a heading");
3446
3447 let mut alphabetical = sample().with_sort(Sort::Alphabetical);
3448 let _ = alphabetical.update(Event::Press(Entry::Property(3)));
3449 assert_eq!(Action::Collapse.event(&alphabetical), None);
3450 }
3451
3452 #[test]
3453 fn rows_resolve_their_colours_in_both_themes() {
3454 for theme in [light(), dark()] {
3455 let tokens = Tokens::of(&theme);
3456 let idle = row_style(&tokens, Status::default());
3457 assert_eq!(idle.background, None);
3458 assert_eq!(idle.text, tokens.foreground);
3459 assert_eq!(idle.ring, None);
3460
3461 let highlighted = Status {
3462 highlighted: true,
3463 ..Status::default()
3464 };
3465 assert_eq!(
3466 row_style(&tokens, highlighted).background,
3467 None,
3468 "nothing is selected, so the highlight has no fill"
3469 );
3470 assert_eq!(
3471 row_style(&tokens, highlighted).ring,
3472 None,
3473 "no ring unfocused"
3474 );
3475 let focused = Status {
3476 focused: true,
3477 ..highlighted
3478 };
3479 assert_eq!(row_style(&tokens, focused).ring, Some(tokens.ring));
3480 let focused_heading = Status {
3481 heading: true,
3482 ..focused
3483 };
3484 assert_eq!(
3485 row_style(&tokens, focused_heading).background,
3486 Some(fade(tokens.muted, 0.6)),
3487 "a highlighted heading keeps its band and adds the ring"
3488 );
3489 assert_eq!(row_style(&tokens, focused_heading).ring, Some(tokens.ring));
3490
3491 let hovered = Status {
3492 hovered: true,
3493 ..Status::default()
3494 };
3495 assert_eq!(
3496 row_style(&tokens, hovered).background,
3497 Some(fade(tokens.accent, 0.6))
3498 );
3499 let disabled = Status {
3500 disabled: true,
3501 ..hovered
3502 };
3503 assert_eq!(row_style(&tokens, disabled).background, None);
3504 assert_eq!(row_style(&tokens, disabled).text, tokens.muted_foreground);
3505
3506 let heading = Status {
3507 heading: true,
3508 ..Status::default()
3509 };
3510 assert_eq!(
3511 row_style(&tokens, heading).background,
3512 Some(fade(tokens.muted, 0.6))
3513 );
3514 assert_eq!(
3515 row_style(
3516 &tokens,
3517 Status {
3518 hovered: true,
3519 ..heading
3520 }
3521 )
3522 .background,
3523 Some(tokens.muted)
3524 );
3525
3526 assert_eq!(value_colour(&tokens, true), tokens.foreground);
3527 assert_eq!(value_colour(&tokens, false), tokens.muted_foreground);
3528 assert_eq!(mark_colour(&tokens), tokens.primary);
3529 assert_eq!(divider_colour(&tokens, true), tokens.ring);
3530 assert_ne!(divider_colour(&tokens, false), tokens.ring);
3531 assert_eq!(frame_style(&tokens).border.color, tokens.border);
3532 let swatch = swatch_style(&tokens, Color::WHITE);
3533 assert_eq!(swatch.background, Some(Background::Color(Color::WHITE)));
3534 assert_eq!(swatch.border.color, swatch_ring(&tokens));
3535 }
3536 }
3537
3538 #[test]
3539 fn swatches_keep_a_visible_ring_on_a_dark_background() {
3540 let tokens = Tokens::of(&dark());
3541 let ring = swatch_ring(&tokens);
3542 let near_black = Color::from_rgb8(0x18, 0x18, 0x1b);
3543 let lift = |colour: Color| colour.r + colour.g + colour.b;
3544 assert!(
3545 lift(ring) - lift(near_black) > 0.6,
3546 "{ring:?} stands out from {near_black:?}"
3547 );
3548 assert!(lift(ring) > lift(tokens.border), "stronger than the border");
3549 }
3550
3551 #[test]
3552 fn the_builder_starts_with_the_toolbar_and_description() {
3553 let state = sample();
3554 let grid: PropertyGrid<'_, u32, ()> = property_grid(&state);
3555 assert!(grid.toolbar && grid.description);
3556 assert!(!grid.is_enabled());
3557 assert_eq!(grid.height, Length::Shrink);
3558 let grid = grid
3559 .toolbar(false)
3560 .description(false)
3561 .placeholder("Search")
3562 .height(200)
3563 .keymap(Keymap::new())
3564 .custom(1, |_| Space::new().into())
3565 .custom(1, |_| Space::new().into())
3566 .on_event(|_| ());
3567 assert!(grid.is_enabled());
3568 assert_eq!(
3569 grid.customs.len(),
3570 1,
3571 "a second renderer replaces the first"
3572 );
3573 assert!(format!("{grid:?}").contains("Search"));
3574 }
3575}