1use crate::error::{GuiError, GuiResult};
15
16pub mod box_sizing;
17pub mod flex;
18pub mod grid;
19pub mod tree;
20
21pub use box_sizing::{
22 apply_relative_offset, compute_box_sizing, resolve_absolute_position, resolve_box_constraints,
23 resolve_dimension, resolve_inset, resolve_margin, resolve_padding, BoxConstraints,
24 BoxDimensions, Measurer, TextMeasurementCache, MAX_LAYOUT_DEPTH, STRICT_TOLERANCE_PX,
25};
26pub use flex::{compute_flex, compute_multi_line_flex, compute_single_line_flex, FlexItem};
27pub use grid::compute_grid;
28pub use tree::{
29 AvailableSpaceKey, CachedLayout, LayoutCacheKey, LayoutMetrics, LayoutNode, LayoutNodeId,
30 LayoutTree,
31};
32
33#[derive(Debug, Clone, Copy, PartialEq)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
36pub enum AvailableSpace {
37 Definite(f32),
39 MinContent,
41 MaxContent,
43}
44
45impl AvailableSpace {
46 pub fn is_definite(&self) -> bool {
48 matches!(self, Self::Definite(_))
49 }
50
51 pub fn into_option(self) -> Option<f32> {
53 match self {
54 Self::Definite(val) => Some(val),
55 _ => None,
56 }
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub struct Size<T> {
64 pub width: T,
65 pub height: T,
66}
67
68impl<T> Size<T> {
69 pub const fn new(width: T, height: T) -> Self {
71 Self { width, height }
72 }
73}
74
75impl<T: Copy> Size<T> {
76 pub fn all(value: T) -> Self {
78 Self {
79 width: value,
80 height: value,
81 }
82 }
83}
84
85impl Size<Dimension> {
86 pub fn auto() -> Self {
88 Self {
89 width: Dimension::Auto,
90 height: Dimension::Auto,
91 }
92 }
93
94 pub fn from_lengths(width: f32, height: f32) -> Self {
96 Self {
97 width: Dimension::Length(width),
98 height: Dimension::Length(height),
99 }
100 }
101}
102
103impl Size<LengthPercentage> {
104 pub fn zero() -> Self {
106 Self {
107 width: LengthPercentage::Length(0.0),
108 height: LengthPercentage::Length(0.0),
109 }
110 }
111}
112
113impl Size<f32> {
114 pub const ZERO: Self = Self {
116 width: 0.0,
117 height: 0.0,
118 };
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
123#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
124pub struct Point<T> {
125 pub x: T,
126 pub y: T,
127}
128
129impl<T> Point<T> {
130 pub const fn new(x: T, y: T) -> Self {
132 Self { x, y }
133 }
134}
135
136impl Point<f32> {
137 pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
143#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
144pub struct Rect<T> {
145 pub left: T,
146 pub right: T,
147 pub top: T,
148 pub bottom: T,
149}
150
151impl<T> Rect<T> {
152 pub const fn new(left: T, right: T, top: T, bottom: T) -> Self {
154 Self {
155 left,
156 right,
157 top,
158 bottom,
159 }
160 }
161}
162
163impl<T: Copy> Rect<T> {
164 pub fn all(value: T) -> Self {
166 Self {
167 left: value,
168 right: value,
169 top: value,
170 bottom: value,
171 }
172 }
173
174 pub fn symmetric(vertical: T, horizontal: T) -> Self {
176 Self {
177 left: horizontal,
178 right: horizontal,
179 top: vertical,
180 bottom: vertical,
181 }
182 }
183}
184
185impl Rect<LengthPercentage> {
186 pub fn zero() -> Self {
188 Self::all(LengthPercentage::Length(0.0))
189 }
190}
191
192impl Rect<LengthPercentageAuto> {
193 pub fn zero() -> Self {
195 Self::all(LengthPercentageAuto::Length(0.0))
196 }
197
198 pub fn auto() -> Self {
200 Self::all(LengthPercentageAuto::Auto)
201 }
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Default)]
209#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
210pub struct LayoutRect {
211 pub x: f32,
212 pub y: f32,
213 pub width: f32,
214 pub height: f32,
215}
216
217impl LayoutRect {
218 pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
220 Self {
221 x,
222 y,
223 width,
224 height,
225 }
226 }
227
228 pub const ZERO: Self = Self {
230 x: 0.0,
231 y: 0.0,
232 width: 0.0,
233 height: 0.0,
234 };
235
236 pub fn location(&self) -> Point<f32> {
238 Point::new(self.x, self.y)
239 }
240
241 pub fn size(&self) -> Size<f32> {
243 Size::new(self.width, self.height)
244 }
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Default)]
249#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
250pub enum Dimension {
251 #[default]
252 Auto,
253 Length(f32),
254 Percent(f32),
255}
256
257impl Dimension {
258 pub const fn auto() -> Self {
260 Self::Auto
261 }
262
263 pub const fn length(px: f32) -> Self {
265 Self::Length(px)
266 }
267
268 pub const fn percent(pct: f32) -> Self {
270 Self::Percent(pct)
271 }
272
273 pub fn is_auto(&self) -> bool {
275 matches!(self, Self::Auto)
276 }
277
278 pub fn is_length(&self) -> bool {
280 matches!(self, Self::Length(_))
281 }
282
283 pub fn is_percent(&self) -> bool {
285 matches!(self, Self::Percent(_))
286 }
287
288 pub fn validate(&self) -> GuiResult<()> {
290 match self {
291 Self::Auto => Ok(()),
292 Self::Length(v) | Self::Percent(v) => {
293 if !v.is_finite() {
294 Err(GuiError::InvalidNumericInput)
295 } else if *self == Self::Length(*v) && *v < 0.0 {
296 Err(GuiError::InvalidLayoutGeometry)
297 } else {
298 Ok(())
299 }
300 }
301 }
302 }
303}
304
305#[derive(Debug, Clone, Copy, PartialEq)]
307#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
308pub enum LengthPercentage {
309 Length(f32),
310 Percent(f32),
311}
312
313impl LengthPercentage {
314 pub const fn length(px: f32) -> Self {
316 Self::Length(px)
317 }
318
319 pub const fn percent(pct: f32) -> Self {
321 Self::Percent(pct)
322 }
323
324 pub fn is_length(&self) -> bool {
326 matches!(self, Self::Length(_))
327 }
328
329 pub fn is_percent(&self) -> bool {
331 matches!(self, Self::Percent(_))
332 }
333
334 pub fn to_i32_pixels(&self) -> i32 {
336 match self {
337 Self::Length(px) => px.max(0.0).round() as i32,
338 _ => 0,
339 }
340 }
341
342 pub fn validate(&self) -> GuiResult<()> {
344 match self {
345 Self::Length(v) | Self::Percent(v) => {
346 if !v.is_finite() {
347 Err(GuiError::InvalidNumericInput)
348 } else if *v < 0.0 {
349 Err(GuiError::InvalidLayoutGeometry)
350 } else {
351 Ok(())
352 }
353 }
354 }
355 }
356}
357
358impl Default for LengthPercentage {
359 fn default() -> Self {
360 Self::Length(0.0)
361 }
362}
363
364#[derive(Debug, Clone, Copy, PartialEq, Default)]
366#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
367pub enum LengthPercentageAuto {
368 #[default]
369 Auto,
370 Length(f32),
371 Percent(f32),
372}
373
374impl LengthPercentageAuto {
375 pub const fn auto() -> Self {
377 Self::Auto
378 }
379
380 pub const fn length(px: f32) -> Self {
382 Self::Length(px)
383 }
384
385 pub const fn percent(pct: f32) -> Self {
387 Self::Percent(pct)
388 }
389
390 pub fn is_auto(&self) -> bool {
392 matches!(self, Self::Auto)
393 }
394
395 pub fn is_length(&self) -> bool {
397 matches!(self, Self::Length(_))
398 }
399
400 pub fn is_percent(&self) -> bool {
402 matches!(self, Self::Percent(_))
403 }
404
405 pub fn to_i32_pixels(&self) -> i32 {
407 match self {
408 Self::Length(px) => px.max(0.0).round() as i32,
409 _ => 0,
410 }
411 }
412
413 pub fn validate(&self) -> GuiResult<()> {
415 match self {
416 Self::Auto => Ok(()),
417 Self::Length(v) | Self::Percent(v) => {
418 if !v.is_finite() {
419 Err(GuiError::InvalidNumericInput)
420 } else {
421 Ok(())
422 }
423 }
424 }
425 }
426}
427
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
430#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
431pub enum Display {
432 #[default]
433 Flex,
434 Grid,
435 None,
436}
437
438#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
440#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
441pub enum Position {
442 #[default]
443 Relative,
444 Absolute,
445}
446
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
449#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
450pub enum FlexDirection {
451 #[default]
452 Row,
453 Column,
454 RowReverse,
455 ColumnReverse,
456}
457
458impl FlexDirection {
459 pub const ROW: Self = Self::Row;
460 pub const COLUMN: Self = Self::Column;
461 pub const ROW_REVERSE: Self = Self::RowReverse;
462 pub const COLUMN_REVERSE: Self = Self::ColumnReverse;
463}
464
465#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
467#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
468pub enum FlexWrap {
469 #[default]
470 NoWrap,
471 Wrap,
472 WrapReverse,
473}
474
475impl FlexWrap {
476 pub const NO_WRAP: Self = Self::NoWrap;
477 pub const WRAP: Self = Self::Wrap;
478 pub const WRAP_REVERSE: Self = Self::WrapReverse;
479}
480
481#[derive(Debug, Clone, Copy, PartialEq, Eq)]
483#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
484pub enum AlignItems {
485 Start,
486 End,
487 Center,
488 Baseline,
489 Stretch,
490}
491
492impl AlignItems {
493 pub const START: Self = Self::Start;
494 pub const END: Self = Self::End;
495 pub const CENTER: Self = Self::Center;
496 pub const BASELINE: Self = Self::Baseline;
497 pub const STRETCH: Self = Self::Stretch;
498}
499
500#[derive(Debug, Clone, Copy, PartialEq, Eq)]
502#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
503pub enum AlignSelf {
504 Start,
505 End,
506 Center,
507 Baseline,
508 Stretch,
509}
510
511impl AlignSelf {
512 pub const START: Self = Self::Start;
513 pub const END: Self = Self::End;
514 pub const CENTER: Self = Self::Center;
515 pub const BASELINE: Self = Self::Baseline;
516 pub const STRETCH: Self = Self::Stretch;
517}
518
519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
521#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
522pub enum AlignContent {
523 Start,
524 End,
525 Center,
526 Stretch,
527 SpaceBetween,
528 SpaceAround,
529 SpaceEvenly,
530}
531
532impl AlignContent {
533 pub const START: Self = Self::Start;
534 pub const END: Self = Self::End;
535 pub const CENTER: Self = Self::Center;
536 pub const STRETCH: Self = Self::Stretch;
537 pub const SPACE_BETWEEN: Self = Self::SpaceBetween;
538 pub const SPACE_AROUND: Self = Self::SpaceAround;
539 pub const SPACE_EVENLY: Self = Self::SpaceEvenly;
540}
541
542#[derive(Debug, Clone, Copy, PartialEq, Eq)]
544#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
545pub enum JustifyContent {
546 Start,
547 End,
548 Center,
549 Stretch,
550 SpaceBetween,
551 SpaceAround,
552 SpaceEvenly,
553}
554
555impl JustifyContent {
556 pub const START: Self = Self::Start;
557 pub const END: Self = Self::End;
558 pub const CENTER: Self = Self::Center;
559 pub const STRETCH: Self = Self::Stretch;
560 pub const SPACE_BETWEEN: Self = Self::SpaceBetween;
561 pub const SPACE_AROUND: Self = Self::SpaceAround;
562 pub const SPACE_EVENLY: Self = Self::SpaceEvenly;
563}
564
565#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
567#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
568pub enum GridAutoFlow {
569 #[default]
570 Row,
571 Column,
572}
573
574#[derive(Debug, Clone, PartialEq)]
576#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
577pub enum TrackSizingFunction {
578 Fixed(f32),
579 Percent(f32),
580 Flex(f32),
581 Auto,
582 MinMax(Box<TrackSizingFunction>, Box<TrackSizingFunction>),
583}
584
585#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
587#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
588pub struct GridPlacement {
589 pub start: i16,
590 pub span: u16,
591}
592
593impl GridPlacement {
594 pub const fn new(start: i16, span: u16) -> Self {
596 Self { start, span }
597 }
598}
599
600#[derive(Debug, Clone, PartialEq)]
602#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
603pub struct Style {
604 pub display: Display,
605 pub position: Position,
606 pub size: Size<Dimension>,
607 pub min_size: Size<Dimension>,
608 pub max_size: Size<Dimension>,
609 pub aspect_ratio: Option<f32>,
610 pub padding: Rect<LengthPercentage>,
611 pub margin: Rect<LengthPercentageAuto>,
612 pub inset: Rect<LengthPercentageAuto>,
613 pub flex_direction: FlexDirection,
614 pub flex_wrap: FlexWrap,
615 pub flex_grow: f32,
616 pub flex_shrink: f32,
617 pub flex_basis: Dimension,
618 pub gap: Size<LengthPercentage>,
619 pub align_items: Option<AlignItems>,
620 pub align_self: Option<AlignSelf>,
621 pub justify_items: Option<AlignItems>,
622 pub justify_self: Option<AlignSelf>,
623 pub align_content: Option<AlignContent>,
624 pub justify_content: Option<JustifyContent>,
625 pub grid_template_rows: Vec<TrackSizingFunction>,
626 pub grid_template_columns: Vec<TrackSizingFunction>,
627 pub grid_auto_rows: Vec<TrackSizingFunction>,
628 pub grid_auto_columns: Vec<TrackSizingFunction>,
629 pub grid_auto_flow: GridAutoFlow,
630 pub grid_row: GridPlacement,
631 pub grid_column: GridPlacement,
632}
633
634impl Default for Style {
635 fn default() -> Self {
636 Self {
637 display: Display::Flex,
638 position: Position::Relative,
639 size: Size::auto(),
640 min_size: Size::auto(),
641 max_size: Size::auto(),
642 aspect_ratio: None,
643 padding: Rect::<LengthPercentage>::zero(),
644 margin: Rect::<LengthPercentageAuto>::zero(),
645 inset: Rect::auto(),
646 flex_direction: FlexDirection::Row,
647 flex_wrap: FlexWrap::NoWrap,
648 flex_grow: 0.0,
649 flex_shrink: 1.0,
650 flex_basis: Dimension::Auto,
651 gap: Size::zero(),
652 align_items: None,
653 align_self: None,
654 justify_items: None,
655 justify_self: None,
656 align_content: None,
657 justify_content: None,
658 grid_template_rows: Vec::new(),
659 grid_template_columns: Vec::new(),
660 grid_auto_rows: Vec::new(),
661 grid_auto_columns: Vec::new(),
662 grid_auto_flow: GridAutoFlow::Row,
663 grid_row: GridPlacement::default(),
664 grid_column: GridPlacement::default(),
665 }
666 }
667}
668
669impl Style {
670 pub fn validate(&self) -> GuiResult<()> {
672 if let Some(ratio) = self.aspect_ratio {
673 if !ratio.is_finite() || ratio <= 0.0 {
674 return Err(GuiError::InvalidNumericInput);
675 }
676 }
677 if !self.flex_grow.is_finite() || self.flex_grow < 0.0 {
678 return Err(GuiError::InvalidNumericInput);
679 }
680 if !self.flex_shrink.is_finite() || self.flex_shrink < 0.0 {
681 return Err(GuiError::InvalidNumericInput);
682 }
683
684 self.size.width.validate()?;
685 self.size.height.validate()?;
686 self.min_size.width.validate()?;
687 self.min_size.height.validate()?;
688 self.max_size.width.validate()?;
689 self.max_size.height.validate()?;
690
691 self.padding.left.validate()?;
692 self.padding.right.validate()?;
693 self.padding.top.validate()?;
694 self.padding.bottom.validate()?;
695
696 self.gap.width.validate()?;
697 self.gap.height.validate()?;
698
699 self.margin.left.validate()?;
700 self.margin.right.validate()?;
701 self.margin.top.validate()?;
702 self.margin.bottom.validate()?;
703
704 self.inset.left.validate()?;
705 self.inset.right.validate()?;
706 self.inset.top.validate()?;
707 self.inset.bottom.validate()?;
708
709 self.flex_basis.validate()?;
710
711 Ok(())
712 }
713}
714
715#[cfg(test)]
716mod tests {
717 use super::*;
718
719 #[test]
720 fn test_style_defaults_and_validation() {
721 let style = Style::default();
722 assert_eq!(style.display, Display::Flex);
723 assert_eq!(style.flex_grow, 0.0);
724 assert_eq!(style.flex_shrink, 1.0);
725 assert!(style.validate().is_ok());
726 }
727
728 #[test]
729 fn test_style_validation_rejects_nan_and_negative_dimensions() {
730 let mut style = Style {
731 flex_grow: -1.0,
732 ..Style::default()
733 };
734 assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));
735
736 style.flex_grow = f32::NAN;
737 assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));
738
739 style = Style {
740 size: Size {
741 width: Dimension::Length(-10.0),
742 ..Size::auto()
743 },
744 ..Style::default()
745 };
746 assert_eq!(style.validate(), Err(GuiError::InvalidLayoutGeometry));
747
748 style = Style {
749 aspect_ratio: Some(-2.0),
750 ..Style::default()
751 };
752 assert_eq!(style.validate(), Err(GuiError::InvalidNumericInput));
753 }
754
755 #[test]
756 fn test_layout_rect_helpers() {
757 let rect = LayoutRect::new(10.0, 20.0, 300.0, 200.0);
758 assert_eq!(rect.location(), Point::new(10.0, 20.0));
759 assert_eq!(rect.size(), Size::new(300.0, 200.0));
760 }
761}