1
//! Box model geometry types and writing-mode support for the layout solver.
2
//!
3
//! Provides edge-size types (`EdgeSizes`, `ResolvedBoxProps`, `PackedBoxProps`),
4
//! CSS value resolution (`UnresolvedMargin`, `UnresolvedEdge`, `ResolutionParams`),
5
//! intrinsic sizing (`IntrinsicSizes`), and writing-mode context (`WritingModeContext`).
6

            
7
use azul_core::{
8
    geom::{LogicalPosition, LogicalRect, LogicalSize},
9
    ui_solver::ResolvedOffsets,
10
};
11
use azul_css::props::{
12
    basic::{pixel::PixelValue, PhysicalSize, PropertyContext, ResolutionContext, SizeMetric},
13
    layout::LayoutWritingMode,
14
    style::{StyleDirection, StyleTextOrientation},
15
};
16

            
17
/// The containing block a node's used size is resolved against — with each
18
/// axis carrying whether it is a LENGTH or a measurement CONSTRAINT.
19
///
20
/// # Why this type exists
21
///
22
/// Taffy models available space as a sum type (`Definite` / `MinContent` /
23
/// `MaxContent`) precisely so that "indefinite" is not representable as a
24
/// float. The bridge used to flatten that into `f32::INFINITY`, and from that
25
/// point on nothing downstream could tell 800px from no-constraint: `width:
26
/// auto` stretch-fit to the infinity, `width: 100%` multiplied straight
27
/// through it, and the persisted result became an infinite clip, a
28
/// `u32::MAX`-wide compositor layer, and a ~900 GB pixmap request. Three
29
/// separate fixes patched three separate leaks of the same erasure; this type
30
/// removes the erasure. Inside sizing there is no flattened form to misuse —
31
/// every consumer must say what an indefinite axis means for it.
32
///
33
/// # The `flattened` view
34
///
35
/// The legacy `LogicalSize` (INFINITY sentinel included) is still stored,
36
/// because the layout CACHE is keyed on it (`classify_size_key` canonicalizes
37
/// the indefinite axis and its slotting depends on the exact legacy values).
38
/// Both views are built by one constructor from one input, so they cannot
39
/// drift. Migrating the cache keys onto the typed axes is a follow-up; until
40
/// then the flattened view is for KEYS, never for arithmetic.
41
#[derive(Copy, Debug, Clone, PartialEq)]
42
pub struct ContainingBlock {
43
    /// The inline-axis constraint.
44
    pub width: crate::text3::cache::AvailableSpace,
45
    /// The block-axis constraint.
46
    pub height: crate::text3::cache::AvailableSpace,
47
    /// The exact `LogicalSize` the pre-typed code carried, for cache keys.
48
    flattened: LogicalSize,
49
}
50

            
51
impl ContainingBlock {
52
    /// A fully definite containing block — the normal layout case.
53
    #[must_use]
54
66500
    pub const fn definite(size: LogicalSize) -> Self {
55
66500
        Self {
56
66500
            width: crate::text3::cache::AvailableSpace::Definite(size.width),
57
66500
            height: crate::text3::cache::AvailableSpace::Definite(size.height),
58
66500
            flattened: size,
59
66500
        }
60
66500
    }
61

            
62
    /// Adopt a legacy flattened size, reading a non-finite axis as the
63
    /// max-content constraint.
64
    ///
65
    /// The migration shim for call sites that have no semantic channel saying
66
    /// WHICH measurement produced the sentinel. Max-content is the right
67
    /// default: it is what `AvailableSpace::default()` is, and what every
68
    /// pre-typed consumer effectively assumed ("no constraint, natural size").
69
    #[must_use]
70
30
    pub const fn from_flattened(size: LogicalSize) -> Self {
71
30
        Self {
72
30
            width: axis_from_flattened(size.width, crate::text3::cache::AvailableSpace::MaxContent),
73
30
            height: axis_from_flattened(
74
30
                size.height,
75
30
                crate::text3::cache::AvailableSpace::MaxContent,
76
30
            ),
77
30
            flattened: size,
78
30
        }
79
30
    }
80

            
81
    /// Adopt a legacy flattened size whose WIDTH sentinel's meaning is known
82
    /// from a `LayoutConstraints::available_width_type` channel.
83
    ///
84
    /// A finite width is definite regardless of the channel (the channel
85
    /// describes the pass, the number describes this box). The height axis has
86
    /// never had a semantic channel, so a non-finite height reads as
87
    /// max-content like [`Self::from_flattened`].
88
    #[must_use]
89
49853
    pub const fn from_flattened_with_width_type(
90
49853
        size: LogicalSize,
91
49853
        width_type: crate::text3::cache::AvailableSpace,
92
49853
    ) -> Self {
93
49853
        let width_kind = match width_type {
94
            crate::text3::cache::AvailableSpace::MinContent => {
95
947
                crate::text3::cache::AvailableSpace::MinContent
96
            }
97
48906
            _ => crate::text3::cache::AvailableSpace::MaxContent,
98
        };
99
49853
        Self {
100
49853
            width: axis_from_flattened(size.width, width_kind),
101
49853
            height: axis_from_flattened(
102
49853
                size.height,
103
49853
                crate::text3::cache::AvailableSpace::MaxContent,
104
49853
            ),
105
49853
            flattened: size,
106
49853
        }
107
49853
    }
108

            
109
    /// Build from already-typed axes plus the legacy flattened view the
110
    /// pre-typed code carried for this situation (cache keys).
111
    #[must_use]
112
301007
    pub const fn from_axes(
113
301007
        width: crate::text3::cache::AvailableSpace,
114
301007
        height: crate::text3::cache::AvailableSpace,
115
301007
        flattened: LogicalSize,
116
301007
    ) -> Self {
117
301007
        Self {
118
301007
            width,
119
301007
            height,
120
301007
            flattened,
121
301007
        }
122
301007
    }
123

            
124
    /// The exact legacy `LogicalSize` — cache keys and other not-yet-migrated
125
    /// consumers only. Never do arithmetic on this: a non-finite component is
126
    /// a constraint, not a number.
127
    #[must_use]
128
117928
    pub const fn flattened(&self) -> LogicalSize {
129
117928
        self.flattened
130
117928
    }
131
}
132

            
133
/// One axis of [`ContainingBlock::from_flattened`]: finite stays definite,
134
/// a sentinel becomes `indefinite_kind`.
135
///
136
/// Small and `#[inline(never)]` on purpose (M12.7): the wasm lift mis-reads
137
/// f32 loads inside large sizing functions, and every constructor above is
138
/// called from them.
139
#[inline(never)]
140
99766
const fn axis_from_flattened(
141
99766
    v: f32,
142
99766
    indefinite_kind: crate::text3::cache::AvailableSpace,
143
99766
) -> crate::text3::cache::AvailableSpace {
144
99766
    if v.is_finite() {
145
92144
        crate::text3::cache::AvailableSpace::Definite(v)
146
    } else {
147
7622
        indefinite_kind
148
    }
149
99766
}
150

            
151
#[derive(Copy, Debug, Clone, PartialEq, PartialOrd)]
152
pub struct PositionedRectangle {
153
    /// The outer bounds of the rectangle
154
    pub bounds: LogicalRect,
155
    /// Margin of the rectangle.
156
    pub margin: ResolvedOffsets,
157
    /// Border widths of the rectangle.
158
    pub border: ResolvedOffsets,
159
    /// Padding of the rectangle.
160
    pub padding: ResolvedOffsets,
161
}
162

            
163
// +spec:box-model:83b3b8 - Box dimensions: content area with optional padding, border, margin areas
164
/// Represents the four edges of a box for properties like margin, padding, border.
165
// +spec:box-model:3b155c - "4 values assigned to sides" pattern (top, right, bottom, left) matching
166
// margin/inset shorthands +spec:width-calculation:37f9e7 - CSS 2.2 §8.1 box dimensions: content,
167
// padding, border, margin areas with top/right/bottom/left segments
168
#[derive(Debug, Clone, Copy, Default)]
169
pub struct EdgeSizes {
170
    pub top: f32,
171
    pub right: f32,
172
    pub bottom: f32,
173
    pub left: f32,
174
}
175

            
176
impl EdgeSizes {
177
    /// Sum of horizontal edges (left + right).
178
    #[must_use]
179
88
    pub fn horizontal_sum(&self) -> f32 {
180
88
        self.left + self.right
181
88
    }
182

            
183
    /// Sum of vertical edges (top + bottom).
184
    #[must_use]
185
88
    pub fn vertical_sum(&self) -> f32 {
186
88
        self.top + self.bottom
187
88
    }
188

            
189
    // +spec:block-formatting-context:440282 - vertical writing modes use analogous layout via
190
    // main/cross axis abstraction +spec:block-formatting-context:a49f9e - line-relative
191
    // directions mapped via writing mode +spec:block-formatting-context:387117 - writing-mode
192
    // property maps block flow to vertical/horizontal axes +spec:box-model:4c01a3 - dimensional
193
    // mapping: main=block axis, cross=inline axis per writing mode +spec:box-model:4c1a9f -
194
    // physical-to-logical mapping of margin/padding/border for vertical writing modes
195
    // +spec:box-model:9414ab - flow-relative mapping of box edges (margin/padding/border) per
196
    // writing mode +spec:inline-formatting-context:2de457 - block/inline dimension mapping via
197
    // writing mode +spec:inline-formatting-context:c6b91e - line-relative "over"/"under" mapped
198
    // to physical top/bottom via writing mode +spec:writing-modes:00a918 - Abstract-to-physical
199
    // mappings for block/inline to top/right/bottom/left +spec:writing-modes:14e6f0 -
200
    // block-start/end depend only on writing-mode; inline-start/end also depend on direction
201
    // (handled in positioning.rs) +spec:writing-modes:1c2101 - Abstract directional terms
202
    // (top/right/bottom/left) to logical axes (main/cross) based on writing-mode
203
    // +spec:writing-modes:1c5155 - line-relative mappings: over/under/line-left/line-right →
204
    // top/bottom/left/right in horizontal-tb +spec:writing-modes:70daf1 - block/inline axis
205
    // mapping per writing-mode for edge sizes +spec:writing-modes:f9af71 - flow-relative
206
    // directions: block-start/end and inline-start/end mapped to physical edges
207
    // +spec:writing-modes:60b023 - abstract-to-physical mapping: block axis = main, inline axis =
208
    // cross +spec:writing-modes:829cd7 - flow-relative directions: block-start/end from
209
    // writing-mode, inline-start/end from writing-mode+direction +spec:writing-modes:a2113d -
210
    // block/inline axis mapping for writing modes (block-axis, inline-axis, block-start/end,
211
    // inline-start/end) +spec:writing-modes:c0ae9c - abstract directional mappings from
212
    // writing-mode/direction +spec:writing-modes:c91130 - Abstract box terminology:
213
    // block/inline axis mapping per writing-mode +spec:writing-modes:cd31ce - flow-relative
214
    // directions mapped to physical via writing mode +spec:writing-modes:fd8c18 - block/inline
215
    // axis mapping based on writing mode +spec:writing-modes:0e549a - writing-mode computed
216
    // value influences physical/logical axis mapping
217
    /// Returns the size of the edge at the start of the main/block axis.
218
    #[must_use]
219
1354797
    pub const fn main_start(&self, wm: LayoutWritingMode) -> f32 {
220
1354797
        match wm {
221
1354397
            LayoutWritingMode::HorizontalTb => self.top,
222
400
            LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr => self.left,
223
        }
224
1354797
    }
225

            
226
    /// Returns the size of the edge at the end of the main/block axis.
227
    #[must_use]
228
1330612
    pub const fn main_end(&self, wm: LayoutWritingMode) -> f32 {
229
1330612
        match wm {
230
1330196
            LayoutWritingMode::HorizontalTb => self.bottom,
231
416
            LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr => self.right,
232
        }
233
1330612
    }
234

            
235
    /// Returns the sum of the start and end sizes on the main/block axis.
236
    #[must_use]
237
979727
    pub fn main_sum(&self, wm: LayoutWritingMode) -> f32 {
238
979727
        self.main_start(wm) + self.main_end(wm)
239
979727
    }
240

            
241
    // +spec:block-formatting-context:6225cb - line-relative directions: vertical modes map
242
    // line-over/under to top/bottom
243
    /// Returns the size of the edge at the start of the cross/inline axis.
244
    #[must_use]
245
1016780
    pub const fn cross_start(&self, wm: LayoutWritingMode) -> f32 {
246
1016780
        match wm {
247
1016450
            LayoutWritingMode::HorizontalTb => self.left,
248
330
            LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr => self.top,
249
        }
250
1016780
    }
251

            
252
    /// Returns the size of the edge at the end of the cross/inline axis.
253
    #[must_use]
254
951637
    pub const fn cross_end(&self, wm: LayoutWritingMode) -> f32 {
255
951637
        match wm {
256
951309
            LayoutWritingMode::HorizontalTb => self.right,
257
328
            LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr => self.bottom,
258
        }
259
951637
    }
260

            
261
    /// Returns the sum of the start and end sizes on the cross/inline axis.
262
    #[must_use]
263
900678
    pub fn cross_sum(&self, wm: LayoutWritingMode) -> f32 {
264
900678
        self.cross_start(wm) + self.cross_end(wm)
265
900678
    }
266

            
267
    // +spec:block-formatting-context:a49f9e - line-over/line-under are line-relative
268
    //   block-axis edges: top/bottom in horizontal-tb, right/left in vertical modes.
269
    // +spec:inline-formatting-context:c6b91e - line-relative "over"/"under" mapped to
270
    //   physical edges via writing mode.
271
    // +spec:writing-modes:1c5155 - line-relative mappings for over/under.
272
    /// Returns the line-over edge (line-relative block-axis start).
273
    ///
274
    /// Per CSS Writing Modes L4 §6.3, the line-over side is `top` in
275
    /// `horizontal-tb` and `right` in both vertical writing modes. Unlike
276
    /// [`Self::main_start`] (a physical block-axis accessor), this is the
277
    /// *line-relative* over side and coincides with `main_start` only in
278
    /// `horizontal-tb`.
279
    #[must_use]
280
8
    pub const fn line_over(&self, wm: LayoutWritingMode) -> f32 {
281
8
        match wm {
282
3
            LayoutWritingMode::HorizontalTb => self.top,
283
5
            LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr => self.right,
284
        }
285
8
    }
286

            
287
    /// Returns the line-under edge (line-relative block-axis end).
288
    ///
289
    /// Per CSS Writing Modes L4 §6.3, the line-under side is `bottom` in
290
    /// `horizontal-tb` and `left` in both vertical writing modes.
291
    #[must_use]
292
5
    pub const fn line_under(&self, wm: LayoutWritingMode) -> f32 {
293
5
        match wm {
294
2
            LayoutWritingMode::HorizontalTb => self.bottom,
295
3
            LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr => self.left,
296
        }
297
5
    }
298

            
299
    /// Returns the sum of the line-over and line-under edges.
300
    #[must_use]
301
2
    pub fn line_over_under_sum(&self, wm: LayoutWritingMode) -> f32 {
302
2
        self.line_over(wm) + self.line_under(wm)
303
2
    }
304

            
305
    // +spec:writing-modes:829cd7 - inline-start/end depend on writing-mode AND direction.
306
    // +spec:writing-modes:c0ae9c - flow-relative inline mappings derive from
307
    //   writing-mode + direction (RTL's inline-start = line-right).
308
    // +spec:writing-modes:14e6f0 - inline-start/end depend on direction as well as wm.
309
    /// Returns the flow-relative inline-start edge.
310
    ///
311
    /// The inline-start side is `line-left` (see [`Self::cross_start`]) when the
312
    /// inline base direction is LTR, and `line-right` (see [`Self::cross_end`])
313
    /// when it is RTL. This is the direction-aware counterpart that
314
    /// `cross_start`/`cross_end` (which are direction-blind line-left/line-right)
315
    /// cannot express on their own.
316
    #[must_use]
317
17
    pub const fn inline_start(&self, wm: LayoutWritingMode, dir: StyleDirection) -> f32 {
318
17
        match dir {
319
10
            StyleDirection::Ltr => self.cross_start(wm),
320
7
            StyleDirection::Rtl => self.cross_end(wm),
321
        }
322
17
    }
323

            
324
    /// Returns the flow-relative inline-end edge.
325
    ///
326
    /// The inline-end side is `line-right` when the inline base direction is
327
    /// LTR, and `line-left` when it is RTL.
328
    #[must_use]
329
15
    pub const fn inline_end(&self, wm: LayoutWritingMode, dir: StyleDirection) -> f32 {
330
15
        match dir {
331
9
            StyleDirection::Ltr => self.cross_end(wm),
332
6
            StyleDirection::Rtl => self.cross_start(wm),
333
        }
334
15
    }
335

            
336
    /// Returns the sum of the inline-start and inline-end edges.
337
    ///
338
    /// Direction-independent (start + end covers the whole inline axis), but
339
    /// takes `dir` for call-site symmetry with the individual accessors.
340
    #[must_use]
341
9
    pub fn inline_sum(&self, wm: LayoutWritingMode, dir: StyleDirection) -> f32 {
342
9
        self.inline_start(wm, dir) + self.inline_end(wm, dir)
343
9
    }
344
}
345

            
346
// ============================================================================
347
// UNRESOLVED VALUE TYPES (for lazy resolution during layout)
348
// ============================================================================
349

            
350
/// An unresolved CSS margin value.
351
// +spec:box-model:ff1730 - margin properties apply to both continuous and paged media
352
///
353
/// Margins can be `auto` (for centering) or a length value that needs
354
/// resolution against the containing block.
355
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
356
pub enum UnresolvedMargin {
357
    /// margin: 0 (default)
358
    #[default]
359
    Zero,
360
    /// margin: auto (for centering, CSS 2.2 § 10.3.3)
361
    Auto,
362
    /// A length value (px, %, em, vh, etc.)
363
    Length(PixelValue),
364
}
365

            
366
impl UnresolvedMargin {
367
    /// Returns true if this is an auto margin
368
    #[must_use]
369
1124745
    pub const fn is_auto(&self) -> bool {
370
1124745
        matches!(self, Self::Auto)
371
1124745
    }
372

            
373
    /// Resolve this margin value to pixels.
374
    ///
375
    /// - `Auto` returns 0.0 (actual auto margin calculation happens in layout)
376
    /// - `Zero` returns 0.0
377
    /// - `Length` is resolved using the resolution context
378
    #[allow(clippy::match_same_arms)]
379
    // enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that
380
    // can't merge)
381
    #[must_use]
382
1124748
    pub fn resolve(&self, ctx: &ResolutionContext) -> f32 {
383
1124748
        match self {
384
166164
            Self::Zero => 0.0,
385
            // +spec:box-model:c921aa - auto margin-top/bottom used value is 0 for block-level
386
            // non-replaced elements in normal flow +spec:box-model:e25fdc - auto
387
            // margins treated as zero for abspos size computation
388
84
            Self::Auto => 0.0, // Auto is handled separately in layout
389
958500
            Self::Length(pv) => pv.resolve_with_context(ctx, PropertyContext::Margin),
390
        }
391
1124748
    }
392
}
393

            
394
/// Unresolved edge sizes for margin/padding/border.
395
///
396
/// This stores the raw CSS values before resolution, allowing us to
397
/// defer resolution until the containing block size is known.
398
#[derive(Debug, Clone, Copy, Default)]
399
pub struct UnresolvedEdge<T> {
400
    pub top: T,
401
    pub right: T,
402
    pub bottom: T,
403
    pub left: T,
404
}
405

            
406
impl<T> UnresolvedEdge<T> {
407
10
    pub const fn new(top: T, right: T, bottom: T, left: T) -> Self {
408
10
        Self {
409
10
            top,
410
10
            right,
411
10
            bottom,
412
10
            left,
413
10
        }
414
10
    }
415
}
416

            
417
impl UnresolvedEdge<UnresolvedMargin> {
418
    /// Resolve all margin edges to pixel values.
419
    #[must_use]
420
281184
    pub fn resolve(&self, ctx: &ResolutionContext) -> EdgeSizes {
421
281184
        EdgeSizes {
422
281184
            top: self.top.resolve(ctx),
423
281184
            right: self.right.resolve(ctx),
424
281184
            bottom: self.bottom.resolve(ctx),
425
281184
            left: self.left.resolve(ctx),
426
281184
        }
427
281184
    }
428

            
429
    /// Extract which margins are set to `auto`.
430
    #[must_use]
431
281185
    pub const fn get_margin_auto(&self) -> MarginAuto {
432
281185
        MarginAuto {
433
281185
            top: self.top.is_auto(),
434
281185
            right: self.right.is_auto(),
435
281185
            bottom: self.bottom.is_auto(),
436
281185
            left: self.left.is_auto(),
437
281185
        }
438
281185
    }
439
}
440

            
441
impl UnresolvedEdge<PixelValue> {
442
    /// Resolve all edges to pixel values.
443
    #[must_use]
444
562369
    pub fn resolve(&self, ctx: &ResolutionContext, prop_ctx: PropertyContext) -> EdgeSizes {
445
562369
        EdgeSizes {
446
562369
            top: self.top.resolve_with_context(ctx, prop_ctx),
447
562369
            right: self.right.resolve_with_context(ctx, prop_ctx),
448
562369
            bottom: self.bottom.resolve_with_context(ctx, prop_ctx),
449
562369
            left: self.left.resolve_with_context(ctx, prop_ctx),
450
562369
        }
451
562369
    }
452
}
453

            
454
/// Parameters needed to resolve CSS values to pixels.
455
#[derive(Debug, Clone, Copy)]
456
pub struct ResolutionParams {
457
    // +spec:inline-formatting-context:26c933 - LogicalSize maps inline/block dimensions to
458
    // physical width/height per writing mode
459
    /// The containing block size (for % resolution)
460
    pub containing_block: LogicalSize,
461
    /// The viewport size (for vh/vw resolution)
462
    pub viewport_size: LogicalSize,
463
    /// The element's computed font-size (for em resolution)
464
    pub element_font_size: f32,
465
    /// The root element's font-size (for rem resolution)
466
    pub root_font_size: f32,
467
}
468

            
469
impl ResolutionParams {
470
    /// Create a `ResolutionContext` from these parameters.
471
    #[must_use]
472
281197
    pub const fn to_resolution_context(&self) -> ResolutionContext {
473
281197
        ResolutionContext {
474
281197
            vertical_writing_mode: false,
475
281197
            element_font_size: self.element_font_size,
476
281197
            // For non-font properties, `em` resolves against the element's own
477
281197
            // computed font-size, so parent_font_size == element_font_size here.
478
281197
            // Do NOT use this context for font-size resolution itself.
479
281197
            parent_font_size: self.element_font_size,
480
281197
            root_font_size: self.root_font_size,
481
281197
            element_size: None,
482
281197
            containing_block_size: PhysicalSize::new(
483
281197
                self.containing_block.width,
484
281197
                self.containing_block.height,
485
281197
            ),
486
281197
            viewport_size: PhysicalSize::new(self.viewport_size.width, self.viewport_size.height),
487
281197
        }
488
281197
    }
489
}
490

            
491
// ============================================================================
492
// UNRESOLVED BOX PROPS (new design)
493
// ============================================================================
494

            
495
/// Box properties with unresolved CSS values.
496
///
497
/// This stores the raw CSS values as parsed, deferring resolution until
498
/// layout time when the containing block size is known.
499
#[derive(Debug, Clone, Copy, Default)]
500
pub struct UnresolvedBoxProps {
501
    pub margin: UnresolvedEdge<UnresolvedMargin>,
502
    pub padding: UnresolvedEdge<PixelValue>,
503
    pub border: UnresolvedEdge<PixelValue>,
504
    /// css-writing-modes-4 §7.2: margin/padding percentages resolve against
505
    /// the containing block's INLINE size. Captured at collection time from
506
    /// the node's writing mode so late re-resolution (`resolve_box_props` with
507
    /// the real containing block) picks the right axis without re-reading
508
    /// the cascade.
509
    pub vertical_writing_mode: bool,
510
}
511

            
512
impl UnresolvedBoxProps {
513
    /// Resolve all box properties to pixel values.
514
    #[must_use]
515
281183
    pub fn resolve(&self, params: &ResolutionParams) -> ResolvedBoxProps {
516
281183
        let mut ctx = params.to_resolution_context();
517
281183
        ctx.vertical_writing_mode = self.vertical_writing_mode;
518
281183
        ResolvedBoxProps {
519
281183
            margin: self.margin.resolve(&ctx),
520
281183
            padding: self.padding.resolve(&ctx, PropertyContext::Padding),
521
281183
            border: self.border.resolve(&ctx, PropertyContext::BorderWidth),
522
281183
            margin_auto: self.margin.get_margin_auto(),
523
281183
        }
524
281183
    }
525
}
526

            
527
// ============================================================================
528
// RESOLVED BOX PROPS (legacy name: BoxProps)
529
// ============================================================================
530

            
531
/// Tracks which margins are set to `auto` (for centering calculations).
532
#[derive(Debug, Clone, Copy, Default)]
533
#[allow(clippy::struct_excessive_bools)] // one independent bool per margin edge (auto flags)
534
pub struct MarginAuto {
535
    pub left: bool,
536
    pub right: bool,
537
    pub top: bool,
538
    pub bottom: bool,
539
}
540

            
541
/// A fully resolved representation of a node's box model properties.
542
// +spec:box-model:3e083b - content/padding/border/margin box model layers
543
// +spec:box-model:a227ff - content/padding/border/margin edges defining box extents for overflow
544
// +spec:containing-block:bca691 - box model edges: padding/border/margin boxes with content-box,
545
// padding-box, margin-box methods
546
///
547
/// All values are in pixels. This is the result of resolving `UnresolvedBoxProps`
548
/// against a containing block.
549
#[derive(Debug, Clone, Copy, Default)]
550
pub struct ResolvedBoxProps {
551
    pub margin: EdgeSizes,
552
    pub padding: EdgeSizes,
553
    pub border: EdgeSizes,
554
    /// Tracks which margins are set to `auto`.
555
    /// CSS 2.2 § 10.3.3: If both margin-left and margin-right are auto,
556
    /// their used values are equal, centering the element within its container.
557
    pub margin_auto: MarginAuto,
558
}
559

            
560
impl ResolvedBoxProps {
561
    // +spec:box-model:be08c6 - inner size (content-box) from outer size minus border+padding,
562
    // floored at zero +spec:writing-modes:a58616 - abstract dimensions: inline size maps to
563
    // physical width/height per writing-mode
564
    /// Calculates the inner content-box size from an outer border-box size,
565
    /// correctly accounting for the specified writing mode.
566
    #[must_use]
567
450330
    pub fn inner_size(&self, outer_size: LogicalSize, wm: LayoutWritingMode) -> LogicalSize {
568
450330
        let outer_main = outer_size.main(wm);
569
450330
        let outer_cross = outer_size.cross(wm);
570

            
571
        // The sum of padding and border along the cross (inline) axis.
572
450330
        let cross_axis_spacing = self.padding.cross_sum(wm) + self.border.cross_sum(wm);
573

            
574
        // The sum of padding and border along the main (block) axis.
575
450330
        let main_axis_spacing = self.padding.main_sum(wm) + self.border.main_sum(wm);
576

            
577
        // +spec:box-model:2589b1 - content size = border-box - border - padding, floored at zero
578
        // +spec:box-model:3ab53d - if padding+border > border-box, content floors at 0px
579
450330
        let inner_main = (outer_main - main_axis_spacing).max(0.0);
580
450330
        let inner_cross = (outer_cross - cross_axis_spacing).max(0.0);
581

            
582
450330
        LogicalSize::from_main_cross(inner_main, inner_cross, wm)
583
450330
    }
584

            
585
    // +spec:box-model:aa585e - Content/padding/border/margin edge relationships
586
    // +spec:height-calculation:6c9abb - box model edges: margin > border > padding > content
587
    /// Returns the content-box rect from a border-box rect.
588
    /// Shrinks inward by border + padding on each side.
589
    // +spec:box-model:1720a5 - content of a block box is confined to its content edges
590
    #[must_use]
591
10
    pub fn content_box(&self, border_box: LogicalRect) -> LogicalRect {
592
10
        let x = border_box.origin.x + self.border.left + self.padding.left;
593
10
        let y = border_box.origin.y + self.border.top + self.padding.top;
594
10
        let w =
595
10
            (border_box.size.width - self.border.horizontal_sum() - self.padding.horizontal_sum())
596
10
                .max(0.0);
597
10
        let h = (border_box.size.height - self.border.vertical_sum() - self.padding.vertical_sum())
598
10
            .max(0.0);
599
10
        LogicalRect {
600
10
            origin: LogicalPosition { x, y },
601
10
            size: LogicalSize {
602
10
                width: w,
603
10
                height: h,
604
10
            },
605
10
        }
606
10
    }
607

            
608
    /// Returns the padding-box rect from a border-box rect.
609
    /// Shrinks inward by border on each side.
610
    #[must_use]
611
10
    pub fn padding_box(&self, border_box: LogicalRect) -> LogicalRect {
612
10
        let x = border_box.origin.x + self.border.left;
613
10
        let y = border_box.origin.y + self.border.top;
614
10
        let w = (border_box.size.width - self.border.horizontal_sum()).max(0.0);
615
10
        let h = (border_box.size.height - self.border.vertical_sum()).max(0.0);
616
10
        LogicalRect {
617
10
            origin: LogicalPosition { x, y },
618
10
            size: LogicalSize {
619
10
                width: w,
620
10
                height: h,
621
10
            },
622
10
        }
623
10
    }
624

            
625
    /// Returns the margin-box rect from a border-box rect.
626
    /// Expands outward by margin on each side.
627
    #[must_use]
628
10
    pub fn margin_box(&self, border_box: LogicalRect) -> LogicalRect {
629
10
        let x = border_box.origin.x - self.margin.left;
630
10
        let y = border_box.origin.y - self.margin.top;
631
10
        let w = border_box.size.width + self.margin.horizontal_sum();
632
10
        let h = border_box.size.height + self.margin.vertical_sum();
633
10
        LogicalRect {
634
10
            origin: LogicalPosition { x, y },
635
10
            size: LogicalSize {
636
10
                width: w,
637
10
                height: h,
638
10
            },
639
10
        }
640
10
    }
641

            
642
    // +spec:box-model:0e75c1 - margin, padding, border contribute to layout bounds (default
643
    // line-fit-edge: leading uses line-height model)
644
    /// Total horizontal space consumed by margin + border + padding.
645
    #[must_use]
646
8
    pub fn horizontal_mbp(&self) -> f32 {
647
8
        self.margin.horizontal_sum() + self.border.horizontal_sum() + self.padding.horizontal_sum()
648
8
    }
649

            
650
    /// Total vertical space consumed by margin + border + padding.
651
    #[must_use]
652
8
    pub fn vertical_mbp(&self) -> f32 {
653
8
        self.margin.vertical_sum() + self.border.vertical_sum() + self.padding.vertical_sum()
654
8
    }
655

            
656
    /// Total horizontal space consumed by border + padding only (no margin).
657
    #[must_use]
658
7
    pub fn horizontal_bp(&self) -> f32 {
659
7
        self.border.horizontal_sum() + self.padding.horizontal_sum()
660
7
    }
661

            
662
    /// Total vertical space consumed by border + padding only (no margin).
663
    #[must_use]
664
7
    pub fn vertical_bp(&self) -> f32 {
665
7
        self.border.vertical_sum() + self.padding.vertical_sum()
666
7
    }
667
}
668

            
669
/// Type alias for backwards compatibility.
670
/// TODO: Remove this once all code uses `ResolvedBoxProps` directly.
671
pub type BoxProps = ResolvedBoxProps;
672

            
673
/// Packed representation of box model properties using i16×10 encoding.
674
///
675
/// Stores margin/padding/border as i16 values scaled by 10 (0.1px precision),
676
/// reducing the hot struct from 52B to 26B. Range: ±3276.7px per edge.
677
///
678
/// Only used for storage in `LayoutNodeHot`. The layout solver unpacks to
679
/// `ResolvedBoxProps` (f32) for computation.
680
#[derive(Debug, Clone, Copy, Default)]
681
#[repr(C)]
682
pub struct PackedBoxProps {
683
    pub margin: [i16; 4],  // top, right, bottom, left — ×10
684
    pub padding: [i16; 4], // ×10
685
    pub border: [i16; 4],  // ×10
686
    pub margin_auto: MarginAuto,
687
}
688

            
689
impl PackedBoxProps {
690
    /// Pack a `ResolvedBoxProps` into compact i16×10 encoding.
691
    #[inline]
692
    #[must_use]
693
334758
    pub fn pack(bp: &ResolvedBoxProps) -> Self {
694
334758
        Self {
695
334758
            margin: Self::pack_edge(&bp.margin),
696
334758
            padding: Self::pack_edge(&bp.padding),
697
334758
            border: Self::pack_edge(&bp.border),
698
334758
            margin_auto: bp.margin_auto,
699
334758
        }
700
334758
    }
701

            
702
    /// Unpack to full `ResolvedBoxProps` with f32 values.
703
    #[inline]
704
    #[must_use]
705
4525717
    pub fn unpack(&self) -> ResolvedBoxProps {
706
4525717
        ResolvedBoxProps {
707
4525717
            margin: Self::unpack_edge(&self.margin),
708
4525717
            padding: Self::unpack_edge(&self.padding),
709
4525717
            border: Self::unpack_edge(&self.border),
710
4525717
            margin_auto: self.margin_auto,
711
4525717
        }
712
4525717
    }
713

            
714
    /// Convenience: unpack and call `inner_size` on the result.
715
    #[inline]
716
    #[must_use]
717
117393
    pub fn inner_size(&self, outer_size: LogicalSize, wm: LayoutWritingMode) -> LogicalSize {
718
117393
        self.unpack().inner_size(outer_size, wm)
719
117393
    }
720

            
721
    /// Convenience: unpack and call `content_box` on the result.
722
    #[inline]
723
    #[must_use]
724
5
    pub fn content_box(&self, border_box: LogicalRect) -> LogicalRect {
725
5
        self.unpack().content_box(border_box)
726
5
    }
727

            
728
    /// Convenience: unpack and call `padding_box` on the result.
729
    #[inline]
730
    #[must_use]
731
5
    pub fn padding_box(&self, border_box: LogicalRect) -> LogicalRect {
732
5
        self.unpack().padding_box(border_box)
733
5
    }
734

            
735
    /// Convenience: unpack and call `margin_box` on the result.
736
    #[inline]
737
    #[must_use]
738
5
    pub fn margin_box(&self, border_box: LogicalRect) -> LogicalRect {
739
5
        self.unpack().margin_box(border_box)
740
5
    }
741

            
742
    /// Convenience: unpack and return horizontal MBP.
743
    #[inline]
744
    #[must_use]
745
2
    pub fn horizontal_mbp(&self) -> f32 {
746
2
        self.unpack().horizontal_mbp()
747
2
    }
748

            
749
    /// Convenience: unpack and return vertical MBP.
750
    #[inline]
751
    #[must_use]
752
2
    pub fn vertical_mbp(&self) -> f32 {
753
2
        self.unpack().vertical_mbp()
754
2
    }
755

            
756
    /// Convenience: unpack and return horizontal BP.
757
    #[inline]
758
    #[must_use]
759
2
    pub fn horizontal_bp(&self) -> f32 {
760
2
        self.unpack().horizontal_bp()
761
2
    }
762

            
763
    /// Convenience: unpack and return vertical BP.
764
    #[inline]
765
    #[must_use]
766
2
    pub fn vertical_bp(&self) -> f32 {
767
2
        self.unpack().vertical_bp()
768
2
    }
769

            
770
    #[inline]
771
    #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/counter/fixed-point cast
772
1069816
    fn pack_edge(e: &EdgeSizes) -> [i16; 4] {
773
        const MIN: f32 = i16::MIN as f32;
774
        const MAX: f32 = i16::MAX as f32;
775
1069816
        [
776
1069816
            (e.top * 10.0).round().clamp(MIN, MAX) as i16,
777
1069816
            (e.right * 10.0).round().clamp(MIN, MAX) as i16,
778
1069816
            (e.bottom * 10.0).round().clamp(MIN, MAX) as i16,
779
1069816
            (e.left * 10.0).round().clamp(MIN, MAX) as i16,
780
1069816
        ]
781
1069816
    }
782

            
783
    #[inline]
784
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
785
                                                 // pixel/coord path or to avoid churning call sites
786
                                                 // for a perf-neutral change)
787
13642689
    fn unpack_edge(e: &[i16; 4]) -> EdgeSizes {
788
13642689
        EdgeSizes {
789
13642689
            top: f32::from(e[0]) * 0.1,
790
13642689
            right: f32::from(e[1]) * 0.1,
791
13642689
            bottom: f32::from(e[2]) * 0.1,
792
13642689
            left: f32::from(e[3]) * 0.1,
793
13642689
        }
794
13642689
    }
795
}
796

            
797
// Re-export float and clear types from azul_css
798
pub use azul_css::props::layout::{LayoutClear, LayoutFloat};
799

            
800
// +spec:intrinsic-sizing:af39b6 - min-content, max-content, and stretch fit size definitions
801
// min-content constraint, max-content constraint definitions
802
// and fit-content sizes for both inline and block axes
803
// +spec:height-calculation:e9ec84 - replaced elements have natural dimensions (width, height,
804
// ratio)
805
/// Represents the intrinsic sizing information for an element, calculated
806
/// without knowledge of the final containing block size.
807
// +spec:intrinsic-sizing:127a10 - min-content, max-content, fit-content size definitions
808
// (css-sizing-3 §2.1) +spec:intrinsic-sizing:21f2cb - defines min-content, max-content, and
809
// stretch-fit size terminology +spec:width-calculation:1583c4 - min-content, max-content,
810
// fit-content intrinsic size definitions (§2.1)
811
#[derive(Debug, Clone, Copy, Default)]
812
pub struct IntrinsicSizes {
813
    // +spec:width-calculation:b83d0a - min-content width ("preferred minimum width" in
814
    // CSS2.1§10.3.5) +spec:writing-modes:1583c4 - min-content size in inline axis = size
815
    // fitting contents with all soft wraps taken
816
    /// §2.1 min-content inline size: inline size fitting contents if all soft wraps taken.
817
    pub min_content_width: f32,
818
    // +spec:width-calculation:0c74d3 - max-content width ("preferred width" in CSS2.1§10.3.5)
819
    // +spec:writing-modes:6e85d3 - max-content inline size is the "ideal" size in the inline axis
820
    // (writing-mode-dependent)
821
    /// §2.1 max-content inline size: narrowest inline size if no soft wraps taken.
822
    pub max_content_width: f32,
823
    /// The width specified by CSS properties, if any.
824
    pub preferred_width: Option<f32>,
825
    /// §2.1 min-content block size: for block containers, tables, and inline boxes,
826
    /// equivalent to max-content block size.
827
    pub min_content_height: f32,
828
    // +spec:writing-modes:8c94e2 - max-content block size is the "ideal" block size after layout
829
    /// §2.1 max-content block size: "ideal" block size, usually content height after layout.
830
    pub max_content_height: f32,
831
    /// The height specified by CSS properties, if any.
832
    pub preferred_height: Option<f32>,
833
    // +spec:intrinsic-sizing:af39b6 - natural (intrinsic) aspect ratio of a replaced element
834
    // +spec:height-calculation:e9ec84 - replaced-element natural width/height/ratio
835
    /// The element's natural aspect ratio (inline / block), if it has one — e.g. a
836
    /// replaced element with intrinsic dimensions. `None` for non-replaced content.
837
    pub preferred_aspect_ratio: Option<f32>,
838
}
839

            
840
impl IntrinsicSizes {
841
    // +spec:intrinsic-sizing:127a10 - fit-content = clamp(min-content, stretch-fit, max-content)
842
    // +spec:intrinsic-sizing:21f2cb - stretch-fit size drawn from available (containing-block)
843
    // space
844
    /// CSS Sizing §2.1 fit-content **inline** size:
845
    /// `clamp(min-content, stretch-fit, max-content)`, where the stretch-fit size is the
846
    /// `available_inline_size` (the space the containing block offers in the inline axis).
847
    /// Equal to `max(min_content, min(stretch_fit, max_content))`.
848
    #[must_use]
849
3
    pub const fn fit_content_width(&self, available_inline_size: f32) -> f32 {
850
3
        available_inline_size
851
3
            .min(self.max_content_width)
852
3
            .max(self.min_content_width)
853
3
    }
854

            
855
    /// CSS Sizing §2.1 fit-content **block** size:
856
    /// `clamp(min-content, stretch-fit, max-content)` in the block axis.
857
    #[must_use]
858
3
    pub const fn fit_content_height(&self, available_block_size: f32) -> f32 {
859
3
        available_block_size
860
3
            .min(self.max_content_height)
861
3
            .max(self.min_content_height)
862
3
    }
863
}
864

            
865
// ============================================================================
866
// WRITING MODE SUPPORT
867
// ============================================================================
868

            
869
/// Captures the resolved writing mode context for a node.
870
///
871
/// This struct bundles together all the CSS properties that affect how
872
/// logical directions (inline/block) map to physical directions (x/y).
873
/// Spec agents should use this struct to implement writing-mode-aware layout.
874
///
875
/// # CSS Writing Modes Level 4
876
///
877
/// - `writing-mode` determines the block flow direction and inline base direction
878
/// - `direction` determines the inline base direction (ltr or rtl)
879
/// - `text-orientation` determines glyph orientation in vertical writing modes
880
// +spec:block-formatting-context:333dcb - typographic mode captured by text_orientation field
881
// +spec:block-formatting-context:66eb6d - text-orientation property (mixed|upright|sideways)
882
// integrated into WritingModeContext +spec:block-formatting-context:8be1b0 - writing modes and
883
// vertical text orientation context (UTN#22) +spec:display-property:0a39dc - text-orientation
884
// affects inline-level alignment via WritingModeContext +spec:display-property:591355 -
885
// bidirectionality support via direction property in WritingModeContext
886
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
887
pub struct WritingModeContext {
888
    pub writing_mode: LayoutWritingMode,
889
    pub direction: StyleDirection,
890
    // +spec:block-formatting-context:925cfe - text-orientation mixed/upright for horizontal
891
    // scripts in vertical mode
892
    pub text_orientation: StyleTextOrientation,
893
}
894

            
895
impl Default for WritingModeContext {
896
303295
    fn default() -> Self {
897
303295
        Self {
898
303295
            writing_mode: LayoutWritingMode::HorizontalTb,
899
303295
            direction: StyleDirection::Ltr,
900
303295
            text_orientation: StyleTextOrientation::Mixed,
901
303295
        }
902
303295
    }
903
}
904

            
905
impl WritingModeContext {
906
    /// Constructs a `WritingModeContext`, applying spec-mandated overrides.
907
    // +spec:writing-modes:8307e4 - text-orientation: upright forces used direction to ltr
908
    #[must_use]
909
112103
    pub fn new(
910
112103
        writing_mode: LayoutWritingMode,
911
112103
        direction: StyleDirection,
912
112103
        text_orientation: StyleTextOrientation,
913
112103
    ) -> Self {
914
        // CSS Writing Modes Level 4 §5.1: text-orientation: upright causes
915
        // the used value of direction to be ltr, and all characters to be
916
        // treated as strong LTR for bidi reordering purposes.
917
112103
        let used_direction = if text_orientation == StyleTextOrientation::Upright {
918
13
            StyleDirection::Ltr
919
        } else {
920
112090
            direction
921
        };
922
112103
        Self {
923
112103
            writing_mode,
924
112103
            direction: used_direction,
925
112103
            text_orientation,
926
112103
        }
927
112103
    }
928

            
929
    // +spec:writing-modes:458d31 - text-orientation:upright forces used direction to ltr
930
    /// Returns the used value of `direction`.
931
    ///
932
    /// The upright override is already applied in `new()`, so this just
933
    /// returns the stored direction.
934
    #[must_use]
935
14
    pub const fn used_direction(&self) -> StyleDirection {
936
14
        self.direction
937
14
    }
938

            
939
    // +spec:containing-block:c205e5 - orthogonal flow: child writing mode perpendicular to
940
    // containing block's
941

            
942
    // +spec:block-formatting-context:6225cb - vertical writing modes: line-over is right,
943
    // line-under is left +spec:block-formatting-context:9a4269 - vertical vs horizontal script
944
    // classification
945
    /// Returns true if the writing mode is horizontal (`HorizontalTb`).
946
    ///
947
    /// When true, the inline axis is horizontal and the block axis is vertical.
948
    #[must_use]
949
58202
    pub const fn is_horizontal(&self) -> bool {
950
58202
        matches!(self.writing_mode, LayoutWritingMode::HorizontalTb)
951
58202
    }
952

            
953
    /// Returns true if the inline size corresponds to the physical width.
954
    ///
955
    /// In horizontal writing modes, inline size = width.
956
    /// In vertical writing modes, inline size = height.
957
    // +spec:block-formatting-context:bb9845 - orthogonal flows: inline/block axis mapping
958
    #[must_use]
959
13
    pub const fn inline_size_is_width(&self) -> bool {
960
13
        self.is_horizontal()
961
13
    }
962

            
963
    /// Returns true if the block size corresponds to the physical height.
964
    ///
965
    /// In horizontal writing modes, block size = height.
966
    /// In vertical writing modes, block size = width.
967
    #[must_use]
968
13
    pub const fn block_size_is_height(&self) -> bool {
969
13
        self.is_horizontal()
970
13
    }
971

            
972
    // +spec:writing-modes:32541a - direction property controls inline text direction via stylesheet
973
    /// Returns true if the inline direction is reversed (RTL in horizontal,
974
    /// or bottom-to-top in certain vertical modes).
975
    #[must_use]
976
10
    pub fn is_inline_reversed(&self) -> bool {
977
10
        self.used_direction() == StyleDirection::Rtl
978
10
    }
979
}
980

            
981
#[cfg(test)]
982
#[allow(clippy::float_cmp, clippy::unreadable_literal)]
983
mod autotest_generated {
984
    use super::*;
985

            
986
    // ---------------------------------------------------------------- helpers
987

            
988
    /// All writing modes, so every mapping test can be run exhaustively.
989
    const ALL_WM: [LayoutWritingMode; 3] = [
990
        LayoutWritingMode::HorizontalTb,
991
        LayoutWritingMode::VerticalRl,
992
        LayoutWritingMode::VerticalLr,
993
    ];
994

            
995
    fn edges(top: f32, right: f32, bottom: f32, left: f32) -> EdgeSizes {
996
        EdgeSizes {
997
            top,
998
            right,
999
            bottom,
            left,
        }
    }
    fn rect(x: f32, y: f32, w: f32, h: f32) -> LogicalRect {
        LogicalRect {
            origin: LogicalPosition { x, y },
            size: LogicalSize {
                width: w,
                height: h,
            },
        }
    }
    /// `EdgeSizes`/`ResolvedBoxProps` carry no `PartialEq`, and the packed
    /// encoding is lossy by design, so float comparisons need a tolerance.
    fn close(a: f32, b: f32, eps: f32) -> bool {
        (a - b).abs() <= eps
    }
    fn params(cb: LogicalSize, vp: LogicalSize, font: f32, root: f32) -> ResolutionParams {
        ResolutionParams {
            containing_block: cb,
            viewport_size: vp,
            element_font_size: font,
            root_font_size: root,
        }
    }
    /// 800x600 containing block, 1000x500 viewport, 16px element / 10px root font.
    /// Every dimension is distinct so a transposed axis cannot pass by accident.
    fn distinct_params() -> ResolutionParams {
        params(
            LogicalSize::new(800.0, 600.0),
            LogicalSize::new(1000.0, 500.0),
            16.0,
            10.0,
        )
    }
    fn props(margin: EdgeSizes, padding: EdgeSizes, border: EdgeSizes) -> ResolvedBoxProps {
        ResolvedBoxProps {
            margin,
            padding,
            border,
            margin_auto: MarginAuto::default(),
        }
    }
    // ================================================================
    // EdgeSizes: sums
    // ================================================================
    #[test]
    fn edge_sizes_sums_pick_the_right_pair_of_edges() {
        let e = edges(1.0, 2.0, 4.0, 8.0); // top, right, bottom, left
        assert_eq!(e.horizontal_sum(), 10.0, "horizontal = left + right");
        assert_eq!(e.vertical_sum(), 5.0, "vertical = top + bottom");
    }
    #[test]
    fn edge_sizes_default_is_all_zero() {
        let e = EdgeSizes::default();
        assert_eq!(e.horizontal_sum(), 0.0);
        assert_eq!(e.vertical_sum(), 0.0);
        for wm in ALL_WM {
            assert_eq!(e.main_sum(wm), 0.0);
            assert_eq!(e.cross_sum(wm), 0.0);
        }
    }
    #[test]
    fn edge_sizes_sums_saturate_to_infinity_instead_of_panicking() {
        // f32::MAX + f32::MAX overflows to +inf; it must not panic or wrap.
        let e = edges(f32::MAX, f32::MAX, f32::MAX, f32::MAX);
        assert!(e.horizontal_sum().is_infinite() && e.horizontal_sum() > 0.0);
        assert!(e.vertical_sum().is_infinite() && e.vertical_sum() > 0.0);
    }
    #[test]
    fn edge_sizes_opposing_infinities_produce_nan_not_a_panic() {
        // inf + (-inf) is NaN by IEEE-754. The point is that it is deterministic
        // and does not trap — nothing downstream may assume a finite sum.
        let e = edges(
            f32::INFINITY,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::NEG_INFINITY,
        );
        assert!(e.horizontal_sum().is_nan());
        assert!(e.vertical_sum().is_nan());
    }
    #[test]
    fn edge_sizes_nan_edges_propagate_without_panicking() {
        let e = edges(f32::NAN, 1.0, 2.0, 3.0);
        assert!(e.vertical_sum().is_nan());
        assert_eq!(
            e.horizontal_sum(),
            4.0,
            "a NaN top must not poison left+right"
        );
        for wm in ALL_WM {
            let _ = e.main_sum(wm);
            let _ = e.cross_sum(wm);
        }
    }
    // ================================================================
    // EdgeSizes: writing-mode axis mapping
    // ================================================================
    #[test]
    fn edge_sizes_axis_mapping_is_exact_for_every_writing_mode() {
        let e = edges(1.0, 2.0, 4.0, 8.0); // top, right, bottom, left
        // horizontal-tb: block (main) axis is vertical, inline (cross) axis is horizontal.
        let h = LayoutWritingMode::HorizontalTb;
        assert_eq!(e.main_start(h), 1.0, "main-start = top");
        assert_eq!(e.main_end(h), 4.0, "main-end = bottom");
        assert_eq!(e.cross_start(h), 8.0, "cross-start = left");
        assert_eq!(e.cross_end(h), 2.0, "cross-end = right");
        // vertical-*: block (main) axis is horizontal, inline (cross) axis is vertical.
        for wm in [LayoutWritingMode::VerticalRl, LayoutWritingMode::VerticalLr] {
            assert_eq!(e.main_start(wm), 8.0, "main-start = left");
            assert_eq!(e.main_end(wm), 2.0, "main-end = right");
            assert_eq!(e.cross_start(wm), 1.0, "cross-start = top");
            assert_eq!(e.cross_end(wm), 4.0, "cross-end = bottom");
        }
    }
    // +spec:block-formatting-context:a49f9e - line-over/line-under accessors.
    #[test]
    fn edge_sizes_line_over_under_is_line_relative_not_physical() {
        let e = edges(1.0, 2.0, 4.0, 8.0); // top, right, bottom, left
        // horizontal-tb: over = top, under = bottom (coincides with main_start/end).
        let h = LayoutWritingMode::HorizontalTb;
        assert_eq!(e.line_over(h), 1.0, "line-over = top in horizontal-tb");
        assert_eq!(e.line_under(h), 4.0, "line-under = bottom in horizontal-tb");
        assert_eq!(
            e.line_over(h),
            e.main_start(h),
            "over == main-start only in horizontal-tb"
        );
        // vertical modes: over = right, under = left (CSS Writing Modes L4 §6.3).
        // Crucially this differs from main_start/main_end (left/right), proving the
        // line-relative accessor is not just an alias of the physical block axis.
        for wm in [LayoutWritingMode::VerticalRl, LayoutWritingMode::VerticalLr] {
            assert_eq!(e.line_over(wm), 2.0, "line-over = right in vertical modes");
            assert_eq!(e.line_under(wm), 8.0, "line-under = left in vertical modes");
            assert_ne!(
                e.line_over(wm),
                e.main_start(wm),
                "over != main-start in vertical modes"
            );
        }
        // Sum picks the line-relative pair, independent of writing mode orientation.
        assert_eq!(e.line_over_under_sum(h), 5.0);
        assert_eq!(e.line_over_under_sum(LayoutWritingMode::VerticalRl), 10.0);
    }
    // +spec:writing-modes:829cd7 / c0ae9c - direction-aware inline-start/end accessors.
    #[test]
    fn edge_sizes_inline_start_end_depend_on_direction() {
        let e = edges(1.0, 2.0, 4.0, 8.0); // top, right, bottom, left
        for wm in ALL_WM {
            // LTR: inline-start = line-left = cross_start; inline-end = line-right = cross_end.
            assert_eq!(
                e.inline_start(wm, StyleDirection::Ltr),
                e.cross_start(wm),
                "LTR inline-start = cross-start (line-left)"
            );
            assert_eq!(
                e.inline_end(wm, StyleDirection::Ltr),
                e.cross_end(wm),
                "LTR inline-end = cross-end (line-right)"
            );
            // RTL: the two ends swap — inline-start moves to line-right.
            assert_eq!(
                e.inline_start(wm, StyleDirection::Rtl),
                e.cross_end(wm),
                "RTL inline-start = cross-end (line-right)"
            );
            assert_eq!(
                e.inline_end(wm, StyleDirection::Rtl),
                e.cross_start(wm),
                "RTL inline-end = cross-start (line-left)"
            );
            // The sum covers the whole inline axis regardless of direction.
            assert_eq!(
                e.inline_sum(wm, StyleDirection::Ltr),
                e.inline_sum(wm, StyleDirection::Rtl),
                "inline-sum is direction-independent"
            );
            assert_eq!(e.inline_sum(wm, StyleDirection::Ltr), e.cross_sum(wm));
        }
        // Concrete horizontal-tb values: LTR start=left(8), RTL start=right(2).
        let h = LayoutWritingMode::HorizontalTb;
        assert_eq!(e.inline_start(h, StyleDirection::Ltr), 8.0);
        assert_eq!(e.inline_start(h, StyleDirection::Rtl), 2.0);
    }
    #[test]
    fn edge_sizes_main_and_cross_sums_partition_the_four_edges() {
        // Whatever the writing mode, main+cross must account for each edge exactly
        // once — a transposition bug in one arm would break this identity.
        let e = edges(1.0, 2.0, 4.0, 8.0);
        for wm in ALL_WM {
            assert_eq!(e.main_start(wm) + e.main_end(wm), e.main_sum(wm));
            assert_eq!(e.cross_start(wm) + e.cross_end(wm), e.cross_sum(wm));
            assert_eq!(
                e.main_sum(wm) + e.cross_sum(wm),
                e.horizontal_sum() + e.vertical_sum(),
                "{wm:?}: main+cross must cover all four edges"
            );
        }
    }
    #[test]
    fn edge_sizes_axis_accessors_survive_extreme_values() {
        let e = edges(f32::MAX, f32::MIN, f32::INFINITY, f32::NEG_INFINITY);
        for wm in ALL_WM {
            let _ = e.main_start(wm);
            let _ = e.main_end(wm);
            let _ = e.cross_start(wm);
            let _ = e.cross_end(wm);
            let _ = e.main_sum(wm);
            let _ = e.cross_sum(wm);
        }
    }
    // ================================================================
    // UnresolvedMargin
    // ================================================================
    #[test]
    fn unresolved_margin_is_auto_only_for_the_auto_variant() {
        assert!(UnresolvedMargin::Auto.is_auto());
        assert!(!UnresolvedMargin::Zero.is_auto());
        assert!(!UnresolvedMargin::Length(PixelValue::const_px(10)).is_auto());
        // A zero-valued length is still *not* `auto`.
        assert!(!UnresolvedMargin::Length(PixelValue::zero()).is_auto());
        assert!(
            !UnresolvedMargin::default().is_auto(),
            "default is Zero, not Auto"
        );
    }
    #[test]
    fn unresolved_margin_auto_and_zero_both_resolve_to_zero_px() {
        let ctx = distinct_params().to_resolution_context();
        assert_eq!(UnresolvedMargin::Zero.resolve(&ctx), 0.0);
        // `auto` is resolved later by the layout algorithm; here it must read as 0.
        assert_eq!(UnresolvedMargin::Auto.resolve(&ctx), 0.0);
    }
    #[test]
    fn unresolved_margin_length_resolves_by_metric() {
        let ctx = distinct_params().to_resolution_context(); // 800x600 cb, 16px font, 10px root
        let r = |pv: PixelValue| UnresolvedMargin::Length(pv).resolve(&ctx);
        assert_eq!(r(PixelValue::px(12.5)), 12.5);
        assert_eq!(r(PixelValue::em(2.0)), 32.0, "em = 2 x element font-size");
        assert_eq!(r(PixelValue::rem(2.0)), 20.0, "rem = 2 x root font-size");
    }
    #[test]
    fn unresolved_margin_percent_resolves_against_containing_block_width() {
        // CSS 2.1 §8.3: percentage margins ALWAYS refer to the containing block
        // *width* — never the height. With a 800x600 block, 50% must be 400, not 300.
        let ctx = distinct_params().to_resolution_context();
        let got = UnresolvedMargin::Length(PixelValue::percent(50.0)).resolve(&ctx);
        assert_eq!(got, 400.0);
        assert_ne!(
            got, 300.0,
            "percentage margin must not use the block height"
        );
    }
    #[test]
    fn unresolved_margin_nan_length_resolves_to_zero_not_nan() {
        // PixelValue stores a fixed-point isize, and `f32 as isize` saturates NaN
        // to 0 — so a NaN can never escape into layout as a NaN margin.
        let ctx = distinct_params().to_resolution_context();
        let got = UnresolvedMargin::Length(PixelValue::px(f32::NAN)).resolve(&ctx);
        assert!(!got.is_nan(), "a NaN px value must not survive resolution");
        assert_eq!(got, 0.0);
    }
    #[test]
    fn unresolved_margin_huge_length_saturates_to_a_finite_value() {
        let ctx = distinct_params().to_resolution_context();
        for v in [f32::MAX, f32::MIN, f32::INFINITY, f32::NEG_INFINITY] {
            let got = UnresolvedMargin::Length(PixelValue::px(v)).resolve(&ctx);
            assert!(got.is_finite(), "px({v}) resolved to a non-finite {got}");
        }
    }
    #[test]
    fn unresolved_margin_percent_of_a_nan_containing_block_is_nan_not_a_panic() {
        // The containing block is a raw f32 and is NOT sanitized, so a NaN block
        // size *does* propagate. Documenting the real behaviour: deterministic NaN,
        // no panic — the guard has to live at the caller, not here.
        let p = params(
            LogicalSize::new(f32::NAN, f32::NAN),
            LogicalSize::new(1000.0, 500.0),
            16.0,
            10.0,
        );
        let got =
            UnresolvedMargin::Length(PixelValue::percent(50.0)).resolve(&p.to_resolution_context());
        assert!(got.is_nan());
    }
    // ================================================================
    // UnresolvedEdge
    // ================================================================
    #[test]
    fn unresolved_edge_new_assigns_fields_in_top_right_bottom_left_order() {
        // The classic CSS shorthand transposition bug: argument order is TRBL.
        let e = UnresolvedEdge::new(1_u8, 2, 4, 8);
        assert_eq!(e.top, 1);
        assert_eq!(e.right, 2);
        assert_eq!(e.bottom, 4);
        assert_eq!(e.left, 8);
    }
    #[test]
    fn unresolved_edge_new_accepts_extreme_payloads() {
        let e = UnresolvedEdge::new(f32::NAN, f32::INFINITY, f32::MAX, f32::MIN);
        assert!(e.top.is_nan());
        assert!(e.right.is_infinite());
        assert_eq!(e.bottom, f32::MAX);
        assert_eq!(e.left, f32::MIN);
    }
    #[test]
    fn get_margin_auto_flags_exactly_the_auto_sides() {
        let e = UnresolvedEdge::new(
            UnresolvedMargin::Zero,                            // top
            UnresolvedMargin::Auto,                            // right
            UnresolvedMargin::Length(PixelValue::const_px(5)), // bottom
            UnresolvedMargin::Auto,                            // left
        );
        let a = e.get_margin_auto();
        assert!(!a.top);
        assert!(a.right);
        assert!(!a.bottom);
        assert!(a.left);
    }
    #[test]
    fn get_margin_auto_on_default_edge_flags_nothing() {
        let a = UnresolvedEdge::<UnresolvedMargin>::default().get_margin_auto();
        assert!(!a.top && !a.right && !a.bottom && !a.left);
    }
    #[test]
    fn unresolved_margin_edge_resolve_keeps_each_side_separate() {
        let ctx = distinct_params().to_resolution_context();
        let e = UnresolvedEdge::new(
            UnresolvedMargin::Length(PixelValue::px(1.0)), // top
            UnresolvedMargin::Length(PixelValue::px(2.0)), // right
            UnresolvedMargin::Auto,                        // bottom -> 0
            UnresolvedMargin::Length(PixelValue::px(8.0)), // left
        );
        let r = e.resolve(&ctx);
        assert_eq!(r.top, 1.0);
        assert_eq!(r.right, 2.0);
        assert_eq!(r.bottom, 0.0, "auto resolves to 0 px here");
        assert_eq!(r.left, 8.0);
    }
    #[test]
    fn pixel_edge_resolve_drops_percentages_on_border_width() {
        // CSS Backgrounds 3 §4.1: `%` is not a valid border-width. The resolver
        // must yield 0 rather than silently resolving against the containing block.
        let ctx = distinct_params().to_resolution_context();
        let e = UnresolvedEdge::new(
            PixelValue::percent(50.0),
            PixelValue::percent(50.0),
            PixelValue::percent(50.0),
            PixelValue::percent(50.0),
        );
        let r = e.resolve(&ctx, PropertyContext::BorderWidth);
        assert_eq!(r.top, 0.0);
        assert_eq!(r.right, 0.0);
        assert_eq!(r.bottom, 0.0);
        assert_eq!(r.left, 0.0);
    }
    #[test]
    fn pixel_edge_resolve_uses_block_width_for_vertical_padding_percentages() {
        // CSS 2.1 §8.4: padding-top/bottom percentages also refer to the containing
        // block WIDTH. With 800x600, every side must land on 80, never 60.
        let ctx = distinct_params().to_resolution_context();
        let e = UnresolvedEdge::new(
            PixelValue::percent(10.0),
            PixelValue::percent(10.0),
            PixelValue::percent(10.0),
            PixelValue::percent(10.0),
        );
        let r = e.resolve(&ctx, PropertyContext::Padding);
        assert_eq!(r.top, 80.0, "padding-top % must use the width");
        assert_eq!(r.bottom, 80.0, "padding-bottom % must use the width");
        assert_eq!(r.left, 80.0);
        assert_eq!(r.right, 80.0);
    }
    #[test]
    fn pixel_edge_resolve_of_viewport_units_uses_the_viewport_not_the_block() {
        let ctx = distinct_params().to_resolution_context(); // viewport 1000x500
        let e = UnresolvedEdge::new(
            PixelValue::from_metric(SizeMetric::Vw, 10.0),
            PixelValue::from_metric(SizeMetric::Vh, 10.0),
            PixelValue::from_metric(SizeMetric::Vmin, 10.0),
            PixelValue::from_metric(SizeMetric::Vmax, 10.0),
        );
        let r = e.resolve(&ctx, PropertyContext::Padding);
        assert_eq!(r.top, 100.0, "10vw of 1000");
        assert_eq!(r.right, 50.0, "10vh of 500");
        assert_eq!(r.bottom, 50.0, "10vmin of min(1000,500)");
        assert_eq!(r.left, 100.0, "10vmax of max(1000,500)");
    }
    // ================================================================
    // ResolutionParams
    // ================================================================
    #[test]
    fn to_resolution_context_maps_every_field() {
        let ctx = distinct_params().to_resolution_context();
        assert_eq!(ctx.element_font_size, 16.0);
        assert_eq!(ctx.root_font_size, 10.0);
        assert_eq!(ctx.containing_block_size.width, 800.0);
        assert_eq!(ctx.containing_block_size.height, 600.0);
        assert_eq!(ctx.viewport_size.width, 1000.0);
        assert_eq!(ctx.viewport_size.height, 500.0);
        assert!(
            ctx.element_size.is_none(),
            "element size is unknown pre-layout"
        );
    }
    #[test]
    fn to_resolution_context_aliases_parent_font_size_onto_the_element_font_size() {
        // Documented quirk: for non-font properties `em` resolves against the
        // element's OWN font-size, so the context deliberately reports
        // parent == element. Using it for font-size resolution would be wrong.
        let ctx = distinct_params().to_resolution_context();
        assert_eq!(ctx.parent_font_size, ctx.element_font_size);
        assert_eq!(ctx.parent_font_size, 16.0);
    }
    #[test]
    fn to_resolution_context_passes_extreme_values_through_unchanged() {
        let p = params(
            LogicalSize::new(f32::MAX, f32::NAN),
            LogicalSize::new(f32::INFINITY, 0.0),
            0.0,
            f32::MIN,
        );
        let ctx = p.to_resolution_context();
        assert_eq!(ctx.containing_block_size.width, f32::MAX);
        assert!(ctx.containing_block_size.height.is_nan());
        assert!(ctx.viewport_size.width.is_infinite());
        assert_eq!(ctx.element_font_size, 0.0);
        assert_eq!(ctx.root_font_size, f32::MIN);
    }
    #[test]
    fn zero_font_size_context_resolves_em_to_zero_without_dividing_by_it() {
        let p = params(LogicalSize::zero(), LogicalSize::zero(), 0.0, 0.0);
        let ctx = p.to_resolution_context();
        assert_eq!(
            PixelValue::em(10.0).resolve_with_context(&ctx, PropertyContext::Margin),
            0.0
        );
        assert_eq!(
            PixelValue::rem(10.0).resolve_with_context(&ctx, PropertyContext::Margin),
            0.0
        );
        // A zero-sized viewport must not turn vmin/vmax into NaN.
        let vmin = PixelValue::from_metric(SizeMetric::Vmin, 50.0);
        assert_eq!(
            vmin.resolve_with_context(&ctx, PropertyContext::Padding),
            0.0
        );
    }
    // ================================================================
    // UnresolvedBoxProps
    // ================================================================
    #[test]
    fn unresolved_box_props_default_resolves_to_an_all_zero_box() {
        let r = UnresolvedBoxProps::default().resolve(&distinct_params());
        assert_eq!(r.horizontal_mbp(), 0.0);
        assert_eq!(r.vertical_mbp(), 0.0);
        assert!(!r.margin_auto.left && !r.margin_auto.right);
    }
    #[test]
    fn unresolved_box_props_resolve_applies_the_right_property_context_per_edge() {
        let p = distinct_params(); // 800x600 block
        let b = UnresolvedBoxProps {
            vertical_writing_mode: false,
            margin: UnresolvedEdge::new(
                UnresolvedMargin::Auto,
                UnresolvedMargin::Length(PixelValue::percent(10.0)), // -> 80 (width)
                UnresolvedMargin::Zero,
                UnresolvedMargin::Auto,
            ),
            padding: UnresolvedEdge::new(
                PixelValue::percent(10.0), // -> 80 (width, even on the top edge)
                PixelValue::px(4.0),
                PixelValue::px(4.0),
                PixelValue::px(4.0),
            ),
            border: UnresolvedEdge::new(
                PixelValue::percent(10.0), // -> 0 (percent is invalid on border-width)
                PixelValue::px(2.0),
                PixelValue::px(2.0),
                PixelValue::px(2.0),
            ),
        };
        let r = b.resolve(&p);
        assert_eq!(r.margin.top, 0.0, "auto margin resolves to 0 px");
        assert_eq!(r.margin.right, 80.0);
        assert_eq!(r.padding.top, 80.0);
        assert_eq!(r.border.top, 0.0, "percent border-width must collapse to 0");
        assert_eq!(r.border.left, 2.0);
        // The auto flags must survive resolution — they are what drives centering.
        assert!(r.margin_auto.top);
        assert!(r.margin_auto.left);
        assert!(!r.margin_auto.right);
        assert!(!r.margin_auto.bottom);
    }
    // ================================================================
    // ResolvedBoxProps::inner_size
    // ================================================================
    #[test]
    fn inner_size_of_a_zero_box_is_zero() {
        let bp = ResolvedBoxProps::default();
        for wm in ALL_WM {
            let s = bp.inner_size(LogicalSize::zero(), wm);
            assert_eq!(s.width, 0.0);
            assert_eq!(s.height, 0.0);
        }
    }
    #[test]
    fn inner_size_subtracts_border_and_padding_but_not_margin() {
        let bp = props(
            edges(100.0, 100.0, 100.0, 100.0), // margin — must be ignored
            edges(1.0, 2.0, 4.0, 8.0),         // padding
            edges(10.0, 20.0, 30.0, 40.0),     // border
        );
        // width  loses left+right: (8+2) + (40+20) = 70
        // height loses top+bottom: (1+4) + (10+30) = 45
        let s = bp.inner_size(
            LogicalSize::new(200.0, 100.0),
            LayoutWritingMode::HorizontalTb,
        );
        assert_eq!(s.width, 130.0);
        assert_eq!(s.height, 55.0);
    }
    #[test]
    fn inner_size_is_identical_in_every_writing_mode() {
        // Physically, content-box = border-box minus the same four edges regardless
        // of writing mode. The main/cross indirection must cancel out exactly; a
        // transposed arm in one mode would show up right here.
        let bp = props(
            EdgeSizes::default(),
            edges(1.0, 2.0, 4.0, 8.0),
            edges(10.0, 20.0, 30.0, 40.0),
        );
        let outer = LogicalSize::new(200.0, 100.0);
        let base = bp.inner_size(outer, LayoutWritingMode::HorizontalTb);
        for wm in ALL_WM {
            let s = bp.inner_size(outer, wm);
            assert_eq!(s.width, base.width, "{wm:?} width diverged");
            assert_eq!(s.height, base.height, "{wm:?} height diverged");
        }
    }
    #[test]
    fn inner_size_floors_at_zero_when_border_and_padding_exceed_the_box() {
        // CSS: if padding+border overflow the border-box, content is 0 — never negative.
        let bp = props(
            EdgeSizes::default(),
            edges(100.0, 100.0, 100.0, 100.0),
            edges(100.0, 100.0, 100.0, 100.0),
        );
        for wm in ALL_WM {
            let s = bp.inner_size(LogicalSize::new(10.0, 10.0), wm);
            assert_eq!(s.width, 0.0, "{wm:?}");
            assert_eq!(s.height, 0.0, "{wm:?}");
            assert!(s.width >= 0.0 && s.height >= 0.0);
        }
    }
    #[test]
    fn inner_size_never_returns_nan() {
        // `.max(0.0)` discards a NaN operand, so NaN can only ever collapse to 0.
        let nan_bp = props(
            EdgeSizes::default(),
            edges(f32::NAN, 0.0, 0.0, 0.0),
            EdgeSizes::default(),
        );
        let cases = [
            (
                ResolvedBoxProps::default(),
                LogicalSize::new(f32::NAN, f32::NAN),
            ),
            (nan_bp, LogicalSize::new(100.0, 100.0)),
            (
                // inf - inf = NaN, which must still floor to 0 rather than escape.
                props(
                    EdgeSizes::default(),
                    edges(f32::INFINITY, 0.0, f32::INFINITY, 0.0),
                    EdgeSizes::default(),
                ),
                LogicalSize::new(f32::INFINITY, f32::INFINITY),
            ),
        ];
        for (bp, outer) in cases {
            for wm in ALL_WM {
                let s = bp.inner_size(outer, wm);
                assert!(!s.width.is_nan(), "{wm:?}: NaN width escaped inner_size");
                assert!(!s.height.is_nan(), "{wm:?}: NaN height escaped inner_size");
                assert!(s.width >= 0.0 && s.height >= 0.0);
            }
        }
    }
    #[test]
    fn inner_size_at_f32_max_stays_finite_and_non_negative() {
        let bp = props(
            EdgeSizes::default(),
            edges(1.0, 2.0, 4.0, 8.0),
            edges(1.0, 1.0, 1.0, 1.0),
        );
        for wm in ALL_WM {
            let s = bp.inner_size(LogicalSize::new(f32::MAX, f32::MAX), wm);
            assert!(s.width.is_finite() && s.height.is_finite());
            assert!(s.width > 0.0 && s.height > 0.0);
        }
    }
    #[test]
    fn inner_size_with_negative_outer_size_floors_to_zero() {
        let bp = ResolvedBoxProps::default();
        for wm in ALL_WM {
            let s = bp.inner_size(LogicalSize::new(-100.0, -50.0), wm);
            assert_eq!(s.width, 0.0, "{wm:?}");
            assert_eq!(s.height, 0.0, "{wm:?}");
        }
    }
    #[test]
    fn inner_size_with_negative_padding_grows_the_content_box() {
        // Negative border/padding is not reachable from CSS, but the struct permits
        // it — assert the arithmetic is plain subtraction rather than something that
        // silently clamps mid-way.
        let bp = props(
            EdgeSizes::default(),
            edges(-5.0, -5.0, -5.0, -5.0),
            EdgeSizes::default(),
        );
        let s = bp.inner_size(
            LogicalSize::new(100.0, 100.0),
            LayoutWritingMode::HorizontalTb,
        );
        assert_eq!(s.width, 110.0);
        assert_eq!(s.height, 110.0);
    }
    // ================================================================
    // ResolvedBoxProps: box rects
    // ================================================================
    #[test]
    fn content_box_shrinks_by_border_plus_padding() {
        let bp = props(
            edges(100.0, 100.0, 100.0, 100.0), // margin is irrelevant here
            edges(1.0, 2.0, 4.0, 8.0),         // padding TRBL
            edges(10.0, 20.0, 30.0, 40.0),     // border TRBL
        );
        let got = bp.content_box(rect(1000.0, 2000.0, 200.0, 100.0));
        // origin moves in by border+padding on the start edges: left 40+8, top 10+1
        // size shrinks by both sides: width 200-(40+20)-(8+2)=130, height 100-(10+30)-(1+4)=55
        assert_eq!(got, rect(1048.0, 2011.0, 130.0, 55.0));
    }
    #[test]
    fn padding_box_shrinks_by_border_only() {
        let bp = props(
            EdgeSizes::default(),
            edges(1.0, 2.0, 4.0, 8.0),
            edges(10.0, 20.0, 30.0, 40.0),
        );
        let got = bp.padding_box(rect(1000.0, 2000.0, 200.0, 100.0));
        assert_eq!(got, rect(1040.0, 2010.0, 140.0, 60.0));
    }
    #[test]
    fn margin_box_expands_by_margin_only() {
        let bp = props(
            edges(1.0, 2.0, 4.0, 8.0), // margin TRBL
            edges(99.0, 99.0, 99.0, 99.0),
            edges(99.0, 99.0, 99.0, 99.0),
        );
        let got = bp.margin_box(rect(1000.0, 2000.0, 200.0, 100.0));
        // origin moves OUT by left/top margin; size grows by both sides.
        assert_eq!(got, rect(992.0, 1999.0, 210.0, 105.0));
    }
    #[test]
    fn box_rects_nest_content_inside_padding_inside_border_inside_margin() {
        let bp = props(
            edges(5.0, 6.0, 7.0, 8.0),
            edges(1.0, 2.0, 3.0, 4.0),
            edges(9.0, 10.0, 11.0, 12.0),
        );
        let border_box = rect(50.0, 60.0, 400.0, 300.0);
        let content = bp.content_box(border_box);
        let padding = bp.padding_box(border_box);
        let margin = bp.margin_box(border_box);
        // Each layer must sit strictly inside the next one out.
        assert!(margin.origin.x <= border_box.origin.x);
        assert!(border_box.origin.x <= padding.origin.x);
        assert!(padding.origin.x <= content.origin.x);
        assert!(margin.origin.y <= border_box.origin.y);
        assert!(border_box.origin.y <= padding.origin.y);
        assert!(padding.origin.y <= content.origin.y);
        assert!(content.size.width <= padding.size.width);
        assert!(padding.size.width <= border_box.size.width);
        assert!(border_box.size.width <= margin.size.width);
        assert!(content.size.height <= padding.size.height);
        assert!(padding.size.height <= border_box.size.height);
        assert!(border_box.size.height <= margin.size.height);
    }
    #[test]
    fn content_box_size_floors_at_zero_but_the_origin_still_moves_in() {
        let bp = props(
            EdgeSizes::default(),
            edges(500.0, 500.0, 500.0, 500.0),
            edges(500.0, 500.0, 500.0, 500.0),
        );
        let got = bp.content_box(rect(0.0, 0.0, 10.0, 10.0));
        assert_eq!(got.size.width, 0.0, "size must clamp, not go negative");
        assert_eq!(got.size.height, 0.0);
        assert_eq!(got.origin.x, 1000.0, "origin is not clamped");
        assert_eq!(got.origin.y, 1000.0);
    }
    #[test]
    fn padding_box_size_floors_at_zero_for_an_oversized_border() {
        let bp = props(
            EdgeSizes::default(),
            EdgeSizes::default(),
            edges(99.0, 99.0, 99.0, 99.0),
        );
        let got = bp.padding_box(rect(0.0, 0.0, 10.0, 10.0));
        assert_eq!(got.size.width, 0.0);
        assert_eq!(got.size.height, 0.0);
    }
    #[test]
    fn margin_box_with_negative_margins_can_shrink_below_zero() {
        // Unlike content_box/padding_box, margin_box does NOT floor at 0 — negative
        // margins are legal CSS and the box genuinely inverts. Pinning the real
        // behaviour so a later "helpful" clamp cannot land unnoticed.
        let bp = props(
            edges(-10.0, -10.0, -10.0, -10.0),
            EdgeSizes::default(),
            EdgeSizes::default(),
        );
        let got = bp.margin_box(rect(0.0, 0.0, 10.0, 10.0));
        assert_eq!(got.size.width, -10.0);
        assert_eq!(got.size.height, -10.0);
        assert_eq!(
            got.origin.x, 10.0,
            "a negative left margin pushes the origin right"
        );
        assert_eq!(got.origin.y, 10.0);
    }
    #[test]
    fn box_rects_do_not_panic_on_nan_or_infinite_geometry() {
        let bp = props(
            edges(f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX),
            edges(f32::NAN, f32::MAX, 0.0, f32::MIN),
            edges(f32::INFINITY, 0.0, f32::NAN, 1.0),
        );
        let r = rect(f32::NAN, f32::INFINITY, f32::MAX, f32::MIN);
        let c = bp.content_box(r);
        let p = bp.padding_box(r);
        let m = bp.margin_box(r);
        // The clamped sizes are the only guaranteed invariant: never negative, never NaN.
        for s in [c.size, p.size] {
            assert!(!s.width.is_nan() && !s.height.is_nan());
            assert!(s.width >= 0.0 && s.height >= 0.0);
        }
        let _ = m;
    }
    // ================================================================
    // ResolvedBoxProps: mbp / bp getters
    // ================================================================
    #[test]
    fn mbp_and_bp_getters_sum_the_expected_layers() {
        let bp = props(
            edges(1.0, 2.0, 4.0, 8.0),         // margin: h=10, v=5
            edges(10.0, 20.0, 40.0, 80.0),     // padding: h=100, v=50
            edges(100.0, 200.0, 400.0, 800.0), // border: h=1000, v=500
        );
        assert_eq!(bp.horizontal_bp(), 1100.0);
        assert_eq!(bp.vertical_bp(), 550.0);
        assert_eq!(bp.horizontal_mbp(), 1110.0);
        assert_eq!(bp.vertical_mbp(), 555.0);
        // mbp is exactly bp plus the margins — the two must never drift apart.
        assert_eq!(
            bp.horizontal_mbp(),
            bp.horizontal_bp() + bp.margin.horizontal_sum()
        );
        assert_eq!(
            bp.vertical_mbp(),
            bp.vertical_bp() + bp.margin.vertical_sum()
        );
    }
    #[test]
    fn mbp_and_bp_getters_are_zero_on_a_default_box() {
        let bp = ResolvedBoxProps::default();
        assert_eq!(bp.horizontal_mbp(), 0.0);
        assert_eq!(bp.vertical_mbp(), 0.0);
        assert_eq!(bp.horizontal_bp(), 0.0);
        assert_eq!(bp.vertical_bp(), 0.0);
    }
    #[test]
    fn mbp_getters_do_not_panic_on_extreme_boxes() {
        let bp = props(
            edges(f32::MAX, f32::MAX, f32::MAX, f32::MAX),
            edges(f32::NAN, 0.0, 0.0, 0.0),
            edges(f32::NEG_INFINITY, 0.0, 0.0, 0.0),
        );
        let _ = bp.horizontal_mbp();
        let _ = bp.vertical_mbp();
        let _ = bp.horizontal_bp();
        let _ = bp.vertical_bp();
    }
    // ================================================================
    // PackedBoxProps: encoding
    // ================================================================
    #[test]
    fn pack_edge_encodes_tenths_of_a_pixel() {
        let e = edges(0.0, 1.0, 2.5, 3276.7);
        let p = PackedBoxProps::pack_edge(&e);
        assert_eq!(p[0], 0);
        assert_eq!(p[1], 10);
        assert_eq!(p[2], 25);
        assert_eq!(p[3], 32767, "the documented +3276.7px maximum");
    }
    #[test]
    fn pack_edge_rounds_to_the_nearest_tenth_rather_than_truncating() {
        let p = PackedBoxProps::pack_edge(&edges(1.04, 1.06, -1.04, -1.06));
        assert_eq!(p[0], 10, "1.04 rounds down");
        assert_eq!(p[1], 11, "1.06 rounds up — truncation would give 10");
        assert_eq!(p[2], -10);
        assert_eq!(p[3], -11);
    }
    #[test]
    fn pack_edge_saturates_out_of_range_values_instead_of_wrapping() {
        // Wrapping would turn a huge positive margin into a huge NEGATIVE one —
        // the single nastiest failure mode of this encoding.
        let p = PackedBoxProps::pack_edge(&edges(10_000.0, -10_000.0, 1e30, -1e30));
        assert_eq!(p[0], i16::MAX);
        assert_eq!(p[1], i16::MIN);
        assert_eq!(p[2], i16::MAX);
        assert_eq!(p[3], i16::MIN);
        assert!(p.iter().all(|v| *v == i16::MAX || *v == i16::MIN));
    }
    #[test]
    fn pack_edge_clamps_infinities_to_the_i16_bounds() {
        let p =
            PackedBoxProps::pack_edge(&edges(f32::INFINITY, f32::NEG_INFINITY, f32::MAX, f32::MIN));
        assert_eq!(p[0], i16::MAX);
        assert_eq!(p[1], i16::MIN);
        assert_eq!(p[2], i16::MAX);
        assert_eq!(p[3], i16::MIN);
    }
    #[test]
    fn pack_edge_maps_nan_to_zero_without_panicking() {
        // `f32::clamp` passes NaN through (it only panics on a NaN *bound*), and the
        // subsequent `as i16` saturates NaN to 0. So a NaN edge encodes as 0px.
        let p = PackedBoxProps::pack_edge(&edges(f32::NAN, f32::NAN, f32::NAN, f32::NAN));
        assert_eq!(p, [0, 0, 0, 0]);
    }
    #[test]
    fn pack_edge_maps_negative_zero_to_zero() {
        let p = PackedBoxProps::pack_edge(&edges(-0.0, -0.0, -0.0, -0.0));
        assert_eq!(p, [0, 0, 0, 0]);
    }
    #[test]
    fn unpack_edge_decodes_tenths_and_preserves_the_trbl_order() {
        let e = PackedBoxProps::unpack_edge(&[10, 25, -10, 32767]);
        assert!(close(e.top, 1.0, 1e-4), "top was {}", e.top);
        assert!(close(e.right, 2.5, 1e-4), "right was {}", e.right);
        assert!(close(e.bottom, -1.0, 1e-4), "bottom was {}", e.bottom);
        assert!(close(e.left, 3276.7, 1e-2), "left was {}", e.left);
    }
    #[test]
    fn unpack_edge_at_the_i16_extremes_stays_finite() {
        let e = PackedBoxProps::unpack_edge(&[i16::MAX, i16::MIN, 0, 1]);
        assert!(e.top.is_finite() && e.right.is_finite());
        assert!(close(e.top, 3276.7, 1e-2));
        assert!(close(e.right, -3276.8, 1e-2));
        assert_eq!(e.bottom, 0.0);
        assert!(close(e.left, 0.1, 1e-6));
    }
    // ================================================================
    // PackedBoxProps: round-trip
    // ================================================================
    #[test]
    fn every_i16_encoding_survives_unpack_then_pack_unchanged() {
        // Exhaustive decode->encode identity over the WHOLE i16 domain: if the
        // f32 round-off in `unpack_edge` ever drifted by more than half a tenth,
        // `pack_edge` would land on a neighbouring code and this would catch it.
        for n in i16::MIN..=i16::MAX {
            let encoded = [n; 4];
            let round_tripped = PackedBoxProps::pack_edge(&PackedBoxProps::unpack_edge(&encoded));
            assert_eq!(round_tripped, encoded, "i16 code {n} did not round-trip");
        }
    }
    #[test]
    fn pack_then_unpack_preserves_values_to_a_tenth_of_a_pixel() {
        let bp = props(
            edges(1.0, 2.5, 0.1, 12.3),
            edges(0.0, 100.25, 3276.7, -3276.8),
            edges(0.5, 0.05, 7.0, 0.0),
        );
        let out = PackedBoxProps::pack(&bp).unpack();
        for (got, want) in [
            (out.margin.top, bp.margin.top),
            (out.margin.right, bp.margin.right),
            (out.margin.bottom, bp.margin.bottom),
            (out.margin.left, bp.margin.left),
            (out.padding.top, bp.padding.top),
            (out.padding.right, bp.padding.right),
            (out.padding.bottom, bp.padding.bottom),
            (out.padding.left, bp.padding.left),
            (out.border.top, bp.border.top),
            (out.border.right, bp.border.right),
            (out.border.bottom, bp.border.bottom),
            (out.border.left, bp.border.left),
        ] {
            // Half a quantum (0.05) plus a little float slack at the 3276.x extreme.
            assert!(close(got, want, 0.051), "{want} round-tripped to {got}");
        }
    }
    #[test]
    fn pack_carries_the_margin_auto_flags_through_verbatim() {
        // margin_auto is NOT part of the lossy i16 encoding, so it must come back bit-exact.
        let bp = ResolvedBoxProps {
            margin_auto: MarginAuto {
                left: true,
                right: false,
                top: true,
                bottom: false,
            },
            ..ResolvedBoxProps::default()
        };
        let out = PackedBoxProps::pack(&bp).unpack();
        assert!(out.margin_auto.left);
        assert!(!out.margin_auto.right);
        assert!(out.margin_auto.top);
        assert!(!out.margin_auto.bottom);
    }
    #[test]
    fn pack_keeps_the_three_edge_groups_apart() {
        // A copy-paste slip in `pack` would splice margin into padding or border.
        let bp = props(
            edges(1.0, 1.0, 1.0, 1.0),
            edges(2.0, 2.0, 2.0, 2.0),
            edges(3.0, 3.0, 3.0, 3.0),
        );
        let p = PackedBoxProps::pack(&bp);
        assert_eq!(p.margin, [10; 4]);
        assert_eq!(p.padding, [20; 4]);
        assert_eq!(p.border, [30; 4]);
    }
    #[test]
    fn pack_of_an_out_of_range_box_clamps_rather_than_flipping_sign() {
        let bp = props(
            edges(5000.0, 5000.0, 5000.0, 5000.0), // beyond +3276.7
            EdgeSizes::default(),
            EdgeSizes::default(),
        );
        let out = PackedBoxProps::pack(&bp).unpack();
        assert!(
            out.margin.top > 0.0,
            "a huge margin must not decode as negative"
        );
        assert!(close(out.margin.top, 3276.7, 1e-2));
    }
    #[test]
    fn packed_default_is_an_all_zero_box() {
        let p = PackedBoxProps::default();
        assert_eq!(p.margin, [0; 4]);
        assert_eq!(p.horizontal_mbp(), 0.0);
        assert_eq!(p.vertical_mbp(), 0.0);
        assert_eq!(p.horizontal_bp(), 0.0);
        assert_eq!(p.vertical_bp(), 0.0);
        let s = p.inner_size(
            LogicalSize::new(10.0, 10.0),
            LayoutWritingMode::HorizontalTb,
        );
        assert_eq!(s.width, 10.0);
        assert_eq!(s.height, 10.0);
    }
    // ================================================================
    // PackedBoxProps: convenience methods must agree with unpack()
    // ================================================================
    #[test]
    fn packed_convenience_methods_match_the_unpacked_equivalents() {
        let bp = props(
            edges(1.0, 2.5, 4.0, 8.5),
            edges(0.5, 1.5, 2.5, 3.5),
            edges(2.0, 4.0, 6.0, 8.0),
        );
        let packed = PackedBoxProps::pack(&bp);
        let unpacked = packed.unpack();
        let r = rect(10.0, 20.0, 300.0, 200.0);
        assert_eq!(packed.content_box(r), unpacked.content_box(r));
        assert_eq!(packed.padding_box(r), unpacked.padding_box(r));
        assert_eq!(packed.margin_box(r), unpacked.margin_box(r));
        assert_eq!(packed.horizontal_mbp(), unpacked.horizontal_mbp());
        assert_eq!(packed.vertical_mbp(), unpacked.vertical_mbp());
        assert_eq!(packed.horizontal_bp(), unpacked.horizontal_bp());
        assert_eq!(packed.vertical_bp(), unpacked.vertical_bp());
        for wm in ALL_WM {
            let a = packed.inner_size(r.size, wm);
            let b = unpacked.inner_size(r.size, wm);
            assert_eq!(a.width, b.width, "{wm:?}");
            assert_eq!(a.height, b.height, "{wm:?}");
        }
    }
    #[test]
    fn packed_inner_size_floors_at_zero_for_a_tiny_box() {
        let bp = props(
            EdgeSizes::default(),
            edges(50.0, 50.0, 50.0, 50.0),
            edges(50.0, 50.0, 50.0, 50.0),
        );
        let packed = PackedBoxProps::pack(&bp);
        for wm in ALL_WM {
            let s = packed.inner_size(LogicalSize::new(1.0, 1.0), wm);
            assert_eq!(s.width, 0.0, "{wm:?}");
            assert_eq!(s.height, 0.0, "{wm:?}");
        }
    }
    #[test]
    fn packed_box_rects_do_not_panic_on_extreme_input_rects() {
        let packed = PackedBoxProps::pack(&props(
            edges(3276.7, 3276.7, 3276.7, 3276.7),
            edges(3276.7, 3276.7, 3276.7, 3276.7),
            edges(3276.7, 3276.7, 3276.7, 3276.7),
        ));
        for r in [
            rect(0.0, 0.0, 0.0, 0.0),
            rect(f32::MAX, f32::MIN, f32::MAX, f32::MAX),
            rect(f32::NAN, f32::NAN, f32::NAN, f32::NAN),
            rect(-1e30, -1e30, -1e30, -1e30),
        ] {
            let c = packed.content_box(r);
            let p = packed.padding_box(r);
            let _ = packed.margin_box(r);
            assert!(c.size.width >= 0.0 && !c.size.width.is_nan());
            assert!(p.size.height >= 0.0 && !p.size.height.is_nan());
        }
    }
    // ================================================================
    // WritingModeContext
    // ================================================================
    #[test]
    fn writing_mode_context_new_stores_what_it_was_given() {
        let c = WritingModeContext::new(
            LayoutWritingMode::VerticalRl,
            StyleDirection::Rtl,
            StyleTextOrientation::Mixed,
        );
        assert_eq!(c.writing_mode, LayoutWritingMode::VerticalRl);
        assert_eq!(c.direction, StyleDirection::Rtl);
        assert_eq!(c.text_orientation, StyleTextOrientation::Mixed);
    }
    #[test]
    fn text_orientation_upright_forces_the_used_direction_to_ltr() {
        // CSS Writing Modes 4 §5.1: `text-orientation: upright` makes the USED value
        // of `direction` ltr, even when the author wrote `direction: rtl`.
        let c = WritingModeContext::new(
            LayoutWritingMode::VerticalRl,
            StyleDirection::Rtl,
            StyleTextOrientation::Upright,
        );
        assert_eq!(c.used_direction(), StyleDirection::Ltr);
        assert!(
            !c.is_inline_reversed(),
            "upright must cancel the RTL reversal"
        );
    }
    #[test]
    fn only_upright_overrides_the_direction() {
        for orientation in [StyleTextOrientation::Mixed, StyleTextOrientation::Sideways] {
            let c = WritingModeContext::new(
                LayoutWritingMode::VerticalRl,
                StyleDirection::Rtl,
                orientation,
            );
            assert_eq!(
                c.used_direction(),
                StyleDirection::Rtl,
                "{orientation:?} must not touch the direction"
            );
            assert!(c.is_inline_reversed());
        }
    }
    #[test]
    fn writing_mode_context_new_is_idempotent() {
        // Re-feeding a context's own fields back into `new()` must be a fixed point,
        // otherwise the upright override would compound across re-resolutions.
        for wm in ALL_WM {
            for dir in [StyleDirection::Ltr, StyleDirection::Rtl] {
                for or in [
                    StyleTextOrientation::Mixed,
                    StyleTextOrientation::Upright,
                    StyleTextOrientation::Sideways,
                ] {
                    let once = WritingModeContext::new(wm, dir, or);
                    let twice = WritingModeContext::new(
                        once.writing_mode,
                        once.direction,
                        once.text_orientation,
                    );
                    assert_eq!(once, twice, "{wm:?}/{dir:?}/{or:?} is not a fixed point");
                }
            }
        }
    }
    #[test]
    fn is_horizontal_is_true_only_for_horizontal_tb() {
        let mk = |wm| WritingModeContext::new(wm, StyleDirection::Ltr, StyleTextOrientation::Mixed);
        assert!(mk(LayoutWritingMode::HorizontalTb).is_horizontal());
        assert!(!mk(LayoutWritingMode::VerticalRl).is_horizontal());
        assert!(!mk(LayoutWritingMode::VerticalLr).is_horizontal());
    }
    #[test]
    fn inline_and_block_axis_predicates_track_is_horizontal() {
        // In horizontal-tb, inline size is the width and block size is the height;
        // both flip together in vertical modes. They may never disagree.
        for wm in ALL_WM {
            for dir in [StyleDirection::Ltr, StyleDirection::Rtl] {
                let c = WritingModeContext::new(wm, dir, StyleTextOrientation::Mixed);
                assert_eq!(c.inline_size_is_width(), c.is_horizontal(), "{wm:?}");
                assert_eq!(c.block_size_is_height(), c.is_horizontal(), "{wm:?}");
                assert_eq!(
                    c.inline_size_is_width(),
                    c.block_size_is_height(),
                    "{wm:?}: the two axes must flip together"
                );
            }
        }
    }
    #[test]
    fn is_inline_reversed_follows_the_used_direction_not_the_writing_mode() {
        for wm in ALL_WM {
            let ltr = WritingModeContext::new(wm, StyleDirection::Ltr, StyleTextOrientation::Mixed);
            let rtl = WritingModeContext::new(wm, StyleDirection::Rtl, StyleTextOrientation::Mixed);
            assert!(!ltr.is_inline_reversed(), "{wm:?} ltr");
            assert!(rtl.is_inline_reversed(), "{wm:?} rtl");
        }
    }
    #[test]
    fn default_writing_mode_context_is_horizontal_ltr_mixed() {
        let c = WritingModeContext::default();
        assert_eq!(c.writing_mode, LayoutWritingMode::HorizontalTb);
        assert_eq!(c.used_direction(), StyleDirection::Ltr);
        assert_eq!(c.text_orientation, StyleTextOrientation::Mixed);
        assert!(c.is_horizontal());
        assert!(c.inline_size_is_width());
        assert!(c.block_size_is_height());
        assert!(!c.is_inline_reversed());
    }
    #[test]
    fn default_context_matches_new_with_the_same_arguments() {
        let built = WritingModeContext::new(
            LayoutWritingMode::HorizontalTb,
            StyleDirection::Ltr,
            StyleTextOrientation::Mixed,
        );
        assert_eq!(WritingModeContext::default(), built);
    }
    #[test]
    fn fit_content_clamps_stretch_fit_between_min_and_max_content() {
        let is = IntrinsicSizes {
            min_content_width: 30.0,
            max_content_width: 100.0,
            min_content_height: 10.0,
            max_content_height: 40.0,
            ..Default::default()
        };
        // stretch-fit within [min, max] → returned as-is.
        assert!((is.fit_content_width(60.0) - 60.0).abs() < f32::EPSILON);
        assert!((is.fit_content_height(25.0) - 25.0).abs() < f32::EPSILON);
        // stretch-fit above max-content → clamped to max-content.
        assert!((is.fit_content_width(500.0) - 100.0).abs() < f32::EPSILON);
        assert!((is.fit_content_height(500.0) - 40.0).abs() < f32::EPSILON);
        // stretch-fit below min-content → clamped up to min-content (min wins over max).
        assert!((is.fit_content_width(0.0) - 30.0).abs() < f32::EPSILON);
        assert!((is.fit_content_height(0.0) - 10.0).abs() < f32::EPSILON);
    }
    #[test]
    fn intrinsic_sizes_default_has_no_preferred_aspect_ratio() {
        assert_eq!(IntrinsicSizes::default().preferred_aspect_ratio, None);
    }
}