ironpress 1.4.3

Pure Rust HTML/CSS/Markdown to PDF converter with layout engine, LaTeX math, tables, images, custom fonts, and streaming output. No browser, no system dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
use crate::parser::css::{AncestorInfo, SelectorContext};
use crate::parser::dom::{DomNode, ElementNode};
use crate::style::computed::{
    AlignItems, BackgroundOrigin, BackgroundPosition, BackgroundRepeat, BackgroundSize, BoxSizing,
    Clear, ComputedStyle, Display, FlexDirection, FlexWrap, Float, JustifyContent, Overflow,
    Position, TextAlign, VerticalAlign, Visibility, compute_style_with_context,
};

use super::context::{ContainingBlock, LayoutContext, LayoutEnv};
use super::engine::{
    BackgroundFields, FlexCell, LayoutBorder, LayoutElement, TextLine, aspect_ratio_height,
    background_svg_for_style, collects_as_inline_text, flatten_element, has_background_paint,
    measure_runs_width, pseudo_is_block_like, push_block_pseudo, resolve_padding_box_height,
};
use super::paginate::estimate_element_height;
use super::text::{
    FlexTextRunCollector, TextWrapOptions, resolved_line_height_factor, wrap_text_runs,
};

/// Each child is laid out as a TextBlock at a computed position. The container
/// emits one TextBlock per flex item with an `offset_left` / `offset_top` that
/// encodes its position inside the flex row/column. The container itself emits
/// a wrapper TextBlock for its background/border first, then the items.
#[allow(clippy::too_many_arguments)]
pub(crate) fn layout_flex_container(
    el: &ElementNode,
    style: &ComputedStyle,
    ctx: &LayoutContext,
    output: &mut Vec<LayoutElement>,
    ancestors: &[AncestorInfo],
    before_style: Option<&ComputedStyle>,
    after_style: Option<&ComputedStyle>,
    positioned_depth: usize,
    env: &mut LayoutEnv,
) {
    let available_width = ctx.available_width();
    let mut block_w = available_width;
    if let Some(w) = style.width {
        block_w = w.min(available_width);
    }
    if let Some(mw) = style.max_width {
        block_w = block_w.min(mw);
    }

    let inner_width = block_w - style.padding.left - style.padding.right;

    // Resolve percentage border-radius for flex containers
    let resolved_border_radius = if let Some(pct) = style.border_radius_pct {
        let dim = style.height.map_or(block_w, |h| block_w.min(h));
        dim * pct / 100.0
    } else {
        style.border_radius
    };

    // Collect child elements and lay each one out into a temporary buffer
    let child_elements: Vec<&ElementNode> = el
        .children
        .iter()
        .filter_map(|c| {
            if let DomNode::Element(e) = c {
                Some(e)
            } else {
                None
            }
        })
        .collect();

    let child_count = child_elements.len();
    if child_count == 0 {
        let before_abs = before_style.is_some_and(|pseudo| {
            pseudo_is_block_like(pseudo) && pseudo.position == Position::Absolute
        });
        let after_abs = after_style.is_some_and(|pseudo| {
            pseudo_is_block_like(pseudo) && pseudo.position == Position::Absolute
        });
        if has_background_paint(style)
            || style.border.has_any()
            || resolved_border_radius > 0.0
            || style.box_shadow.is_some()
            || style.aspect_ratio.is_some()
            || style.height.is_some()
            || before_abs
            || after_abs
        {
            let container_h = style
                .height
                .or_else(|| aspect_ratio_height(block_w, style))
                .unwrap_or(0.0);
            let containing_block = (style.position == Position::Relative
                || style.position == Position::Absolute)
                .then(|| ContainingBlock {
                    x: style.left.unwrap_or(0.0) + style.border.left.width + style.padding.left,
                    width: if style.box_sizing == BoxSizing::BorderBox {
                        block_w - style.border.horizontal_width()
                    } else {
                        block_w + style.padding.left + style.padding.right
                    },
                    height: container_h,
                    depth: positioned_depth,
                });
            let bg = style
                .background_color
                .map(|color: crate::types::Color| color.to_f32_rgba());
            let BackgroundFields {
                gradient: background_gradient,
                radial_gradient: background_radial_gradient,
                svg: background_svg,
                blur_radius: background_blur_radius,
                size: background_size,
                position: background_position,
                repeat: background_repeat,
                origin: background_origin,
            } = BackgroundFields::from_style(style);
            output.push(LayoutElement::TextBlock {
                lines: Vec::new(),
                margin_top: style.margin.top,
                margin_bottom: style.margin.bottom,
                text_align: style.text_align,
                background_color: bg,
                padding_top: style.padding.top,
                padding_bottom: style.padding.bottom,
                padding_left: style.padding.left,
                padding_right: style.padding.right,
                border: LayoutBorder::from_computed(&style.border),
                block_width: Some(block_w),
                block_height: Some(container_h),
                opacity: style.opacity,
                float: style.float,
                clear: style.clear,
                position: style.position,
                offset_top: style.top.unwrap_or(0.0),
                offset_left: style.left.unwrap_or(0.0),
                offset_bottom: 0.0,
                offset_right: 0.0,
                containing_block: None,
                box_shadow: style.box_shadow,
                visible: style.visibility == Visibility::Visible,
                clip_rect: if style.overflow == Overflow::Hidden {
                    Some((0.0, 0.0, block_w, container_h))
                } else {
                    None
                },
                transform: style.transform,
                border_radius: resolved_border_radius,
                outline_width: style.outline_width,
                outline_color: style.outline_color.map(|c| c.to_f32_rgb()),
                text_indent: 0.0,
                letter_spacing: style.letter_spacing,
                word_spacing: style.word_spacing,
                vertical_align: style.vertical_align,
                background_gradient,
                background_radial_gradient,
                background_svg,
                background_blur_radius,
                background_size,
                background_position,
                background_repeat,
                background_origin,
                z_index: style.z_index,
                repeat_on_each_page: false,
                positioned_depth,
                heading_level: None,
                clip_children_count: 0,
            });

            if before_abs {
                push_block_pseudo(
                    output,
                    before_style,
                    el,
                    inner_width.max(0.0),
                    env.fonts,
                    containing_block,
                    positioned_depth,
                    env.counter_state,
                );
            }
            if after_abs {
                push_block_pseudo(
                    output,
                    after_style,
                    el,
                    inner_width.max(0.0),
                    env.fonts,
                    containing_block,
                    positioned_depth,
                    env.counter_state,
                );
            }
        }
        return;
    }

    // Lay out each child into its own set of elements to measure sizes
    #[allow(dead_code)]
    struct FlexItem {
        elements: Vec<LayoutElement>,
        width: f32,
        base_width: f32,
        flex_grow: f32,
        flex_shrink: f32,
        height: f32,
        natural_height: f32,
    }

    let mut items: Vec<FlexItem> = Vec::new();

    // For percentage width resolution, children need the actual container width
    // as the parent reference (not the CSS width which may be None).
    // Subtract total gap space so that percentage widths + gaps fit within the container.
    let total_gaps = style.gap * (child_count.saturating_sub(1)) as f32;
    let width_for_percentages = (inner_width - total_gaps).max(0.0);
    let mut parent_for_children = style.clone();
    if parent_for_children.width.is_none() {
        parent_for_children.width = Some(width_for_percentages);
    }

    for (idx, child_el) in child_elements.iter().enumerate() {
        let classes = child_el.class_list();
        let selector_ctx = SelectorContext {
            ancestors: ancestors.to_vec(),
            child_index: idx,
            sibling_count: child_count,
            preceding_siblings: Vec::new(),
        };
        let child_style = compute_style_with_context(
            child_el.tag,
            child_el.style_attr(),
            &parent_for_children,
            env.rules,
            child_el.tag_name(),
            &classes,
            child_el.id(),
            &child_el.attributes,
            &selector_ctx,
        );

        if child_style.display == Display::None {
            continue;
        }

        // Determine child width: flex-basis takes priority, then explicit width.
        // Flex base size for grow/shrink distribution:
        // - With flex-basis or width: use that value
        // - flex-grow > 0 without basis/width: use 0 so all space is distributed
        //   proportionally by grow factors
        // - flex-grow == 0 without basis/width: use equal share, then shrink to
        //   natural content width (for justify-content)
        //
        // For `box-sizing: content-box` (the CSS default), the specified width
        // is the *content* width, so the outer box used for flex main-axis
        // layout is `width + padding + border`. For `border-box`, the
        // specified width is already the outer box.
        let has_explicit_width = child_style.flex_basis.is_some() || child_style.width.is_some();
        let inflate_outer = |w: f32| -> f32 {
            if child_style.box_sizing == BoxSizing::ContentBox {
                w + child_style.padding.left
                    + child_style.padding.right
                    + child_style.border.horizontal_width()
            } else {
                w
            }
        };
        let child_w_initial = match child_style.flex_basis.or(child_style.width) {
            Some(w) => inflate_outer(w),
            None => {
                if child_style.flex_grow > 0.0 {
                    0.0
                } else {
                    width_for_percentages / child_count as f32
                }
            }
        };
        // For text wrapping, use equal share as measurement width even when
        // flex base is 0 — text needs a nonzero width to wrap into lines.
        // The actual item width will be set after grow distribution.
        let wrap_width = if child_w_initial < 1.0 && child_style.flex_grow > 0.0 {
            width_for_percentages / child_count as f32
        } else {
            child_w_initial
        };

        // Include the child element itself in the ancestor chain so that
        // descendant selectors like `.card h3` can match.
        let mut child_ancestors = ancestors.to_vec();
        child_ancestors.push(AncestorInfo {
            element: child_el,
            child_index: idx,
            sibling_count: child_count,
            preceding_siblings: Vec::new(),
        });

        // Two widths: child_w_for_flex is the outer main-axis size used for
        // wrapping decisions (content-box + padding + border for content-box),
        // child_w_for_layout is the content width used to lay out children so
        // percentage resolution against the parent content area is correct.
        let child_w_for_flex = match child_style.flex_basis.or(child_style.width) {
            Some(w) => inflate_outer(w),
            None => width_for_percentages / child_count as f32,
        };
        let child_w_for_layout = if child_style.flex_grow > 0.0
            && child_style.flex_basis == Some(0.0)
            && child_style.width.is_none()
        {
            // Use full available width for child percentage resolution,
            // but flex wrapping uses the actual basis (child_w_for_flex).
            width_for_percentages
        } else {
            // Content area for child layout = outer minus padding + border.
            (child_w_for_flex
                - child_style.padding.left
                - child_style.padding.right
                - child_style.border.horizontal_width())
            .max(0.0)
        };

        // Check if this flex item has block-level children that need full layout
        let item_has_block_children = child_el.children.iter().any(|c| {
            matches!(c, DomNode::Element(e) if e.tag.is_block() && !collects_as_inline_text(e.tag))
        });

        // For complex flex items (with block children like <h2>, <p>, <div>),
        // use flatten_element to get a proper list of layout elements with
        // margins and structure preserved.
        if item_has_block_children {
            let mut child_elements_buf = Vec::new();
            let layout_height = 10000.0; // large enough to not constrain
            let child_ctx = ctx
                .with_parent(child_w_for_layout, Some(layout_height), style.font_size)
                .with_containing_block(None);
            flatten_element(
                child_el,
                style,
                &child_ctx,
                &mut child_elements_buf,
                None,
                &child_ancestors,
                positioned_depth,
                idx,
                child_count,
                &[],
                env,
            );
            let child_h = child_elements_buf
                .iter()
                .map(|el| match el {
                    LayoutElement::TextBlock {
                        lines,
                        padding_top,
                        padding_bottom,
                        border,
                        block_height,
                        ..
                    } => {
                        let text_h: f32 = lines.iter().map(|l| l.height).sum();
                        let content =
                            padding_top + text_h + padding_bottom + border.vertical_width();
                        // Don't include margins here — they are added as spacer
                        // lines in the merged FlexCell, so counting them would
                        // double the vertical space.
                        block_height.map_or(content, |h| content.max(h))
                    }
                    LayoutElement::FlexRow {
                        cells,
                        margin_top,
                        margin_bottom,
                        ..
                    } => {
                        let row_h = cells
                            .iter()
                            .map(|c| {
                                let text_h: f32 = c.lines.iter().map(|l| l.height).sum();
                                c.padding_top + text_h + c.padding_bottom
                            })
                            .fold(0.0f32, f32::max);
                        margin_top + row_h + margin_bottom
                    }
                    other => estimate_element_height(other),
                })
                .sum::<f32>();

            items.push(FlexItem {
                elements: child_elements_buf,
                width: child_w_for_flex,
                base_width: child_w_for_flex,
                flex_grow: child_style.flex_grow,
                flex_shrink: child_style.flex_shrink,
                height: child_h,
                natural_height: child_h, // Natural height for align-items flex-start
            });
            continue;
        }

        // Simple flex items: collect text runs and wrap
        let mut runs = Vec::new();
        FlexTextRunCollector {
            runs: &mut runs,
            rules: env.rules,
            fonts: env.fonts,
        }
        .collect(
            &child_el.children,
            &child_style,
            None,
            (0.0, 0.0),
            &child_ancestors,
        );

        // When no explicit width/flex-basis and flex-grow is 0, measure the
        // natural (intrinsic) content width so the item shrinks to fit.
        let child_w = if !has_explicit_width && child_style.flex_grow == 0.0 && !runs.is_empty() {
            let natural_text_w = measure_runs_width(&runs, env.fonts);
            let pad_h = child_style.padding.left + child_style.padding.right;
            let border_h = child_style.border.horizontal_width();
            // Outer width = text + padding + border (capped at container)
            (natural_text_w + pad_h + border_h).min(width_for_percentages)
        } else {
            child_w_initial
        };

        // Use wrap_width for text measurement (nonzero even when flex base is 0)
        let wrap_w = if child_style.flex_grow > 0.0 && !has_explicit_width {
            wrap_width
        } else {
            child_w
        };
        // wrap_w is always the outer box width (after content-box inflation),
        // so the inner content area is outer - padding - border.
        let child_inner_w = (wrap_w
            - child_style.padding.left
            - child_style.padding.right
            - child_style.border.horizontal_width())
        .max(0.0);

        let lines = if !runs.is_empty() {
            wrap_text_runs(
                runs,
                TextWrapOptions::new(
                    child_inner_w.max(1.0),
                    child_style.font_size,
                    resolved_line_height_factor(&child_style, env.fonts),
                    child_style.overflow_wrap,
                ),
                env.fonts,
            )
        } else {
            Vec::new()
        };

        let text_height: f32 = lines.iter().map(|l| l.height).sum();
        let aspect_h = child_style
            .height
            .is_none()
            .then(|| aspect_ratio_height(child_w, &child_style))
            .flatten();
        let mut child_h = resolve_padding_box_height(
            text_height,
            child_style.height,
            child_style.padding.top,
            child_style.padding.bottom,
            child_style.border.vertical_width(),
            child_style.box_sizing,
        );
        if let Some(aspect_h) = aspect_h {
            child_h = child_h.max(aspect_h);
        }

        let bg = child_style
            .background_color
            .map(|c: crate::types::Color| c.to_f32_rgba());
        let BackgroundFields {
            gradient: background_gradient,
            radial_gradient: background_radial_gradient,
            svg: background_svg,
            blur_radius: background_blur_radius,
            size: background_size,
            position: background_position,
            repeat: background_repeat,
            origin: background_origin,
        } = BackgroundFields::from_style(&child_style);
        let elem = LayoutElement::TextBlock {
            lines,
            margin_top: child_style.margin.top,
            margin_bottom: child_style.margin.bottom,
            text_align: child_style.text_align,
            background_color: bg,
            padding_top: child_style.padding.top,
            padding_bottom: child_style.padding.bottom,
            padding_left: child_style.padding.left,
            padding_right: child_style.padding.right,
            border: LayoutBorder::from_computed(&child_style.border),
            block_width: Some(child_w),
            block_height: child_style
                .height
                .map(|_| child_h)
                .or(aspect_h.map(|_| child_h)),
            opacity: child_style.opacity,
            float: Float::None,
            clear: Clear::None,
            position: child_style.position,
            offset_top: 0.0,
            offset_left: 0.0,
            offset_bottom: 0.0,
            offset_right: 0.0,
            containing_block: None,
            box_shadow: child_style.box_shadow,
            visible: child_style.visibility == Visibility::Visible,
            clip_rect: if child_style.overflow == Overflow::Hidden {
                Some((0.0, 0.0, child_w, child_h))
            } else {
                None
            },
            transform: child_style.transform,
            border_radius: child_style.border_radius,
            outline_width: child_style.outline_width,
            outline_color: child_style.outline_color.map(|c| c.to_f32_rgb()),
            text_indent: child_style.text_indent,
            letter_spacing: child_style.letter_spacing,
            word_spacing: child_style.word_spacing,
            vertical_align: child_style.vertical_align,
            background_gradient,
            background_radial_gradient,
            background_svg,
            background_blur_radius,
            background_size,
            background_position,
            background_repeat,
            background_origin,
            z_index: child_style.z_index,
            repeat_on_each_page: false,
            positioned_depth: 0,
            heading_level: None,
            clip_children_count: 0,
        };

        items.push(FlexItem {
            elements: vec![elem],
            width: child_w,
            base_width: child_w,
            flex_grow: child_style.flex_grow,
            flex_shrink: child_style.flex_shrink,
            height: child_h + child_style.margin.top + child_style.margin.bottom,
            natural_height: child_h + child_style.margin.top + child_style.margin.bottom,
        });
    }

    if items.is_empty() {
        return;
    }

    let direction = style.flex_direction;
    let justify = style.justify_content;
    let align = style.align_items;
    let wrap = style.flex_wrap;
    let gap = style.gap;

    // Group items into lines (for flex-wrap)
    struct FlexLine {
        item_indices: Vec<usize>,
        main_size: f32,
        cross_size: f32,
    }

    let mut lines: Vec<FlexLine> = Vec::new();

    match direction {
        FlexDirection::Row => {
            let max_main = inner_width;
            let mut current_line = FlexLine {
                item_indices: Vec::new(),
                main_size: 0.0,
                cross_size: 0.0,
            };

            for (i, item) in items.iter().enumerate() {
                let item_main = item.width;
                let gap_extra = if current_line.item_indices.is_empty() {
                    0.0
                } else {
                    gap
                };

                if wrap == FlexWrap::Wrap
                    && !current_line.item_indices.is_empty()
                    && current_line.main_size + gap_extra + item_main > max_main
                {
                    lines.push(current_line);
                    current_line = FlexLine {
                        item_indices: Vec::new(),
                        main_size: 0.0,
                        cross_size: 0.0,
                    };
                }

                if !current_line.item_indices.is_empty() {
                    current_line.main_size += gap;
                }
                current_line.main_size += item_main;
                current_line.cross_size = current_line.cross_size.max(item.height);
                current_line.item_indices.push(i);
            }
            if !current_line.item_indices.is_empty() {
                lines.push(current_line);
            }
        }
        FlexDirection::Column => {
            // In column direction, each item is on its own "line" conceptually,
            // but we group them all into one line for simplicity (no column wrap needed yet)
            let mut line = FlexLine {
                item_indices: Vec::new(),
                main_size: 0.0,
                cross_size: 0.0,
            };
            for (i, item) in items.iter().enumerate() {
                if !line.item_indices.is_empty() {
                    line.main_size += gap;
                }
                line.main_size += item.height;
                line.cross_size = line.cross_size.max(item.width);
                line.item_indices.push(i);
            }
            if !line.item_indices.is_empty() {
                lines.push(line);
            }
        }
    }

    // Compute container dimensions
    let total_cross: f32 = match direction {
        FlexDirection::Row => {
            lines.iter().map(|l| l.cross_size).sum::<f32>()
                + if lines.len() > 1 {
                    (lines.len() - 1) as f32 * gap
                } else {
                    0.0
                }
        }
        FlexDirection::Column => lines.iter().map(|l| l.cross_size).fold(0.0f32, f32::max),
    };

    let total_main: f32 = match direction {
        FlexDirection::Row => inner_width,
        FlexDirection::Column => lines.iter().map(|l| l.main_size).sum::<f32>(),
    };

    let container_height = match direction {
        FlexDirection::Row => total_cross,
        FlexDirection::Column => total_main,
    };

    // `container_h` is the padding-box height (content + vertical padding).
    // `height` / `min-height` are defined against the content box in
    // `box-sizing: content-box` and against the border box in
    // `box-sizing: border-box`. Translate both to a padding-box comparand so
    // the max() here honors Chrome's semantics.
    let pad_v = style.padding.top + style.padding.bottom;
    let border_v = style.border.vertical_width();
    let container_h = style.padding.top + container_height + style.padding.bottom;
    let container_h = match style.height {
        Some(h) => {
            let target = match style.box_sizing {
                BoxSizing::ContentBox => h + pad_v,
                BoxSizing::BorderBox => (h - border_v).max(0.0),
            };
            container_h.max(target)
        }
        None => container_h,
    };
    let container_h = match style.min_height {
        Some(min_h) => {
            let target = match style.box_sizing {
                BoxSizing::ContentBox => min_h + pad_v,
                BoxSizing::BorderBox => (min_h - border_v).max(0.0),
            };
            container_h.max(target)
        }
        None => container_h,
    };
    // Cross-axis inner size once height/min-height have been honored. For
    // row direction with a single line this is what each item should
    // stretch to (align-items: stretch) and what flex-end/center measure
    // against — otherwise a tall `min-height` container collapses visually
    // to the natural item height.
    let inner_cross_size = (container_h - style.padding.top - style.padding.bottom).max(0.0);
    if direction == FlexDirection::Row && lines.len() == 1 {
        if let Some(line) = lines.first_mut() {
            line.cross_size = line.cross_size.max(inner_cross_size);
        }
    }
    // Recompute total_cross after possibly growing a single line.
    let total_cross: f32 = match direction {
        FlexDirection::Row => {
            lines.iter().map(|l| l.cross_size).sum::<f32>()
                + if lines.len() > 1 {
                    (lines.len() - 1) as f32 * gap
                } else {
                    0.0
                }
        }
        FlexDirection::Column => lines.iter().map(|l| l.cross_size).fold(0.0f32, f32::max),
    };
    let bg = style
        .background_color
        .map(|color: crate::types::Color| color.to_f32_rgba());

    // For column direction, emit container background separately
    let emitted_column_bg = direction == FlexDirection::Column
        && (has_background_paint(style) || style.border.has_any() || style.box_shadow.is_some());
    if emitted_column_bg {
        // Emit the container background/border as a visual element.
        // It advances y by its full height in paginate.  We then emit a
        // negative-margin spacer to pull y back so children flow *inside*
        // the background rather than after it.
        let bg_flow_height = container_h + style.border.vertical_width();
        let BackgroundFields {
            gradient: background_gradient,
            radial_gradient: background_radial_gradient,
            svg: background_svg,
            blur_radius: background_blur_radius,
            size: background_size,
            position: background_position,
            repeat: background_repeat,
            origin: background_origin,
        } = BackgroundFields::from_style(style);
        output.push(LayoutElement::TextBlock {
            lines: Vec::new(),
            margin_top: style.margin.top,
            margin_bottom: 0.0,
            text_align: style.text_align,
            background_color: bg,
            padding_top: style.padding.top,
            padding_bottom: style.padding.bottom,
            padding_left: style.padding.left,
            padding_right: style.padding.right,
            border: LayoutBorder::from_computed(&style.border),
            block_width: Some(block_w),
            block_height: Some(container_h),
            opacity: style.opacity,
            float: style.float,
            clear: style.clear,
            position: style.position,
            offset_top: style.top.unwrap_or(0.0),
            offset_left: style.left.unwrap_or(0.0),
            offset_bottom: 0.0,
            offset_right: 0.0,
            containing_block: None,
            box_shadow: style.box_shadow,
            visible: style.visibility == Visibility::Visible,
            clip_rect: if style.overflow == Overflow::Hidden {
                Some((0.0, 0.0, block_w, container_h))
            } else {
                None
            },
            transform: style.transform,
            border_radius: style.border_radius,
            outline_width: style.outline_width,
            outline_color: style.outline_color.map(|c| c.to_f32_rgb()),
            text_indent: 0.0,
            letter_spacing: 0.0,
            word_spacing: 0.0,
            vertical_align: VerticalAlign::Baseline,
            background_gradient,
            background_radial_gradient,
            background_svg,
            background_blur_radius,
            background_size,
            background_position,
            background_repeat,
            background_origin,
            z_index: 0,
            repeat_on_each_page: false,
            positioned_depth: 0,
            heading_level: None,
            clip_children_count: 0,
        });
        // Pull y back so children flow inside the container background
        let BackgroundFields {
            gradient: background_gradient,
            radial_gradient: background_radial_gradient,
            svg: background_svg,
            blur_radius: background_blur_radius,
            size: background_size,
            position: background_position,
            repeat: background_repeat,
            origin: background_origin,
        } = BackgroundFields::none();
        output.push(LayoutElement::TextBlock {
            lines: Vec::new(),
            margin_top: -bg_flow_height,
            margin_bottom: 0.0,
            text_align: TextAlign::Left,
            background_color: None,
            padding_top: 0.0,
            padding_bottom: 0.0,
            padding_left: 0.0,
            padding_right: 0.0,
            border: LayoutBorder::default(),
            block_width: None,
            block_height: None,
            opacity: 1.0,
            float: Float::None,
            clear: Clear::None,
            position: Position::Static,
            offset_top: 0.0,
            offset_left: 0.0,
            offset_bottom: 0.0,
            offset_right: 0.0,
            containing_block: None,
            box_shadow: None,
            visible: true,
            clip_rect: None,
            transform: None,
            border_radius: 0.0,
            outline_width: 0.0,
            outline_color: None,
            text_indent: 0.0,
            letter_spacing: 0.0,
            word_spacing: 0.0,
            vertical_align: VerticalAlign::Baseline,
            background_gradient,
            background_radial_gradient,
            background_svg,
            background_blur_radius,
            background_size,
            background_position,
            background_repeat,
            background_origin,
            z_index: 0,
            repeat_on_each_page: false,
            positioned_depth: 0,
            heading_level: None,
            clip_children_count: 0,
        });
    }

    // Position items within the flex container and emit them
    let mut cross_offset = 0.0;
    // All flex cells across every line, merged into a single FlexRow for
    // row direction. This keeps container borders/backgrounds around every
    // wrapped line and keeps pagination flow correct.
    let mut all_flex_cells: Vec<FlexCell> = Vec::new();

    for line in &lines {
        let line_items: Vec<usize> = line.item_indices.clone();
        let line_item_count = line_items.len();

        match direction {
            FlexDirection::Row => {
                let total_item_width: f32 = line_items.iter().map(|&i| items[i].width).sum();
                let total_gap = if line_item_count > 1 {
                    (line_item_count - 1) as f32 * gap
                } else {
                    0.0
                };
                let mut free_space = inner_width - total_item_width - total_gap;

                // Flex grow: distribute positive free space proportionally
                let total_grow: f32 = line_items.iter().map(|&i| items[i].flex_grow).sum();
                if free_space > 0.0 && total_grow > 0.0 {
                    for &i in &line_items {
                        items[i].width += free_space * (items[i].flex_grow / total_grow);
                    }
                    free_space = 0.0;
                }

                // Flex shrink: shrink items when overflowing
                if free_space < 0.0 {
                    let total_shrink_weighted: f32 = line_items
                        .iter()
                        .map(|&i| items[i].flex_shrink * items[i].base_width)
                        .sum();
                    if total_shrink_weighted > 0.0 {
                        let deficit = -free_space;
                        for &i in &line_items {
                            let shrink_ratio =
                                items[i].flex_shrink * items[i].base_width / total_shrink_weighted;
                            items[i].width = (items[i].width - deficit * shrink_ratio).max(0.0);
                        }
                    }
                    free_space = 0.0;
                }

                // Second pass: re-layout flex-grow items whose width changed
                // significantly. This ensures percentage-width children inside
                // flex items resolve against the final cell width, not the
                // initial estimate.
                for &i in &line_items {
                    if items[i].flex_grow > 0.0
                        && (items[i].width - items[i].base_width).abs() > 1.0
                    {
                        let final_w = items[i].width;
                        let child_el = child_elements[i];
                        let has_block_kids = child_el.children.iter().any(|c| {
                            matches!(c, DomNode::Element(e) if e.tag.is_block() && !collects_as_inline_text(e.tag))
                        });
                        if has_block_kids {
                            let mut relayout_buf = Vec::new();
                            let mut relayout_ancestors = ancestors.to_vec();
                            relayout_ancestors.push(AncestorInfo {
                                element: el,
                                child_index: 0,
                                sibling_count: 0,
                                preceding_siblings: Vec::new(),
                            });
                            let relayout_ctx = ctx
                                .with_parent(final_w, Some(10000.0), style.font_size)
                                .with_containing_block(None);
                            flatten_element(
                                child_el,
                                style,
                                &relayout_ctx,
                                &mut relayout_buf,
                                None,
                                &relayout_ancestors,
                                positioned_depth,
                                i,
                                child_count,
                                &[],
                                env,
                            );
                            if !relayout_buf.is_empty() {
                                items[i].elements = relayout_buf;
                                items[i].height =
                                    items[i].elements.iter().map(estimate_element_height).sum();
                            }
                        }
                    }
                }

                let free_space = free_space.max(0.0);

                // Calculate starting x and spacing based on justify-content
                let (mut x, extra_gap) = match justify {
                    JustifyContent::FlexStart => (0.0, 0.0),
                    JustifyContent::FlexEnd => (free_space, 0.0),
                    JustifyContent::Center => (free_space / 2.0, 0.0),
                    JustifyContent::SpaceBetween => {
                        if line_item_count > 1 {
                            (0.0, free_space / (line_item_count - 1) as f32)
                        } else {
                            (0.0, 0.0)
                        }
                    }
                    JustifyContent::SpaceAround => {
                        let around = free_space / line_item_count as f32;
                        (around / 2.0, around)
                    }
                };

                // Build FlexCells for this row line.
                let mut flex_cells = Vec::new();
                for &item_idx in &line_items {
                    let item = &items[item_idx];

                    // Complex items (multiple elements): merge all lines
                    // into a single FlexCell, inserting margin spacing
                    if item.elements.len() > 1 {
                        let mut merged_lines = Vec::new();
                        let mut first_bg = None;
                        let mut first_pt = 0.0f32;
                        let mut first_pb = 0.0f32;
                        let mut first_pl = 0.0f32;
                        let mut first_pr = 0.0f32;
                        let mut first_br = 0.0f32;
                        let mut is_first = true;
                        // Check if all elements are TextBlocks without borders (mergeable).
                        // TextBlocks with borders must go through nested_elements
                        // so the renderer can draw their individual borders.
                        let all_text_blocks = item.elements.iter().all(|e| {
                            matches!(e, LayoutElement::TextBlock { border, .. } if !border.has_any())
                        });

                        if !all_text_blocks {
                            // Mixed elements (e.g. TextBlock + TableRow):
                            // store in nested_elements for the renderer to handle
                            flex_cells.push(FlexCell {
                                lines: Vec::new(),
                                x_offset: x,
                                width: item.width,
                                natural_height: item.height,
                                text_align: TextAlign::Left,
                                background_color: None,
                                padding_top: 0.0,
                                padding_right: 0.0,
                                padding_bottom: 0.0,
                                padding_left: 0.0,
                                border: LayoutBorder::default(),
                                border_radius: 0.0,
                                background_gradient: None,
                                background_radial_gradient: None,
                                background_svg: None,
                                background_blur_radius: 0.0,
                                background_size: BackgroundSize::Auto,
                                background_position: BackgroundPosition::default(),
                                background_repeat: BackgroundRepeat::Repeat,
                                background_origin: BackgroundOrigin::Padding,
                                transform: None,
                                box_shadow: None,
                                nested_elements: item.elements.clone(),
                                y_offset: 0.0,
                                line_cross_size: 0.0,
                            });
                            x += item.width + gap;
                            continue;
                        }

                        for elem in &item.elements {
                            if let LayoutElement::TextBlock {
                                lines: tb_lines,
                                margin_top,
                                background_color: tb_bg,
                                padding_top: tb_pt,
                                padding_bottom: tb_pb,
                                padding_left: tb_pl,
                                padding_right: tb_pr,
                                border_radius: tb_br,
                                ..
                            } = elem
                            {
                                if is_first {
                                    first_bg = *tb_bg;
                                    first_pt = *tb_pt;
                                    first_pb = *tb_pb;
                                    first_pl = *tb_pl;
                                    first_pr = *tb_pr;
                                    first_br = *tb_br;
                                    is_first = false;
                                }
                                // Add margin spacing between sub-elements
                                if !merged_lines.is_empty() && *margin_top > 0.0 {
                                    merged_lines.push(TextLine {
                                        runs: Vec::new(),
                                        height: *margin_top,
                                    });
                                }
                                merged_lines.extend(tb_lines.iter().cloned());
                            }
                        }
                        // Calculate natural height for merged item
                        let natural_h: f32 = merged_lines.iter().map(|l| l.height).sum();
                        flex_cells.push(FlexCell {
                            lines: merged_lines,
                            x_offset: x,
                            width: item.width,
                            natural_height: natural_h,
                            text_align: TextAlign::Left,
                            background_color: first_bg,
                            padding_top: first_pt,
                            padding_right: first_pr,
                            padding_bottom: first_pb,
                            padding_left: first_pl,
                            border: LayoutBorder::default(),
                            border_radius: first_br,
                            background_gradient: None,
                            background_radial_gradient: None,
                            background_svg: None,
                            background_blur_radius: 0.0,
                            background_size: BackgroundSize::Auto,
                            background_position: BackgroundPosition::default(),
                            background_repeat: BackgroundRepeat::Repeat,
                            background_origin: BackgroundOrigin::Padding,
                            transform: None,
                            box_shadow: None,
                            nested_elements: Vec::new(),
                            y_offset: 0.0,
                            line_cross_size: 0.0,
                        });
                        x += item.width + gap;
                        continue;
                    }

                    // Simple items: extract into FlexCell
                    if let Some(LayoutElement::TextBlock {
                        lines: tb_lines,
                        text_align: tb_ta,
                        background_color: tb_bg,
                        padding_top: tb_pt,
                        padding_bottom: tb_pb,
                        padding_left: tb_pl,
                        padding_right: tb_pr,
                        border_radius: tb_br,
                        background_gradient: tb_grad,
                        background_radial_gradient: tb_rgrad,
                        background_svg: tb_bg_svg,
                        background_blur_radius: tb_bg_blur,
                        background_size: tb_bg_size,
                        background_position: tb_bg_pos,
                        background_repeat: tb_bg_repeat,
                        background_origin: tb_bg_origin,
                        box_shadow: tb_bs,
                        border,
                        ..
                    }) = item.elements.first()
                    {
                        // Calculate natural height for this item
                        let text_h: f32 = tb_lines.iter().map(|l| l.height).sum();
                        let natural_h = *tb_pt + text_h + *tb_pb + border.vertical_width();
                        flex_cells.push(FlexCell {
                            lines: tb_lines.clone(),
                            x_offset: x,
                            width: item.width,
                            text_align: *tb_ta,
                            background_color: *tb_bg,
                            padding_top: *tb_pt,
                            padding_right: *tb_pr,
                            padding_bottom: *tb_pb,
                            padding_left: *tb_pl,
                            border: *border,
                            border_radius: *tb_br,
                            background_gradient: tb_grad.clone(),
                            background_radial_gradient: tb_rgrad.clone(),
                            background_svg: tb_bg_svg.clone(),
                            background_blur_radius: *tb_bg_blur,
                            background_size: *tb_bg_size,
                            background_position: *tb_bg_pos,
                            background_repeat: *tb_bg_repeat,
                            background_origin: *tb_bg_origin,
                            transform: None,
                            box_shadow: *tb_bs,
                            nested_elements: Vec::new(),
                            natural_height: natural_h,
                            y_offset: 0.0,
                            line_cross_size: 0.0,
                        });
                    } else {
                        // Single non-TextBlock element (e.g. Container): store
                        // in nested_elements for the renderer to handle.
                        flex_cells.push(FlexCell {
                            lines: Vec::new(),
                            x_offset: x,
                            width: item.width,
                            natural_height: item.height,
                            text_align: TextAlign::Left,
                            background_color: None,
                            padding_top: 0.0,
                            padding_right: 0.0,
                            padding_bottom: 0.0,
                            padding_left: 0.0,
                            border: LayoutBorder::default(),
                            border_radius: 0.0,
                            background_gradient: None,
                            background_radial_gradient: None,
                            background_svg: None,
                            background_blur_radius: 0.0,
                            background_size: BackgroundSize::Auto,
                            background_position: BackgroundPosition::default(),
                            background_repeat: BackgroundRepeat::Repeat,
                            background_origin: BackgroundOrigin::Padding,
                            transform: None,
                            box_shadow: None,
                            nested_elements: item.elements.clone(),
                            y_offset: 0.0,
                            line_cross_size: 0.0,
                        });
                    }

                    x += item.width + gap + extra_gap;
                }

                // Stamp each cell with its cross-axis position within the
                // container so a single FlexRow can span every wrapped line.
                for cell in flex_cells.iter_mut() {
                    cell.y_offset = cross_offset;
                    cell.line_cross_size = line.cross_size;
                }
                all_flex_cells.extend(flex_cells);
            }
            FlexDirection::Column => {
                let _total_item_height: f32 = line_items.iter().map(|&i| items[i].height).sum();
                let _total_gap = if line_item_count > 1 {
                    (line_item_count - 1) as f32 * gap
                } else {
                    0.0
                };
                let free_space = 0.0f32; // column doesn't constrain main axis to container width
                let _ = free_space;

                let mut y = 0.0;

                for &item_idx in &line_items {
                    let item = &items[item_idx];

                    // Calculate cross-axis (horizontal) alignment
                    let x_offset = match align {
                        AlignItems::FlexStart => 0.0,
                        AlignItems::FlexEnd => inner_width - item.width,
                        AlignItems::Center => (inner_width - item.width) / 2.0,
                        AlignItems::Stretch => 0.0,
                    };

                    let effective_width = if align == AlignItems::Stretch {
                        Some(inner_width)
                    } else {
                        Some(item.width)
                    };

                    for elem in &item.elements {
                        if let LayoutElement::TextBlock {
                            lines: tb_lines,
                            margin_top: tb_mt,
                            margin_bottom: tb_mb,
                            text_align: tb_ta,
                            background_color: tb_bg,
                            padding_top: tb_pt,
                            padding_bottom: tb_pb,
                            padding_left: tb_pl,
                            padding_right: tb_pr,
                            border: tb_border,
                            block_height: tb_bh,
                            opacity: tb_op,
                            position: tb_pos,
                            box_shadow: tb_bs,
                            visible: tb_vis,
                            clip_rect: tb_clip,
                            transform: tb_transform,
                            border_radius: tb_br,
                            outline_width: tb_ow,
                            outline_color: tb_oc,
                            text_indent: tb_ti,
                            letter_spacing: tb_ls,
                            word_spacing: tb_ws,
                            vertical_align: tb_va,
                            background_gradient: tb_grad,
                            background_radial_gradient: tb_rgrad,
                            background_svg: tb_bg_svg,
                            background_blur_radius: tb_bg_blur,
                            background_size: tb_bg_size,
                            background_position: tb_bg_pos,
                            background_repeat: tb_bg_repeat,
                            background_origin: tb_bg_origin,
                            ..
                        } = elem
                        {
                            output.push(LayoutElement::TextBlock {
                                lines: tb_lines.clone(),
                                margin_top: if y == 0.0 && !emitted_column_bg {
                                    style.margin.top + style.padding.top + *tb_mt
                                } else if y == 0.0 {
                                    // Background element already accounts for margin;
                                    // add only the container padding offset.
                                    style.padding.top + *tb_mt
                                } else {
                                    // Apply gap between column-direction flex items.
                                    gap + *tb_mt
                                },
                                margin_bottom: *tb_mb,
                                text_align: *tb_ta,
                                background_color: *tb_bg,
                                padding_top: *tb_pt,
                                padding_bottom: *tb_pb,
                                padding_left: *tb_pl,
                                padding_right: *tb_pr,
                                border: *tb_border,
                                block_width: effective_width,
                                block_height: *tb_bh,
                                opacity: *tb_op,
                                float: Float::None,
                                clear: Clear::None,
                                position: if x_offset > 0.0 || style.padding.left > 0.0 {
                                    Position::Relative
                                } else {
                                    *tb_pos
                                },
                                offset_top: 0.0,
                                offset_left: x_offset + style.padding.left,
                                offset_bottom: 0.0,
                                offset_right: 0.0,
                                containing_block: None,
                                box_shadow: *tb_bs,
                                visible: *tb_vis,
                                clip_rect: *tb_clip,
                                transform: *tb_transform,
                                border_radius: *tb_br,
                                outline_width: *tb_ow,
                                outline_color: *tb_oc,
                                text_indent: *tb_ti,
                                letter_spacing: *tb_ls,
                                word_spacing: *tb_ws,
                                vertical_align: *tb_va,
                                background_gradient: tb_grad.clone(),
                                background_radial_gradient: tb_rgrad.clone(),
                                background_svg: tb_bg_svg.clone(),
                                background_blur_radius: *tb_bg_blur,
                                background_size: *tb_bg_size,
                                background_position: *tb_bg_pos,
                                background_repeat: *tb_bg_repeat,
                                background_origin: *tb_bg_origin,
                                z_index: 0,
                                repeat_on_each_page: false,
                                positioned_depth: 0,
                                heading_level: None,
                                clip_children_count: 0,
                            });
                        }
                    }

                    y += item.height + gap;
                }
            }
        }

        cross_offset += line.cross_size + gap;
    }

    // Emit a single FlexRow carrying every line's cells for row direction.
    // The row's height is the container's inner cross size so pagination and
    // the visual border both include every wrapped line. Each cell's own
    // y_offset and line_cross_size handle per-line alignment internally.
    if direction == FlexDirection::Row && !all_flex_cells.is_empty() {
        let row_height = total_cross.max(inner_cross_size);
        output.push(LayoutElement::FlexRow {
            cells: all_flex_cells,
            row_height,
            margin_top: style.margin.top,
            margin_bottom: 0.0,
            background_color: bg,
            container_width: block_w,
            padding_top: style.padding.top,
            padding_bottom: style.padding.bottom,
            padding_left: style.padding.left,
            padding_right: style.padding.right,
            border: LayoutBorder::from_computed(&style.border),
            border_radius: style.border_radius,
            box_shadow: style.box_shadow,
            background_gradient: style.background_gradient.clone(),
            background_radial_gradient: style.background_radial_gradient.clone(),
            background_svg: background_svg_for_style(style),
            background_blur_radius: style.blur_radius,
            background_size: style.background_size,
            background_position: style.background_position,
            background_repeat: style.background_repeat,
            background_origin: style.background_origin,
            align_items: align,
        });
    }

    // Emit trailing margin (include bottom padding when bg spacer shifted y back)
    let trailing = if emitted_column_bg {
        style.padding.bottom + style.margin.bottom
    } else {
        style.margin.bottom
    };
    if trailing > 0.0 {
        output.push(LayoutElement::TextBlock {
            lines: Vec::new(),
            margin_top: trailing,
            margin_bottom: 0.0,
            text_align: TextAlign::Left,
            background_color: None,
            padding_top: 0.0,
            padding_bottom: 0.0,
            padding_left: 0.0,
            padding_right: 0.0,
            border: LayoutBorder::default(),
            block_width: None,
            block_height: None,
            opacity: 1.0,
            float: Float::None,
            clear: Clear::None,
            position: Position::Static,
            offset_top: 0.0,
            offset_left: 0.0,
            offset_bottom: 0.0,
            offset_right: 0.0,
            containing_block: None,
            box_shadow: None,
            visible: true,
            clip_rect: None,
            transform: None,
            border_radius: 0.0,
            outline_width: 0.0,
            outline_color: None,
            text_indent: 0.0,
            letter_spacing: 0.0,
            word_spacing: 0.0,
            vertical_align: VerticalAlign::Baseline,
            background_gradient: None,
            background_radial_gradient: None,
            background_svg: None,
            background_blur_radius: 0.0,
            background_size: BackgroundSize::Auto,
            background_position: BackgroundPosition::default(),
            background_repeat: BackgroundRepeat::Repeat,
            background_origin: BackgroundOrigin::Padding,
            z_index: 0,
            repeat_on_each_page: false,
            positioned_depth: 0,
            heading_level: None,
            clip_children_count: 0,
        });
    }
}