cssbox-core 0.1.0

Standalone CSS layout engine — core algorithms
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! Computed CSS style types for layout.

use crate::values::{LengthPercentage, LengthPercentageAuto, LengthPercentageNone};

/// CSS `display` outer type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisplayOuter {
    Block,
    Inline,
    None,
}

/// CSS `display` inner type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisplayInner {
    Flow,
    FlowRoot,
    Flex,
    Grid,
    Table,
    TableRowGroup,
    TableRow,
    TableCell,
    TableColumn,
    TableColumnGroup,
    TableCaption,
    TableHeaderGroup,
    TableFooterGroup,
}

/// Resolved `display` value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Display {
    pub outer: DisplayOuter,
    pub inner: DisplayInner,
}

impl Display {
    pub const BLOCK: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::Flow,
    };
    pub const INLINE: Self = Self {
        outer: DisplayOuter::Inline,
        inner: DisplayInner::Flow,
    };
    pub const INLINE_BLOCK: Self = Self {
        outer: DisplayOuter::Inline,
        inner: DisplayInner::FlowRoot,
    };
    pub const FLEX: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::Flex,
    };
    pub const INLINE_FLEX: Self = Self {
        outer: DisplayOuter::Inline,
        inner: DisplayInner::Flex,
    };
    pub const GRID: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::Grid,
    };
    pub const INLINE_GRID: Self = Self {
        outer: DisplayOuter::Inline,
        inner: DisplayInner::Grid,
    };
    pub const TABLE: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::Table,
    };
    pub const TABLE_ROW: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableRow,
    };
    pub const TABLE_CELL: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableCell,
    };
    pub const TABLE_ROW_GROUP: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableRowGroup,
    };
    pub const TABLE_COLUMN: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableColumn,
    };
    pub const TABLE_COLUMN_GROUP: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableColumnGroup,
    };
    pub const TABLE_CAPTION: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableCaption,
    };
    pub const TABLE_HEADER_GROUP: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableHeaderGroup,
    };
    pub const TABLE_FOOTER_GROUP: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::TableFooterGroup,
    };
    pub const NONE: Self = Self {
        outer: DisplayOuter::None,
        inner: DisplayInner::Flow,
    };
    pub const FLOW_ROOT: Self = Self {
        outer: DisplayOuter::Block,
        inner: DisplayInner::FlowRoot,
    };

    pub fn is_none(&self) -> bool {
        self.outer == DisplayOuter::None
    }

    pub fn is_block_level(&self) -> bool {
        self.outer == DisplayOuter::Block
    }

    pub fn is_inline_level(&self) -> bool {
        self.outer == DisplayOuter::Inline
    }

    pub fn establishes_bfc(&self) -> bool {
        matches!(
            self.inner,
            DisplayInner::FlowRoot | DisplayInner::Flex | DisplayInner::Grid | DisplayInner::Table
        )
    }

    pub fn is_table_part(&self) -> bool {
        matches!(
            self.inner,
            DisplayInner::Table
                | DisplayInner::TableRow
                | DisplayInner::TableCell
                | DisplayInner::TableRowGroup
                | DisplayInner::TableColumn
                | DisplayInner::TableColumnGroup
                | DisplayInner::TableCaption
                | DisplayInner::TableHeaderGroup
                | DisplayInner::TableFooterGroup
        )
    }
}

impl Default for Display {
    fn default() -> Self {
        Self::INLINE
    }
}

/// CSS `position` property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Position {
    #[default]
    Static,
    Relative,
    Absolute,
    Fixed,
    Sticky,
}

impl Position {
    pub fn is_positioned(&self) -> bool {
        !matches!(self, Position::Static)
    }

    pub fn is_absolutely_positioned(&self) -> bool {
        matches!(self, Position::Absolute | Position::Fixed)
    }

    pub fn is_in_flow(&self) -> bool {
        matches!(
            self,
            Position::Static | Position::Relative | Position::Sticky
        )
    }
}

/// CSS `box-sizing` property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BoxSizing {
    #[default]
    ContentBox,
    BorderBox,
}

/// CSS `float` property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Float {
    #[default]
    None,
    Left,
    Right,
}

/// CSS `clear` property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Clear {
    #[default]
    None,
    Left,
    Right,
    Both,
}

/// CSS `overflow` property (per axis).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Overflow {
    #[default]
    Visible,
    Hidden,
    Scroll,
    Auto,
}

/// CSS `text-align` property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAlign {
    #[default]
    Left,
    Right,
    Center,
    Justify,
}

/// CSS `vertical-align` (simplified for inline layout).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum VerticalAlign {
    #[default]
    Baseline,
    Top,
    Middle,
    Bottom,
    Length(f32),
}

/// CSS `white-space` property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WhiteSpace {
    #[default]
    Normal,
    Nowrap,
    Pre,
    PreWrap,
    PreLine,
}

impl WhiteSpace {
    pub fn preserves_newlines(&self) -> bool {
        matches!(
            self,
            WhiteSpace::Pre | WhiteSpace::PreWrap | WhiteSpace::PreLine
        )
    }

    pub fn collapses_spaces(&self) -> bool {
        matches!(
            self,
            WhiteSpace::Normal | WhiteSpace::Nowrap | WhiteSpace::PreLine
        )
    }

    pub fn wraps(&self) -> bool {
        matches!(
            self,
            WhiteSpace::Normal | WhiteSpace::PreWrap | WhiteSpace::PreLine
        )
    }
}

// --- Flexbox properties ---

/// CSS `flex-direction`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexDirection {
    #[default]
    Row,
    RowReverse,
    Column,
    ColumnReverse,
}

impl FlexDirection {
    pub fn is_row(&self) -> bool {
        matches!(self, FlexDirection::Row | FlexDirection::RowReverse)
    }

    pub fn is_column(&self) -> bool {
        !self.is_row()
    }

    pub fn is_reverse(&self) -> bool {
        matches!(
            self,
            FlexDirection::RowReverse | FlexDirection::ColumnReverse
        )
    }
}

/// CSS `flex-wrap`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexWrap {
    #[default]
    Nowrap,
    Wrap,
    WrapReverse,
}

/// CSS alignment values (for justify-content, align-items, etc.).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignItems {
    #[default]
    Stretch,
    FlexStart,
    FlexEnd,
    Center,
    Baseline,
    Start,
    End,
}

/// CSS `align-self`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignSelf {
    #[default]
    Auto,
    Stretch,
    FlexStart,
    FlexEnd,
    Center,
    Baseline,
    Start,
    End,
}

/// CSS `justify-content`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JustifyContent {
    #[default]
    FlexStart,
    FlexEnd,
    Center,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
    Start,
    End,
}

/// CSS `align-content`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignContent {
    #[default]
    Stretch,
    FlexStart,
    FlexEnd,
    Center,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
    Start,
    End,
}

// --- Grid properties ---

/// A grid track sizing function.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum TrackSizingFunction {
    /// Fixed length.
    Length(f32),
    /// Percentage of grid container.
    Percentage(f32),
    /// Fraction of remaining space.
    Fr(f32),
    /// Minimum content size.
    MinContent,
    /// Maximum content size.
    MaxContent,
    /// Auto sizing.
    #[default]
    Auto,
    /// minmax(min, max).
    MinMax(Box<TrackSizingFunction>, Box<TrackSizingFunction>),
    /// fit-content(limit).
    FitContent(f32),
}

/// A grid track definition.
#[derive(Debug, Clone, PartialEq)]
pub struct TrackDefinition {
    pub sizing: TrackSizingFunction,
    pub line_name: Option<String>,
}

impl TrackDefinition {
    pub fn new(sizing: TrackSizingFunction) -> Self {
        Self {
            sizing,
            line_name: None,
        }
    }
}

/// Grid auto-flow direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GridAutoFlow {
    #[default]
    Row,
    Column,
    RowDense,
    ColumnDense,
}

/// Grid placement value for a single edge.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum GridPlacement {
    #[default]
    Auto,
    Line(i32),
    Span(u32),
    Named(String),
}

// --- Table properties ---

/// CSS `table-layout`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TableLayout {
    #[default]
    Auto,
    Fixed,
}

/// CSS `border-collapse`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BorderCollapse {
    #[default]
    Separate,
    Collapse,
}

/// CSS `caption-side`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CaptionSide {
    #[default]
    Top,
    Bottom,
}

// --- Computed style ---

/// Full computed style for a layout node.
#[derive(Debug, Clone, PartialEq)]
pub struct ComputedStyle {
    // Display & positioning
    pub display: Display,
    pub position: Position,
    pub float: Float,
    pub clear: Clear,

    // Box model
    pub box_sizing: BoxSizing,
    pub width: LengthPercentageAuto,
    pub height: LengthPercentageAuto,
    pub min_width: LengthPercentage,
    pub min_height: LengthPercentage,
    pub max_width: LengthPercentageNone,
    pub max_height: LengthPercentageNone,

    pub margin_top: LengthPercentageAuto,
    pub margin_right: LengthPercentageAuto,
    pub margin_bottom: LengthPercentageAuto,
    pub margin_left: LengthPercentageAuto,

    pub padding_top: LengthPercentage,
    pub padding_right: LengthPercentage,
    pub padding_bottom: LengthPercentage,
    pub padding_left: LengthPercentage,

    pub border_top_width: f32,
    pub border_right_width: f32,
    pub border_bottom_width: f32,
    pub border_left_width: f32,

    // Positioning offsets
    pub top: LengthPercentageAuto,
    pub right: LengthPercentageAuto,
    pub bottom: LengthPercentageAuto,
    pub left: LengthPercentageAuto,

    // Overflow
    pub overflow_x: Overflow,
    pub overflow_y: Overflow,

    // Text/inline
    pub text_align: TextAlign,
    pub vertical_align: VerticalAlign,
    pub line_height: f32,
    pub white_space: WhiteSpace,

    // Flexbox
    pub flex_direction: FlexDirection,
    pub flex_wrap: FlexWrap,
    pub flex_grow: f32,
    pub flex_shrink: f32,
    pub flex_basis: LengthPercentageAuto,
    pub align_items: AlignItems,
    pub align_self: AlignSelf,
    pub align_content: AlignContent,
    pub justify_content: JustifyContent,
    pub order: i32,

    // Grid container
    pub grid_template_rows: Vec<TrackDefinition>,
    pub grid_template_columns: Vec<TrackDefinition>,
    pub grid_auto_rows: Vec<TrackSizingFunction>,
    pub grid_auto_columns: Vec<TrackSizingFunction>,
    pub grid_auto_flow: GridAutoFlow,
    pub row_gap: f32,
    pub column_gap: f32,

    // Grid item
    pub grid_row_start: GridPlacement,
    pub grid_row_end: GridPlacement,
    pub grid_column_start: GridPlacement,
    pub grid_column_end: GridPlacement,

    // Table
    pub table_layout: TableLayout,
    pub border_collapse: BorderCollapse,
    pub border_spacing: f32,
    pub caption_side: CaptionSide,

    // Z-index
    pub z_index: crate::values::NumberOrAuto,
}

impl Default for ComputedStyle {
    fn default() -> Self {
        Self {
            display: Display::INLINE,
            position: Position::Static,
            float: Float::None,
            clear: Clear::None,

            box_sizing: BoxSizing::ContentBox,
            width: LengthPercentageAuto::Auto,
            height: LengthPercentageAuto::Auto,
            min_width: LengthPercentage::Length(0.0),
            min_height: LengthPercentage::Length(0.0),
            max_width: LengthPercentageNone::None,
            max_height: LengthPercentageNone::None,

            margin_top: LengthPercentageAuto::px(0.0),
            margin_right: LengthPercentageAuto::px(0.0),
            margin_bottom: LengthPercentageAuto::px(0.0),
            margin_left: LengthPercentageAuto::px(0.0),

            padding_top: LengthPercentage::Length(0.0),
            padding_right: LengthPercentage::Length(0.0),
            padding_bottom: LengthPercentage::Length(0.0),
            padding_left: LengthPercentage::Length(0.0),

            border_top_width: 0.0,
            border_right_width: 0.0,
            border_bottom_width: 0.0,
            border_left_width: 0.0,

            top: LengthPercentageAuto::Auto,
            right: LengthPercentageAuto::Auto,
            bottom: LengthPercentageAuto::Auto,
            left: LengthPercentageAuto::Auto,

            overflow_x: Overflow::Visible,
            overflow_y: Overflow::Visible,

            text_align: TextAlign::Left,
            vertical_align: VerticalAlign::Baseline,
            line_height: 1.2,
            white_space: WhiteSpace::Normal,

            flex_direction: FlexDirection::Row,
            flex_wrap: FlexWrap::Nowrap,
            flex_grow: 0.0,
            flex_shrink: 1.0,
            flex_basis: LengthPercentageAuto::Auto,
            align_items: AlignItems::Stretch,
            align_self: AlignSelf::Auto,
            align_content: AlignContent::Stretch,
            justify_content: JustifyContent::FlexStart,
            order: 0,

            grid_template_rows: Vec::new(),
            grid_template_columns: Vec::new(),
            grid_auto_rows: Vec::new(),
            grid_auto_columns: Vec::new(),
            grid_auto_flow: GridAutoFlow::Row,
            row_gap: 0.0,
            column_gap: 0.0,

            grid_row_start: GridPlacement::Auto,
            grid_row_end: GridPlacement::Auto,
            grid_column_start: GridPlacement::Auto,
            grid_column_end: GridPlacement::Auto,

            table_layout: TableLayout::Auto,
            border_collapse: BorderCollapse::Separate,
            border_spacing: 0.0,
            caption_side: CaptionSide::Top,

            z_index: crate::values::NumberOrAuto::Auto,
        }
    }
}

impl ComputedStyle {
    /// Create a block-level element style with default values.
    pub fn block() -> Self {
        Self {
            display: Display::BLOCK,
            ..Default::default()
        }
    }

    /// Create an inline element style.
    pub fn inline() -> Self {
        Self::default()
    }

    /// Whether this element establishes a new block formatting context.
    pub fn establishes_bfc(&self) -> bool {
        self.display.establishes_bfc()
            || self.overflow_x != Overflow::Visible
            || self.overflow_y != Overflow::Visible
            || self.float != Float::None
            || self.position.is_absolutely_positioned()
    }

    /// Whether this element is out of flow.
    pub fn is_out_of_flow(&self) -> bool {
        self.position.is_absolutely_positioned() || self.float != Float::None
    }
}