1use std::collections::{BTreeSet, HashMap, HashSet};
9
10use crate::collection::Collection;
11use crate::component::WindowConfig;
12use crate::control::WindowCommand;
13use std::sync::{Mutex, OnceLock};
14
15#[cfg(feature = "image-support")]
16use std::sync::{
17 Arc,
18 atomic::{AtomicU64, Ordering},
19};
20
21pub fn intern_key(key: &str) -> &'static str {
29 fn pool() -> &'static Mutex<HashMap<String, &'static str>> {
30 static POOL: OnceLock<Mutex<HashMap<String, &'static str>>> = OnceLock::new();
31 POOL.get_or_init(|| Mutex::new(HashMap::new()))
32 }
33 let mut pool = pool()
34 .lock()
35 .unwrap_or_else(|poisoned| poisoned.into_inner());
36 if let Some(existing) = pool.get(key) {
37 return existing;
38 }
39 let leaked: &'static str = Box::leak(key.to_owned().into_boxed_str());
40 pool.insert(leaked.to_owned(), leaked);
41 leaked
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum MouseButton {
47 Left,
49 Right,
51 Middle,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct KeyInfo {
58 pub key: String,
60 pub shift: bool,
62 pub ctrl: bool,
64 pub alt: bool,
66}
67
68impl KeyInfo {
69 pub fn new(key: impl Into<String>, shift: bool, ctrl: bool, alt: bool) -> Self {
71 Self {
72 key: key.into(),
73 shift,
74 ctrl,
75 alt,
76 }
77 }
78}
79
80#[derive(Debug, Clone, PartialEq)]
82pub enum Event {
83 Click,
85 Dblclick,
87 Mousedown(MouseButton),
89 Mouseup(MouseButton),
91 Mouseenter,
93 Mouseleave,
95 Mousemove {
97 x: f32,
99 y: f32,
101 },
102 Keydown(KeyInfo),
104 Keyup(KeyInfo),
106 TextChange(String),
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Default)]
112pub enum Size {
113 #[default]
115 Auto,
116 Px(f32),
118 Percent(f32),
120}
121
122impl Size {
123 pub fn resolve(self, content: f32, available: f32) -> f32 {
126 let value = match self {
127 Size::Auto => content,
128 Size::Px(value) => value,
129 Size::Percent(percent) => available * percent / 100.0,
130 };
131 value.max(0.0)
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
141pub enum Align {
142 #[default]
144 Start,
145 Center,
147 End,
149}
150
151#[derive(Debug, Clone, Copy, PartialEq)]
156pub enum Offset {
157 Px(f32),
159 Percent(f32),
162}
163
164impl Offset {
165 pub fn resolve(self, available: f32) -> f32 {
167 match self {
168 Offset::Px(value) => value,
169 Offset::Percent(percent) => available * percent / 100.0,
170 }
171 }
172}
173
174impl Default for Offset {
175 fn default() -> Self {
176 Offset::Px(0.0)
177 }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
188pub enum Overflow {
189 #[default]
191 Visible,
192 Hidden,
194 Auto,
196 Scroll,
198}
199
200impl Overflow {
201 pub const fn clips(self) -> bool {
203 !matches!(self, Overflow::Visible)
204 }
205
206 pub const fn scrollable(self) -> bool {
208 matches!(self, Overflow::Auto | Overflow::Scroll)
209 }
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
218pub enum WhiteSpace {
219 #[default]
221 Normal,
222 Nowrap,
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
228pub enum Position {
229 #[default]
231 Flow,
232 Absolute,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Default)]
243pub struct Edges {
244 pub top: f32,
246 pub right: f32,
248 pub bottom: f32,
250 pub left: f32,
252}
253
254impl Edges {
255 pub const ZERO: Self = Self {
257 top: 0.0,
258 right: 0.0,
259 bottom: 0.0,
260 left: 0.0,
261 };
262
263 pub const fn all(value: f32) -> Self {
265 Self {
266 top: value,
267 right: value,
268 bottom: value,
269 left: value,
270 }
271 }
272
273 pub const fn horizontal(self) -> f32 {
275 self.left + self.right
276 }
277
278 pub const fn vertical(self) -> f32 {
280 self.top + self.bottom
281 }
282
283 pub const fn is_zero(self) -> bool {
285 self.top == 0.0 && self.right == 0.0 && self.bottom == 0.0 && self.left == 0.0
286 }
287
288 pub const fn scaled(self, factor: f32) -> Self {
290 Self {
291 top: self.top * factor,
292 right: self.right * factor,
293 bottom: self.bottom * factor,
294 left: self.left * factor,
295 }
296 }
297
298 pub const fn plus(self, other: Self) -> Self {
300 Self {
301 top: self.top + other.top,
302 right: self.right + other.right,
303 bottom: self.bottom + other.bottom,
304 left: self.left + other.left,
305 }
306 }
307}
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
311pub enum Resize {
312 #[default]
314 None,
315 Horizontal,
317 Vertical,
319 Both,
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
325pub enum ButtonType {
326 #[default]
328 Submit,
329 Button,
331 Reset,
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
341pub enum Cursor {
342 #[default]
344 Default,
345 Pointer,
347 Text,
349 NotAllowed,
351 Wait,
353 Progress,
355 Help,
357 Crosshair,
359 Move,
361 Grab,
363 Grabbing,
365 EwResize,
367 NsResize,
369 NeswResize,
371 NwseResize,
373}
374
375impl Cursor {
376 pub fn from_name(name: &str) -> Option<Self> {
381 match name.trim().to_ascii_lowercase().as_str() {
382 "default" => Some(Self::Default),
383 "pointer" => Some(Self::Pointer),
384 "text" => Some(Self::Text),
385 "not-allowed" => Some(Self::NotAllowed),
386 "wait" => Some(Self::Wait),
387 "progress" => Some(Self::Progress),
388 "help" => Some(Self::Help),
389 "crosshair" => Some(Self::Crosshair),
390 "move" => Some(Self::Move),
391 "grab" => Some(Self::Grab),
392 "grabbing" => Some(Self::Grabbing),
393 "ew-resize" => Some(Self::EwResize),
394 "ns-resize" => Some(Self::NsResize),
395 "nesw-resize" => Some(Self::NeswResize),
396 "nwse-resize" => Some(Self::NwseResize),
397 _ => None,
398 }
399 }
400}
401
402#[derive(Debug, Clone, Copy, PartialEq, Default)]
404pub enum RequiredIndicator {
405 #[default]
408 Asterisk,
409 None,
411 Accent(u32),
413}
414
415fn size_or_auto_impl(value: &str) -> Option<Size> {
416 let value = value.trim();
417 if value.is_empty() || value.eq_ignore_ascii_case("auto") {
418 return Some(Size::Auto);
419 }
420 if let Some(percent) = value.strip_suffix('%') {
421 return percent.trim().parse::<f32>().ok().map(Size::Percent);
422 }
423 let number = value.strip_suffix("px").unwrap_or(value).trim();
424 number.parse::<f32>().ok().map(Size::Px)
425}
426
427pub fn parse_size_or_auto(value: &str) -> Size {
434 size_or_auto_impl(value).unwrap_or_else(|| {
435 debug_assert!(false, "invalid size value: \"{value}\"");
436 Size::Auto
437 })
438}
439
440fn offset_impl(value: &str) -> Option<Offset> {
441 let value = value.trim();
442 if let Some(percent) = value.strip_suffix('%') {
443 return percent.trim().parse::<f32>().ok().map(Offset::Percent);
444 }
445 let number = value.strip_suffix("px").unwrap_or(value).trim();
446 number.parse::<f32>().ok().map(Offset::Px)
447}
448
449pub fn parse_offset(value: &str) -> Offset {
454 offset_impl(value).unwrap_or_else(|| {
455 debug_assert!(false, "invalid offset value: \"{value}\"");
456 Offset::default()
457 })
458}
459
460fn align_impl(value: &str, start: &str, end: &str) -> Option<Align> {
461 match value.trim().to_ascii_lowercase().as_str() {
462 value if value == start => Some(Align::Start),
463 "center" => Some(Align::Center),
464 value if value == end => Some(Align::End),
465 _ => None,
466 }
467}
468
469pub fn parse_align_x(value: &str) -> Align {
473 align_impl(value, "left", "right").unwrap_or_else(|| {
474 debug_assert!(false, "invalid position-x value: \"{value}\"");
475 Align::Start
476 })
477}
478
479pub fn parse_align_y(value: &str) -> Align {
483 align_impl(value, "top", "bottom").unwrap_or_else(|| {
484 debug_assert!(false, "invalid position-y value: \"{value}\"");
485 Align::Start
486 })
487}
488
489pub fn parse_justify(value: &str) -> Align {
493 align_impl(value, "start", "end").unwrap_or_else(|| {
494 debug_assert!(false, "invalid justify-content value: \"{value}\"");
495 Align::Start
496 })
497}
498
499pub fn parse_align_items(value: &str) -> Align {
503 match align_impl(value, "start", "end") {
504 Some(align) => align,
505 None => {
506 eprintln!("warning: invalid align-items value: {value:?}, using 'start'");
507 Align::Start
508 }
509 }
510}
511
512fn overflow_impl(value: &str) -> Option<Overflow> {
513 match value.trim().to_ascii_lowercase().as_str() {
514 "visible" => Some(Overflow::Visible),
515 "hidden" => Some(Overflow::Hidden),
516 "auto" => Some(Overflow::Auto),
517 "scroll" => Some(Overflow::Scroll),
518 _ => None,
519 }
520}
521
522pub fn parse_overflow(value: &str) -> Overflow {
526 overflow_impl(value).unwrap_or_else(|| {
527 debug_assert!(false, "invalid overflow value: \"{value}\"");
528 Overflow::Visible
529 })
530}
531
532fn white_space_impl(value: &str) -> Option<WhiteSpace> {
533 match value.trim().to_ascii_lowercase().as_str() {
534 "normal" | "wrap" => Some(WhiteSpace::Normal),
535 "nowrap" | "no-wrap" => Some(WhiteSpace::Nowrap),
536 _ => None,
537 }
538}
539
540pub fn parse_white_space(value: &str) -> WhiteSpace {
544 white_space_impl(value).unwrap_or_else(|| {
545 debug_assert!(false, "invalid white-space value: \"{value}\"");
546 WhiteSpace::Normal
547 })
548}
549
550fn position_impl(value: &str) -> Option<Position> {
551 match value.trim().to_ascii_lowercase().as_str() {
552 "flow" | "static" | "relative" => Some(Position::Flow),
553 "absolute" => Some(Position::Absolute),
554 _ => None,
555 }
556}
557
558pub fn parse_position(value: &str) -> Position {
562 position_impl(value).unwrap_or_else(|| {
563 debug_assert!(false, "invalid position value: \"{value}\"");
564 Position::Flow
565 })
566}
567
568fn px_impl(value: &str) -> Option<f32> {
569 let value = value.trim();
570 let number = value.strip_suffix("px").unwrap_or(value).trim();
571 number.parse::<f32>().ok()
572}
573
574pub fn parse_px(value: &str) -> f32 {
577 px_impl(value).unwrap_or_else(|| {
578 debug_assert!(false, "invalid pixel value: \"{value}\"");
579 0.0
580 })
581}
582
583fn color_impl(value: &str) -> Option<u32> {
584 let raw = value.trim();
585 let digits = raw
586 .strip_prefix('#')
587 .or_else(|| raw.strip_prefix("0x"))
588 .unwrap_or(raw);
589 if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
590 return None;
591 }
592 let byte = |text: &str| u8::from_str_radix(text, 16).ok();
593 let (r, g, b, a) = match digits.len() {
594 3 => (
595 byte(&digits[0..1])? * 17,
596 byte(&digits[1..2])? * 17,
597 byte(&digits[2..3])? * 17,
598 0xFF,
599 ),
600 4 => (
601 byte(&digits[0..1])? * 17,
602 byte(&digits[1..2])? * 17,
603 byte(&digits[2..3])? * 17,
604 byte(&digits[3..4])? * 17,
605 ),
606 6 => (
607 byte(&digits[0..2])?,
608 byte(&digits[2..4])?,
609 byte(&digits[4..6])?,
610 0xFF,
611 ),
612 8 => (
613 byte(&digits[0..2])?,
614 byte(&digits[2..4])?,
615 byte(&digits[4..6])?,
616 byte(&digits[6..8])?,
617 ),
618 _ => return None,
619 };
620 Some(((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | a as u32)
621}
622
623pub fn parse_color(value: &str) -> Option<u32> {
627 let parsed = color_impl(value);
628 debug_assert!(
629 parsed.is_some(),
630 "invalid color value: \"{value}\" (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)"
631 );
632 parsed
633}
634
635pub fn parse_bool(value: &str) -> bool {
637 matches!(value.trim(), "true" | "1" | "yes" | "on")
638}
639
640fn required_indicator_impl(value: &str) -> Option<RequiredIndicator> {
641 match value.trim() {
642 "" | "*" => Some(RequiredIndicator::Asterisk),
643 "none" => Some(RequiredIndicator::None),
644 other => color_impl(other).map(RequiredIndicator::Accent),
645 }
646}
647
648pub fn parse_required_indicator(value: &str) -> RequiredIndicator {
652 required_indicator_impl(value).unwrap_or_else(|| {
653 debug_assert!(false, "invalid required-indicator value: \"{value}\"");
654 RequiredIndicator::Asterisk
655 })
656}
657
658fn button_type_impl(value: &str) -> Option<ButtonType> {
659 match value.trim().to_ascii_lowercase().as_str() {
660 "" | "submit" => Some(ButtonType::Submit),
661 "button" => Some(ButtonType::Button),
662 "reset" => Some(ButtonType::Reset),
663 _ => None,
664 }
665}
666
667pub fn parse_button_type(value: &str) -> ButtonType {
671 button_type_impl(value).unwrap_or_else(|| {
672 debug_assert!(false, "invalid button type value: \"{value}\"");
673 ButtonType::Submit
674 })
675}
676
677fn resize_impl(value: &str) -> Option<Resize> {
678 match value.trim().to_ascii_lowercase().as_str() {
679 "" | "none" => Some(Resize::None),
680 "horizontal" => Some(Resize::Horizontal),
681 "vertical" => Some(Resize::Vertical),
682 "both" => Some(Resize::Both),
683 _ => None,
684 }
685}
686
687pub fn parse_resize(value: &str) -> Resize {
691 resize_impl(value).unwrap_or_else(|| {
692 debug_assert!(false, "invalid resize value: \"{value}\"");
693 Resize::None
694 })
695}
696
697#[derive(Debug, Clone, Copy, PartialEq)]
704pub struct Style {
705 pub width: Size,
707 pub height: Size,
709 pub min_width: Option<Size>,
711 pub min_height: Option<Size>,
713 pub max_width: Option<Size>,
715 pub max_height: Option<Size>,
717 pub flex_grow: f32,
720 pub flex_shrink: f32,
723 pub position: Position,
725 pub overflow_x: Overflow,
727 pub overflow_y: Overflow,
729 pub white_space: Option<WhiteSpace>,
732 pub align_x: Align,
734 pub align_y: Align,
736 pub offset_x: Offset,
738 pub offset_y: Offset,
740 pub justify_content: Align,
743 pub align_items: Align,
746 pub padding: Edges,
748 pub margin: Edges,
750 pub background: Option<u32>,
752 pub font_color: Option<u32>,
754 pub font_size: Option<f32>,
756 pub border_color: Option<u32>,
758 pub border_size: f32,
760 pub visible: bool,
763 pub required: bool,
766 pub invalid: bool,
769 pub required_indicator: RequiredIndicator,
771 pub z: i32,
773}
774
775impl Default for Style {
776 fn default() -> Self {
777 Self {
778 width: Size::Auto,
779 height: Size::Auto,
780 min_width: None,
781 min_height: None,
782 max_width: None,
783 max_height: None,
784 flex_grow: 0.0,
785 flex_shrink: 1.0,
786 position: Position::Flow,
787 overflow_x: Overflow::Visible,
788 overflow_y: Overflow::Visible,
789 white_space: None,
790 align_x: Align::Start,
791 align_y: Align::Start,
792 offset_x: Offset::Px(0.0),
793 offset_y: Offset::Px(0.0),
794 justify_content: Align::Start,
795 align_items: Align::Start,
796 padding: Edges::ZERO,
797 margin: Edges::ZERO,
798 background: None,
799 font_color: None,
800 font_size: None,
801 border_color: None,
802 border_size: 0.0,
803 visible: true,
804 required: false,
805 invalid: false,
806 required_indicator: RequiredIndicator::Asterisk,
807 z: 0,
808 }
809 }
810}
811
812impl Style {
813 pub fn inset(&self) -> Edges {
816 self.padding.plus(Edges::all(self.border_size))
817 }
818
819 pub fn resolve_width(&self, content: f32, available: f32) -> f32 {
821 let mut value = self.width.resolve(content, available);
822 if let Some(min) = self.min_width {
823 value = value.max(min.resolve(content, available));
824 }
825 if let Some(max) = self.max_width {
826 value = value.min(max.resolve(content, available));
827 }
828 value.max(0.0)
829 }
830
831 pub fn resolve_height(&self, content: f32, available: f32) -> f32 {
833 let mut value = self.height.resolve(content, available);
834 if let Some(min) = self.min_height {
835 value = value.max(min.resolve(content, available));
836 }
837 if let Some(max) = self.max_height {
838 value = value.min(max.resolve(content, available));
839 }
840 value.max(0.0)
841 }
842}
843
844#[derive(Debug, Clone, PartialEq)]
846pub struct SelectOption {
847 pub label: String,
849 pub value: String,
851}
852
853#[cfg(feature = "image-support")]
854static NEXT_IMAGE_ID: AtomicU64 = AtomicU64::new(1);
855
856#[cfg(feature = "image-support")]
862#[derive(Clone, PartialEq)]
863pub struct ImageData {
864 pub(crate) key: Arc<str>,
865 pub(crate) bytes: Arc<[u8]>,
866 pub(crate) width: u32,
867 pub(crate) height: u32,
868}
869
870#[cfg(all(feature = "image-support", feature = "devtools"))]
871impl serde::Serialize for ImageData {
872 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
873 use serde::ser::SerializeStruct;
876 let mut state = serializer.serialize_struct("ImageData", 3)?;
877 state.serialize_field("width", &self.width)?;
878 state.serialize_field("height", &self.height)?;
879 state.serialize_field("key", &*self.key)?;
880 state.end()
881 }
882}
883
884#[cfg(feature = "image-support")]
885impl ImageData {
886 pub fn from_png(bytes: Vec<u8>) -> crate::Result<Self> {
889 Self::from_png_limited(bytes, 8 * 1024 * 1024, 4096)
890 }
891
892 pub fn from_png_limited(
897 bytes: Vec<u8>,
898 max_bytes: usize,
899 max_dimension: u32,
900 ) -> crate::Result<Self> {
901 if bytes.len() > max_bytes {
902 return Err(crate::Error::Image(format!(
903 "файл слишком большой: {} байт (максимум {max_bytes})",
904 bytes.len()
905 )));
906 }
907 const SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
908 if bytes.len() < 24 || &bytes[..8] != SIGNATURE || &bytes[12..16] != b"IHDR" {
909 return Err(crate::Error::Image(
910 "файл не является PNG с корректным заголовком IHDR".to_owned(),
911 ));
912 }
913 let width = u32::from_be_bytes(bytes[16..20].try_into().unwrap_or_default());
914 let height = u32::from_be_bytes(bytes[20..24].try_into().unwrap_or_default());
915 if width == 0 || height == 0 || width > max_dimension || height > max_dimension {
916 return Err(crate::Error::Image(format!(
917 "недопустимое разрешение {width}x{height} (максимум {max_dimension} px)"
918 )));
919 }
920
921 let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes.as_slice()));
922 decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
923 let mut reader = decoder
924 .read_info()
925 .map_err(|error| crate::Error::Image(error.to_string()))?;
926 let mut buffer = vec![0; reader.output_buffer_size()];
927 reader
928 .next_frame(&mut buffer)
929 .map_err(|error| crate::Error::Image(error.to_string()))?;
930
931 let id = NEXT_IMAGE_ID.fetch_add(1, Ordering::Relaxed);
932 Ok(Self {
933 key: Arc::from(format!("runtime-image-{id}")),
934 bytes: Arc::from(bytes),
935 width,
936 height,
937 })
938 }
939
940 pub fn width(&self) -> u32 {
942 self.width
943 }
944
945 pub fn height(&self) -> u32 {
947 self.height
948 }
949}
950
951#[cfg(feature = "image-support")]
952impl std::fmt::Debug for ImageData {
953 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
954 formatter
955 .debug_struct("ImageData")
956 .field("key", &self.key)
957 .field("bytes", &self.bytes.len())
958 .field("width", &self.width)
959 .field("height", &self.height)
960 .finish()
961 }
962}
963
964#[derive(Debug, Clone, PartialEq)]
969pub enum NodeKind {
970 Column,
972 Row,
974 TitleBar,
977 Window,
980 Text {
982 content: String,
984 },
985 #[cfg(feature = "image-support")]
987 Image {
988 src: &'static str,
990 data: &'static [u8],
992 width: u32,
994 height: u32,
996 alt: String,
998 },
999 #[cfg(feature = "image-support")]
1001 RuntimeImage {
1002 image: ImageData,
1004 alt: String,
1006 },
1007 Button {
1010 disabled: bool,
1012 button_type: ButtonType,
1014 },
1015 TextField {
1018 value: String,
1020 placeholder: String,
1022 disabled: bool,
1024 multiline: bool,
1026 resize: Resize,
1028 masked: bool,
1031 },
1032 #[cfg(feature = "elements-checkbox")]
1034 Checkbox {
1035 label: String,
1037 checked: bool,
1039 disabled: bool,
1041 },
1042 #[cfg(feature = "elements-radio")]
1045 Radio {
1046 label: String,
1048 value: String,
1050 selected: bool,
1053 disabled: bool,
1055 },
1056 #[cfg(feature = "elements-select")]
1058 Select {
1059 value: String,
1061 options: Vec<SelectOption>,
1063 disabled: bool,
1065 },
1066}
1067
1068#[derive(Debug, Clone, PartialEq)]
1074pub struct VElement {
1075 pub key: &'static str,
1077 pub kind: NodeKind,
1079 pub style: Style,
1081 pub tag: &'static str,
1084 pub attrs: Vec<(&'static str, String)>,
1089 pub window: Option<WindowConfig>,
1092 pub children: Vec<VElement>,
1094}
1095
1096impl VElement {
1097 pub fn leaf(key: &'static str, kind: NodeKind) -> Self {
1099 Self {
1100 key,
1101 kind,
1102 style: Style::default(),
1103 tag: "",
1104 attrs: Vec::new(),
1105 window: None,
1106 children: Vec::new(),
1107 }
1108 }
1109
1110 pub fn container(key: &'static str, kind: NodeKind, children: Vec<VElement>) -> Self {
1112 Self {
1113 key,
1114 kind,
1115 style: Style::default(),
1116 tag: "",
1117 attrs: Vec::new(),
1118 window: None,
1119 children,
1120 }
1121 }
1122
1123 pub fn with_style(mut self, style: Style) -> Self {
1125 self.style = style;
1126 self
1127 }
1128
1129 pub fn with_window(mut self, config: WindowConfig) -> Self {
1131 self.window = Some(config);
1132 self
1133 }
1134
1135 pub fn window_config(&self) -> Option<&WindowConfig> {
1137 self.window.as_ref()
1138 }
1139
1140 pub fn with_tag(mut self, tag: &'static str) -> Self {
1142 self.tag = tag;
1143 self
1144 }
1145
1146 pub fn with_attr(mut self, name: &'static str, value: impl Into<String>) -> Self {
1148 self.attrs.push((name, value.into()));
1149 self
1150 }
1151
1152 pub fn with_attrs(mut self, attrs: Vec<(&'static str, String)>) -> Self {
1154 self.attrs = attrs;
1155 self
1156 }
1157
1158 pub fn attr(&self, name: &str) -> Option<&str> {
1160 self.attrs
1161 .iter()
1162 .find(|(key, _)| *key == name)
1163 .map(|(_, value)| value.as_str())
1164 }
1165
1166 pub fn to_json(&self) -> serde_json::Value {
1176 let children: Vec<_> = self.children.iter().map(VElement::to_json).collect();
1177 serde_json::json!({
1178 "tag": self.tag,
1179 "key": self.key,
1180 "attrs": &self.attrs,
1181 "children": children,
1182 })
1183 }
1184
1185 pub fn get(&self, key: &str) -> Option<&VElement> {
1187 if self.key == key {
1188 return Some(self);
1189 }
1190 self.children.iter().find_map(|child| child.get(key))
1191 }
1192
1193 pub fn find_by_tag(&self, tag: &str) -> Option<&VElement> {
1195 if self.tag == tag {
1196 return Some(self);
1197 }
1198 self.children
1199 .iter()
1200 .find_map(|child| child.find_by_tag(tag))
1201 }
1202
1203 pub fn find_by_attr(&self, name: &str, value: &str) -> Option<&VElement> {
1205 if self.attr(name) == Some(value) {
1206 return Some(self);
1207 }
1208 self.children
1209 .iter()
1210 .find_map(|child| child.find_by_attr(name, value))
1211 }
1212
1213 pub fn get_mut(&mut self, key: &str) -> Option<&mut VElement> {
1215 if self.key == key {
1216 return Some(self);
1217 }
1218 self.children
1219 .iter_mut()
1220 .find_map(|child| child.get_mut(key))
1221 }
1222
1223 pub fn content(&self) -> Option<&str> {
1225 match &self.kind {
1226 NodeKind::Text { content } => Some(content),
1227 _ => None,
1228 }
1229 }
1230
1231 pub fn descendants(&self) -> Collection<&VElement> {
1236 let mut nodes = Collection::new();
1237 self.collect_descendants(&mut nodes);
1238 nodes
1239 }
1240
1241 fn collect_descendants<'a>(&'a self, out: &mut Collection<&'a VElement>) {
1242 out.push(self);
1243 for child in &self.children {
1244 child.collect_descendants(out);
1245 }
1246 }
1247
1248 pub fn find_by_content(&self, content: &str) -> Option<&VElement> {
1250 if self.content() == Some(content) {
1251 return Some(self);
1252 }
1253 self.children
1254 .iter()
1255 .find_map(|child| child.find_by_content(content))
1256 }
1257
1258 pub fn find_containing(&self, needle: &str) -> Option<&VElement> {
1260 if self
1261 .content()
1262 .is_some_and(|content| content.contains(needle))
1263 {
1264 return Some(self);
1265 }
1266 self.children
1267 .iter()
1268 .find_map(|child| child.find_containing(needle))
1269 }
1270
1271 fn find_titlebar(&self) -> Option<&VElement> {
1273 if matches!(self.kind, NodeKind::TitleBar) {
1274 return Some(self);
1275 }
1276 self.children.iter().find_map(VElement::find_titlebar)
1277 }
1278
1279 fn collect_plain_text(&self, out: &mut String) {
1281 match &self.kind {
1282 NodeKind::Text { content } => out.push_str(content),
1283 NodeKind::Button { .. } | NodeKind::TextField { .. } => {}
1284 #[cfg(feature = "elements-checkbox")]
1285 NodeKind::Checkbox { .. } => {}
1286 #[cfg(feature = "elements-radio")]
1287 NodeKind::Radio { .. } => {}
1288 #[cfg(feature = "elements-select")]
1289 NodeKind::Select { .. } => {}
1290 _ => {
1291 for child in &self.children {
1292 child.collect_plain_text(out);
1293 }
1294 }
1295 }
1296 }
1297
1298 pub fn collect_plain_text_public(&self, out: &mut String) {
1305 self.collect_plain_text(out)
1306 }
1307
1308 pub fn titlebar_text(&self) -> Option<String> {
1313 let bar = self.find_titlebar()?;
1314 let mut text = String::new();
1315 bar.collect_plain_text(&mut text);
1316 let trimmed = text.trim();
1317 if trimmed.is_empty() {
1318 None
1319 } else {
1320 Some(trimmed.to_owned())
1321 }
1322 }
1323}
1324
1325pub trait VNode {
1331 fn key(&self) -> &'static str;
1333 fn kind(&self) -> &NodeKind;
1335 fn kind_mut(&mut self) -> &mut NodeKind;
1337 fn style(&self) -> &Style;
1339 fn style_mut(&mut self) -> &mut Style;
1341 fn tag(&self) -> &'static str;
1343 fn attrs(&self) -> &[(&'static str, String)];
1345 fn children(&self) -> &[VElement];
1347
1348 fn attr(&self, name: &str) -> Option<&str> {
1350 self.attrs()
1351 .iter()
1352 .find(|(key, _)| *key == name)
1353 .map(|(_, value)| value.as_str())
1354 }
1355
1356 fn text(&self) -> Option<&str> {
1358 match self.kind() {
1359 NodeKind::Text { content } => Some(content),
1360 _ => None,
1361 }
1362 }
1363
1364 fn set_text(&mut self, value: impl Into<String>) {
1366 if let NodeKind::Text { content } = self.kind_mut() {
1367 *content = value.into();
1368 }
1369 }
1370
1371 fn visible(&self) -> bool {
1373 self.style().visible
1374 }
1375
1376 fn set_visible(&mut self, value: bool) {
1378 self.style_mut().visible = value;
1379 }
1380
1381 fn disabled(&self) -> bool {
1383 match self.kind() {
1384 NodeKind::Button { disabled, .. } | NodeKind::TextField { disabled, .. } => *disabled,
1385 #[cfg(feature = "elements-checkbox")]
1386 NodeKind::Checkbox { disabled, .. } => *disabled,
1387 #[cfg(feature = "elements-radio")]
1388 NodeKind::Radio { disabled, .. } => *disabled,
1389 #[cfg(feature = "elements-select")]
1390 NodeKind::Select { disabled, .. } => *disabled,
1391 _ => false,
1392 }
1393 }
1394
1395 fn set_disabled(&mut self, value: bool) {
1397 match self.kind_mut() {
1398 NodeKind::Button { disabled, .. } | NodeKind::TextField { disabled, .. } => {
1399 *disabled = value;
1400 }
1401 #[cfg(feature = "elements-checkbox")]
1402 NodeKind::Checkbox { disabled, .. } => *disabled = value,
1403 #[cfg(feature = "elements-radio")]
1404 NodeKind::Radio { disabled, .. } => *disabled = value,
1405 #[cfg(feature = "elements-select")]
1406 NodeKind::Select { disabled, .. } => *disabled = value,
1407 _ => {}
1408 }
1409 }
1410
1411 fn value(&self) -> Option<&str> {
1413 match self.kind() {
1414 NodeKind::TextField { value, .. } => Some(value),
1415 #[cfg(feature = "elements-select")]
1416 NodeKind::Select { value, .. } => Some(value),
1417 _ => None,
1418 }
1419 }
1420
1421 fn set_value(&mut self, new_value: impl Into<String>) {
1423 let new_value = new_value.into();
1424 match self.kind_mut() {
1425 NodeKind::TextField { value, .. } => {
1426 *value = new_value;
1427 }
1428 #[cfg(feature = "elements-select")]
1429 NodeKind::Select { value, .. } => {
1430 *value = new_value;
1431 }
1432 _ => {}
1433 }
1434 }
1435
1436 fn checked(&self) -> bool {
1438 #[cfg(feature = "elements-checkbox")]
1439 {
1440 matches!(self.kind(), NodeKind::Checkbox { checked: true, .. })
1441 }
1442 #[cfg(not(feature = "elements-checkbox"))]
1443 {
1444 false
1445 }
1446 }
1447
1448 fn set_checked(&mut self, value: bool) {
1450 #[cfg(feature = "elements-checkbox")]
1451 if let NodeKind::Checkbox { checked, .. } = self.kind_mut() {
1452 *checked = value;
1453 }
1454 #[cfg(not(feature = "elements-checkbox"))]
1455 let _ = value;
1456 }
1457
1458 fn selected(&self) -> bool {
1460 #[cfg(feature = "elements-radio")]
1461 {
1462 matches!(self.kind(), NodeKind::Radio { selected: true, .. })
1463 }
1464 #[cfg(not(feature = "elements-radio"))]
1465 {
1466 false
1467 }
1468 }
1469
1470 fn set_selected(&mut self, value: bool) {
1472 #[cfg(feature = "elements-radio")]
1473 if let NodeKind::Radio { selected, .. } = self.kind_mut() {
1474 *selected = value;
1475 }
1476 #[cfg(not(feature = "elements-radio"))]
1477 let _ = value;
1478 }
1479
1480 fn options(&self) -> &[SelectOption] {
1482 match self.kind() {
1483 #[cfg(feature = "elements-select")]
1484 NodeKind::Select { options, .. } => options,
1485 _ => &[],
1486 }
1487 }
1488
1489 fn set_options(&mut self, value: Vec<SelectOption>) {
1491 #[cfg(feature = "elements-select")]
1492 if let NodeKind::Select { options, .. } = self.kind_mut() {
1493 *options = value;
1494 }
1495 #[cfg(not(feature = "elements-select"))]
1496 let _ = value;
1497 }
1498
1499 fn act(&self, command: WindowCommand) {
1502 crate::control::request(command);
1503 }
1504}
1505
1506pub trait VWindow: VNode {
1511 fn config(&self) -> Option<&WindowConfig>;
1513
1514 fn close(&self) {
1516 self.act(WindowCommand::Close);
1517 }
1518
1519 fn minimize(&self) {
1521 self.act(WindowCommand::Minimize);
1522 }
1523
1524 fn maximize(&self) {
1526 self.act(WindowCommand::Maximize);
1527 }
1528
1529 fn restore(&self) {
1531 self.act(WindowCommand::Restore);
1532 }
1533
1534 fn toggle_maximize(&self) {
1536 self.act(WindowCommand::ToggleMaximize);
1537 }
1538
1539 fn show(&self) {
1541 self.act(WindowCommand::Show);
1542 }
1543
1544 fn hide(&self) {
1546 self.act(WindowCommand::Hide);
1547 }
1548
1549 fn open_modal(&self) {
1551 self.act(WindowCommand::OpenModal);
1552 }
1553
1554 fn open_window(&self) {
1556 self.act(WindowCommand::OpenWindow);
1557 }
1558
1559 fn open(&self, id: &str) {
1561 self.act(WindowCommand::Open(id.to_owned()));
1562 }
1563
1564 fn close_window(&self, id: &str) {
1566 self.act(WindowCommand::CloseWindow(id.to_owned()));
1567 }
1568
1569 fn show_window(&self, id: &str) {
1571 self.act(WindowCommand::ShowWindow(id.to_owned()));
1572 }
1573
1574 fn hide_window(&self, id: &str) {
1576 self.act(WindowCommand::HideWindow(id.to_owned()));
1577 }
1578
1579 fn is_maximized(&self) -> bool {
1581 crate::control::is_maximized()
1582 }
1583}
1584
1585impl VNode for VElement {
1586 fn key(&self) -> &'static str {
1587 self.key
1588 }
1589
1590 fn kind(&self) -> &NodeKind {
1591 &self.kind
1592 }
1593
1594 fn kind_mut(&mut self) -> &mut NodeKind {
1595 &mut self.kind
1596 }
1597
1598 fn style(&self) -> &Style {
1599 &self.style
1600 }
1601
1602 fn style_mut(&mut self) -> &mut Style {
1603 &mut self.style
1604 }
1605
1606 fn tag(&self) -> &'static str {
1607 self.tag
1608 }
1609
1610 fn attrs(&self) -> &[(&'static str, String)] {
1611 &self.attrs
1612 }
1613
1614 fn children(&self) -> &[VElement] {
1615 &self.children
1616 }
1617}
1618
1619impl VWindow for VElement {
1620 fn config(&self) -> Option<&WindowConfig> {
1621 self.window.as_ref()
1622 }
1623}
1624
1625#[derive(Debug, Clone, PartialEq)]
1627pub enum Op {
1628 SetContent {
1630 key: &'static str,
1632 content: String,
1634 },
1635 SetLabel {
1637 key: &'static str,
1639 label: String,
1641 },
1642 SetDisabled {
1644 key: &'static str,
1646 disabled: bool,
1648 },
1649 SetValue {
1651 key: &'static str,
1653 value: String,
1655 },
1656 SetPlaceholder {
1658 key: &'static str,
1660 placeholder: String,
1662 },
1663 SetMasked {
1665 key: &'static str,
1667 masked: bool,
1669 },
1670 SetChecked {
1672 key: &'static str,
1674 checked: bool,
1676 },
1677 SetSelected {
1679 key: &'static str,
1681 selected: bool,
1683 },
1684 SetOptions {
1686 key: &'static str,
1688 options: Vec<SelectOption>,
1690 },
1691 Insert {
1693 key: &'static str,
1695 },
1696 Remove {
1698 key: &'static str,
1700 },
1701 Replace {
1703 key: &'static str,
1705 },
1706}
1707
1708impl Op {
1709 pub fn key(&self) -> &'static str {
1711 match self {
1712 Self::SetContent { key, .. }
1713 | Self::SetLabel { key, .. }
1714 | Self::SetDisabled { key, .. }
1715 | Self::SetValue { key, .. }
1716 | Self::SetPlaceholder { key, .. }
1717 | Self::SetMasked { key, .. }
1718 | Self::SetChecked { key, .. }
1719 | Self::SetSelected { key, .. }
1720 | Self::SetOptions { key, .. }
1721 | Self::Insert { key }
1722 | Self::Remove { key }
1723 | Self::Replace { key } => key,
1724 }
1725 }
1726}
1727
1728#[derive(Debug, Clone, Default, PartialEq)]
1730pub struct Patch {
1731 pub ops: Vec<Op>,
1733 pub changed: BTreeSet<&'static str>,
1735}
1736
1737impl Patch {
1738 pub fn is_empty(&self) -> bool {
1740 self.ops.is_empty()
1741 }
1742}
1743
1744pub fn diff(old: &VElement, new: &VElement) -> Patch {
1750 let mut patch = Patch::default();
1751 diff_node(old, new, &mut patch);
1752 patch
1753}
1754
1755fn diff_node(old: &VElement, new: &VElement, patch: &mut Patch) {
1756 if old.key != new.key {
1757 debug_assert!(false, "diff_node вызван для разных ключей");
1758 patch.ops.push(Op::Replace { key: new.key });
1759 patch.changed.insert(new.key);
1760 return;
1761 }
1762 if !kind_compatible(&old.kind, &new.kind) {
1763 patch.ops.push(Op::Replace { key: new.key });
1764 patch.changed.insert(new.key);
1765 return;
1766 }
1767 if old.style != new.style {
1768 patch.changed.insert(new.key);
1769 }
1770 if old.attrs != new.attrs {
1771 patch.changed.insert(new.key);
1772 }
1773 diff_kind(&old.kind, &new.kind, new.key, patch);
1774 diff_children(old, new, patch);
1775}
1776
1777fn kind_compatible(a: &NodeKind, b: &NodeKind) -> bool {
1779 match (a, b) {
1780 (NodeKind::Column, NodeKind::Column)
1781 | (NodeKind::Row, NodeKind::Row)
1782 | (NodeKind::TitleBar, NodeKind::TitleBar)
1783 | (NodeKind::Window, NodeKind::Window)
1784 | (NodeKind::Text { .. }, NodeKind::Text { .. })
1785 | (NodeKind::Button { .. }, NodeKind::Button { .. })
1786 | (NodeKind::TextField { .. }, NodeKind::TextField { .. }) => true,
1787 #[cfg(feature = "image-support")]
1788 (NodeKind::Image { src: src_a, .. }, NodeKind::Image { src: src_b, .. }) => src_a == src_b,
1789 #[cfg(feature = "image-support")]
1790 (NodeKind::RuntimeImage { image: a, .. }, NodeKind::RuntimeImage { image: b, .. }) => {
1791 a.key == b.key
1792 }
1793 #[cfg(feature = "elements-checkbox")]
1794 (NodeKind::Checkbox { .. }, NodeKind::Checkbox { .. }) => true,
1795 #[cfg(feature = "elements-radio")]
1796 (NodeKind::Radio { .. }, NodeKind::Radio { .. }) => true,
1797 #[cfg(feature = "elements-select")]
1798 (NodeKind::Select { .. }, NodeKind::Select { .. }) => true,
1799 _ => false,
1800 }
1801}
1802
1803fn diff_kind(old: &NodeKind, new: &NodeKind, key: &'static str, patch: &mut Patch) {
1804 match (old, new) {
1805 (NodeKind::Text { content: a }, NodeKind::Text { content: b }) => {
1806 if a != b {
1807 patch.ops.push(Op::SetContent {
1808 key,
1809 content: b.clone(),
1810 });
1811 patch.changed.insert(key);
1812 }
1813 }
1814 #[cfg(feature = "image-support")]
1815 (
1816 NodeKind::Image {
1817 data: data_a,
1818 alt: alt_a,
1819 ..
1820 },
1821 NodeKind::Image {
1822 data: data_b,
1823 alt: alt_b,
1824 ..
1825 },
1826 ) => {
1827 if data_a != data_b || alt_a != alt_b {
1828 patch.changed.insert(key);
1829 }
1830 }
1831 #[cfg(feature = "image-support")]
1832 (
1833 NodeKind::RuntimeImage {
1834 image: image_a,
1835 alt: alt_a,
1836 },
1837 NodeKind::RuntimeImage {
1838 image: image_b,
1839 alt: alt_b,
1840 },
1841 ) => {
1842 if image_a != image_b || alt_a != alt_b {
1843 patch.changed.insert(key);
1844 }
1845 }
1846 (
1847 NodeKind::Button {
1848 disabled: disabled_a,
1849 button_type: type_a,
1850 },
1851 NodeKind::Button {
1852 disabled: disabled_b,
1853 button_type: button_type_b,
1854 },
1855 ) => {
1856 if disabled_a != disabled_b {
1857 patch.ops.push(Op::SetDisabled {
1858 key,
1859 disabled: *disabled_b,
1860 });
1861 patch.changed.insert(key);
1862 }
1863 if type_a != button_type_b {
1864 patch.changed.insert(key);
1865 }
1866 }
1867 (
1868 NodeKind::TextField {
1869 value: value_a,
1870 placeholder: placeholder_a,
1871 disabled: disabled_a,
1872 multiline: multiline_a,
1873 resize: resize_a,
1874 masked: masked_a,
1875 },
1876 NodeKind::TextField {
1877 value: value_b,
1878 placeholder: placeholder_b,
1879 disabled: disabled_b,
1880 multiline: multiline_b,
1881 resize: resize_b,
1882 masked: masked_b,
1883 },
1884 ) => {
1885 if value_a != value_b {
1886 patch.ops.push(Op::SetValue {
1887 key,
1888 value: value_b.clone(),
1889 });
1890 patch.changed.insert(key);
1891 }
1892 if placeholder_a != placeholder_b {
1893 patch.ops.push(Op::SetPlaceholder {
1894 key,
1895 placeholder: placeholder_b.clone(),
1896 });
1897 patch.changed.insert(key);
1898 }
1899 if disabled_a != disabled_b {
1900 patch.ops.push(Op::SetDisabled {
1901 key,
1902 disabled: *disabled_b,
1903 });
1904 patch.changed.insert(key);
1905 }
1906 if multiline_a != multiline_b {
1907 patch.changed.insert(key);
1908 }
1909 if resize_a != resize_b {
1910 patch.changed.insert(key);
1911 }
1912 if masked_a != masked_b {
1913 patch.ops.push(Op::SetMasked {
1914 key,
1915 masked: *masked_b,
1916 });
1917 patch.changed.insert(key);
1918 }
1919 }
1920 #[cfg(feature = "elements-checkbox")]
1921 (
1922 NodeKind::Checkbox {
1923 label: label_a,
1924 checked: checked_a,
1925 disabled: disabled_a,
1926 },
1927 NodeKind::Checkbox {
1928 label: label_b,
1929 checked: checked_b,
1930 disabled: disabled_b,
1931 },
1932 ) => {
1933 if label_a != label_b {
1934 patch.ops.push(Op::SetLabel {
1935 key,
1936 label: label_b.clone(),
1937 });
1938 patch.changed.insert(key);
1939 }
1940 if checked_a != checked_b {
1941 patch.ops.push(Op::SetChecked {
1942 key,
1943 checked: *checked_b,
1944 });
1945 patch.changed.insert(key);
1946 }
1947 if disabled_a != disabled_b {
1948 patch.ops.push(Op::SetDisabled {
1949 key,
1950 disabled: *disabled_b,
1951 });
1952 patch.changed.insert(key);
1953 }
1954 }
1955 #[cfg(feature = "elements-radio")]
1956 (
1957 NodeKind::Radio {
1958 label: label_a,
1959 value: value_a,
1960 selected: selected_a,
1961 disabled: disabled_a,
1962 },
1963 NodeKind::Radio {
1964 label: label_b,
1965 value: value_b,
1966 selected: selected_b,
1967 disabled: disabled_b,
1968 },
1969 ) => {
1970 if label_a != label_b {
1971 patch.ops.push(Op::SetLabel {
1972 key,
1973 label: label_b.clone(),
1974 });
1975 patch.changed.insert(key);
1976 }
1977 if value_a != value_b {
1978 patch.changed.insert(key);
1979 }
1980 if selected_a != selected_b {
1981 patch.ops.push(Op::SetSelected {
1982 key,
1983 selected: *selected_b,
1984 });
1985 patch.changed.insert(key);
1986 }
1987 if disabled_a != disabled_b {
1988 patch.ops.push(Op::SetDisabled {
1989 key,
1990 disabled: *disabled_b,
1991 });
1992 patch.changed.insert(key);
1993 }
1994 }
1995 #[cfg(feature = "elements-select")]
1996 (
1997 NodeKind::Select {
1998 value: value_a,
1999 options: options_a,
2000 disabled: disabled_a,
2001 },
2002 NodeKind::Select {
2003 value: value_b,
2004 options: options_b,
2005 disabled: disabled_b,
2006 },
2007 ) => {
2008 if value_a != value_b {
2009 patch.ops.push(Op::SetValue {
2010 key,
2011 value: value_b.clone(),
2012 });
2013 patch.changed.insert(key);
2014 }
2015 if options_a != options_b {
2016 patch.ops.push(Op::SetOptions {
2017 key,
2018 options: options_b.clone(),
2019 });
2020 patch.changed.insert(key);
2021 }
2022 if disabled_a != disabled_b {
2023 patch.ops.push(Op::SetDisabled {
2024 key,
2025 disabled: *disabled_b,
2026 });
2027 patch.changed.insert(key);
2028 }
2029 }
2030 (NodeKind::Column, NodeKind::Column)
2031 | (NodeKind::Row, NodeKind::Row)
2032 | (NodeKind::TitleBar, NodeKind::TitleBar)
2033 | (NodeKind::Window, NodeKind::Window) => {}
2034 _ => debug_assert!(false, "несовместимые типы должны фильтроваться раньше"),
2035 }
2036}
2037
2038fn diff_children(old: &VElement, new: &VElement, patch: &mut Patch) {
2039 let old_by_key: HashMap<&'static str, &VElement> = old
2040 .children
2041 .iter()
2042 .map(|child| (child.key, child))
2043 .collect();
2044 let mut matched = HashSet::new();
2045 for new_child in &new.children {
2046 match old_by_key.get(new_child.key) {
2047 Some(old_child) => {
2048 matched.insert(new_child.key);
2049 diff_node(old_child, new_child, patch);
2050 }
2051 None => {
2052 patch.ops.push(Op::Insert { key: new_child.key });
2053 patch.changed.insert(new_child.key);
2054 }
2055 }
2056 }
2057 for old_child in &old.children {
2058 if !matched.contains(old_child.key) {
2059 patch.ops.push(Op::Remove { key: old_child.key });
2060 patch.changed.insert(old_child.key);
2061 }
2062 }
2063}
2064
2065#[cfg(test)]
2066mod tests {
2067 use super::*;
2068
2069 #[test]
2070 fn parse_align_items_accepts_center() {
2071 assert_eq!(parse_align_items("center"), Align::Center);
2072 assert_eq!(parse_align_items("start"), Align::Start);
2073 assert_eq!(parse_align_items("end"), Align::End);
2074 }
2075
2076 #[test]
2077 fn invalid_align_items_returns_start_not_panic() {
2078 let result = std::panic::catch_unwind(|| {
2079 parse_align_items("ыефке")
2083 });
2084 assert!(
2085 result.is_ok(),
2086 "parse_align_items panicked on invalid value"
2087 );
2088 assert_eq!(result.unwrap(), Align::Start);
2089 }
2090}