boko 0.2.0

Fast ebook conversion library for EPUB and Kindle formats
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
//! Style pool with SoA (Struct of Arrays) layout for efficient storage.

use std::collections::HashMap;
use std::fmt::Write;
use std::hash::{Hash, Hasher};

/// Trait for converting IR style values back to CSS strings.
pub trait ToCss {
    /// Write this value as CSS to the buffer.
    fn to_css(&self, buf: &mut String);

    /// Convert to a CSS string (convenience method).
    fn to_css_string(&self) -> String {
        let mut buf = String::new();
        self.to_css(&mut buf);
        buf
    }
}

/// Unique identifier for a style in the StylePool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct StyleId(pub u32);

impl StyleId {
    /// The default style (always 0).
    pub const DEFAULT: StyleId = StyleId(0);
}

/// Font weight (100-900, with named constants).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct FontWeight(pub u16);

impl FontWeight {
    pub const NORMAL: FontWeight = FontWeight(400);
    pub const BOLD: FontWeight = FontWeight(700);
}

impl ToCss for FontWeight {
    fn to_css(&self, buf: &mut String) {
        match self.0 {
            400 => buf.push_str("normal"),
            700 => buf.push_str("bold"),
            w => write!(buf, "{}", w).unwrap(),
        }
    }
}

/// Font style (normal, italic, oblique).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FontStyle {
    #[default]
    Normal,
    Italic,
    Oblique,
}

impl ToCss for FontStyle {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            FontStyle::Normal => "normal",
            FontStyle::Italic => "italic",
            FontStyle::Oblique => "oblique",
        });
    }
}

/// Font variant (normal, small-caps).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FontVariant {
    #[default]
    Normal,
    SmallCaps,
}

/// Text transform values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextTransform {
    #[default]
    None,
    Uppercase,
    Lowercase,
    Capitalize,
}

impl ToCss for TextTransform {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            TextTransform::None => "none",
            TextTransform::Uppercase => "uppercase",
            TextTransform::Lowercase => "lowercase",
            TextTransform::Capitalize => "capitalize",
        });
    }
}

/// Hyphenation mode.
/// Default is `Manual` so that explicit `hyphens: auto` is emitted in KFX output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Hyphens {
    Auto,
    #[default]
    Manual,
    None,
}

impl ToCss for Hyphens {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            Hyphens::Auto => "auto",
            Hyphens::Manual => "manual",
            Hyphens::None => "none",
        });
    }
}

/// Text decoration line style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum DecorationStyle {
    #[default]
    None,
    Solid,
    Dotted,
    Dashed,
    Double,
}

impl ToCss for DecorationStyle {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            DecorationStyle::None => "none",
            DecorationStyle::Solid => "solid",
            DecorationStyle::Dotted => "dotted",
            DecorationStyle::Dashed => "dashed",
            DecorationStyle::Double => "double",
        });
    }
}

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

impl ToCss for Float {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            Float::None => "none",
            Float::Left => "left",
            Float::Right => "right",
        });
    }
}

/// Page break behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BreakValue {
    #[default]
    Auto,
    Always,
    Avoid,
    /// Break to a new column (for multi-column layouts)
    Column,
}

impl ToCss for BreakValue {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            BreakValue::Auto => "auto",
            BreakValue::Always => "always",
            BreakValue::Avoid => "avoid",
            BreakValue::Column => "column",
        });
    }
}

/// Border style values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BorderStyle {
    #[default]
    None,
    Solid,
    Dotted,
    Dashed,
    Double,
    Groove,
    Ridge,
    Inset,
    Outset,
}

impl ToCss for BorderStyle {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            BorderStyle::None => "none",
            BorderStyle::Solid => "solid",
            BorderStyle::Dotted => "dotted",
            BorderStyle::Dashed => "dashed",
            BorderStyle::Double => "double",
            BorderStyle::Groove => "groove",
            BorderStyle::Ridge => "ridge",
            BorderStyle::Inset => "inset",
            BorderStyle::Outset => "outset",
        });
    }
}

/// List style position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ListStylePosition {
    #[default]
    Outside,
    Inside,
}

impl ToCss for ListStylePosition {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            ListStylePosition::Outside => "outside",
            ListStylePosition::Inside => "inside",
        });
    }
}

/// CSS visibility values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Visibility {
    #[default]
    Visible,
    Hidden,
    Collapse,
}

impl ToCss for Visibility {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            Visibility::Visible => "visible",
            Visibility::Hidden => "hidden",
            Visibility::Collapse => "collapse",
        });
    }
}

/// CSS box-sizing values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BoxSizing {
    /// Width/height include only content (CSS default)
    #[default]
    ContentBox,
    /// Width/height include padding and border
    BorderBox,
}

impl ToCss for BoxSizing {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            BoxSizing::ContentBox => "content-box",
            BoxSizing::BorderBox => "border-box",
        });
    }
}

impl ToCss for FontVariant {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            FontVariant::Normal => "normal",
            FontVariant::SmallCaps => "small-caps",
        });
    }
}

/// Text alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextAlign {
    #[default]
    Start,
    End,
    Left,
    Right,
    Center,
    Justify,
}

impl ToCss for TextAlign {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            TextAlign::Start => "start",
            TextAlign::End => "end",
            TextAlign::Left => "left",
            TextAlign::Right => "right",
            TextAlign::Center => "center",
            TextAlign::Justify => "justify",
        });
    }
}

/// Display mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Display {
    #[default]
    Block,
    Inline,
    None,
    ListItem,
    TableCell,
    TableRow,
}

/// CSS list-style-type values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ListStyleType {
    /// No marker
    #[default]
    None,
    /// • (default for ul)
    Disc,
    /// â—‹
    Circle,
    /// â–ª
    Square,
    /// 1, 2, 3 (default for ol)
    Decimal,
    /// a, b, c
    LowerAlpha,
    /// A, B, C
    UpperAlpha,
    /// i, ii, iii
    LowerRoman,
    /// I, II, III
    UpperRoman,
}

impl ToCss for ListStyleType {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            ListStyleType::None => "none",
            ListStyleType::Disc => "disc",
            ListStyleType::Circle => "circle",
            ListStyleType::Square => "square",
            ListStyleType::Decimal => "decimal",
            ListStyleType::LowerAlpha => "lower-alpha",
            ListStyleType::UpperAlpha => "upper-alpha",
            ListStyleType::LowerRoman => "lower-roman",
            ListStyleType::UpperRoman => "upper-roman",
        });
    }
}

impl ToCss for Display {
    fn to_css(&self, buf: &mut String) {
        buf.push_str(match self {
            Display::Block => "block",
            Display::Inline => "inline",
            Display::None => "none",
            Display::ListItem => "list-item",
            Display::TableCell => "table-cell",
            Display::TableRow => "table-row",
        });
    }
}

/// RGBA color (8 bits per channel).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Color {
    pub const BLACK: Color = Color {
        r: 0,
        g: 0,
        b: 0,
        a: 255,
    };
    pub const WHITE: Color = Color {
        r: 255,
        g: 255,
        b: 255,
        a: 255,
    };
    pub const TRANSPARENT: Color = Color {
        r: 0,
        g: 0,
        b: 0,
        a: 0,
    };

    /// Create a new opaque color.
    pub fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b, a: 255 }
    }

    /// Create a new color with alpha.
    pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }
}

impl ToCss for Color {
    fn to_css(&self, buf: &mut String) {
        if self.a == 255 {
            // Opaque: use #RRGGBB
            write!(buf, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b).unwrap();
        } else if self.a == 0 {
            buf.push_str("transparent");
        } else {
            // With alpha: use rgba()
            let alpha = self.a as f32 / 255.0;
            write!(buf, "rgba({},{},{},{:.2})", self.r, self.g, self.b, alpha).unwrap();
        }
    }
}

/// Length value with unit.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Length {
    #[default]
    Auto,
    Px(f32),
    Em(f32),
    Rem(f32),
    Percent(f32),
}

impl Eq for Length {}

impl Hash for Length {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Length::Auto => 0u8.hash(state),
            Length::Px(v) => {
                1u8.hash(state);
                v.to_bits().hash(state);
            }
            Length::Em(v) => {
                2u8.hash(state);
                v.to_bits().hash(state);
            }
            Length::Rem(v) => {
                3u8.hash(state);
                v.to_bits().hash(state);
            }
            Length::Percent(v) => {
                4u8.hash(state);
                v.to_bits().hash(state);
            }
        }
    }
}

impl ToCss for Length {
    fn to_css(&self, buf: &mut String) {
        match self {
            Length::Auto => buf.push_str("auto"),
            Length::Px(v) => {
                if *v == 0.0 {
                    buf.push('0');
                } else {
                    write!(buf, "{}px", v).unwrap();
                }
            }
            Length::Em(v) => write!(buf, "{}em", v).unwrap(),
            Length::Rem(v) => write!(buf, "{}rem", v).unwrap(),
            Length::Percent(v) => write!(buf, "{}%", v).unwrap(),
        }
    }
}

/// Computed style for a node (all properties resolved).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct ComputedStyle {
    // Font properties
    pub font_family: Option<String>,
    pub font_size: Length,
    pub font_weight: FontWeight,
    pub font_style: FontStyle,

    // Colors
    pub color: Option<Color>,
    pub background_color: Option<Color>,

    // Text
    pub text_align: TextAlign,
    pub text_indent: Length,
    pub line_height: Length,
    pub text_decoration_underline: bool,
    pub text_decoration_line_through: bool,

    // Box model
    pub display: Display,
    pub margin_top: Length,
    pub margin_bottom: Length,
    pub margin_left: Length,
    pub margin_right: Length,
    pub padding_top: Length,
    pub padding_bottom: Length,
    pub padding_left: Length,
    pub padding_right: Length,

    // Vertical alignment for inline elements
    pub vertical_align_super: bool,
    pub vertical_align_sub: bool,

    // List properties
    pub list_style_type: ListStyleType,

    // Font variant
    pub font_variant: FontVariant,

    // Text spacing
    pub letter_spacing: Length,
    pub word_spacing: Length,

    // Text transform
    pub text_transform: TextTransform,

    // Hyphenation
    pub hyphens: Hyphens,

    // No-break (white-space: nowrap)
    pub no_break: bool,

    // Phase 2: Text decoration extensions
    pub underline_style: DecorationStyle,
    pub overline: bool,
    pub underline_color: Option<Color>,

    // Phase 3: Layout properties
    pub width: Length,
    pub height: Length,
    pub max_width: Length,
    pub min_height: Length,
    pub float: Float,

    // Phase 4: Page break properties
    pub break_before: BreakValue,
    pub break_after: BreakValue,
    pub break_inside: BreakValue,

    // Phase 5: Border properties (4 sides)
    pub border_style_top: BorderStyle,
    pub border_style_right: BorderStyle,
    pub border_style_bottom: BorderStyle,
    pub border_style_left: BorderStyle,
    pub border_width_top: Length,
    pub border_width_right: Length,
    pub border_width_bottom: Length,
    pub border_width_left: Length,
    pub border_color_top: Option<Color>,
    pub border_color_right: Option<Color>,
    pub border_color_bottom: Option<Color>,
    pub border_color_left: Option<Color>,
    // Border radius (corners)
    pub border_radius_top_left: Length,
    pub border_radius_top_right: Length,
    pub border_radius_bottom_left: Length,
    pub border_radius_bottom_right: Length,

    // Phase 6: List properties
    pub list_style_position: ListStylePosition,

    // Phase 7: Amazon properties
    pub language: Option<String>,
    pub visibility: Visibility,
    pub box_sizing: BoxSizing,
}

impl ComputedStyle {
    /// Check if this style differs from the default (has any non-default properties).
    pub fn is_default(&self) -> bool {
        *self == ComputedStyle::default()
    }

    // --- Modifier checks for exporters ---

    /// Check if the style is bold (font-weight >= 700).
    #[inline]
    pub fn is_bold(&self) -> bool {
        self.font_weight.0 >= 700
    }

    /// Check if the style is italic.
    #[inline]
    pub fn is_italic(&self) -> bool {
        matches!(self.font_style, FontStyle::Italic | FontStyle::Oblique)
    }

    /// Check if the style has underline decoration.
    #[inline]
    pub fn is_underline(&self) -> bool {
        self.text_decoration_underline
    }

    /// Check if the style has strikethrough decoration.
    #[inline]
    pub fn is_strikethrough(&self) -> bool {
        self.text_decoration_line_through
    }

    /// Check if the style is superscript.
    #[inline]
    pub fn is_superscript(&self) -> bool {
        self.vertical_align_super
    }

    /// Check if the style is subscript.
    #[inline]
    pub fn is_subscript(&self) -> bool {
        self.vertical_align_sub
    }

    /// Check if the style uses a monospace font.
    pub fn is_monospace(&self) -> bool {
        self.font_family
            .as_ref()
            .map(|f| {
                let lower = f.to_lowercase();
                lower.contains("mono")
                    || lower.contains("courier")
                    || lower.contains("consolas")
                    || lower.contains("menlo")
            })
            .unwrap_or(false)
    }

    /// Check if the list style is ordered (numbered).
    pub fn is_ordered_list(&self) -> bool {
        matches!(
            self.list_style_type,
            ListStyleType::Decimal
                | ListStyleType::LowerAlpha
                | ListStyleType::UpperAlpha
                | ListStyleType::LowerRoman
                | ListStyleType::UpperRoman
        )
    }

    /// Check if the style uses small-caps font variant.
    #[inline]
    pub fn is_small_caps(&self) -> bool {
        matches!(self.font_variant, FontVariant::SmallCaps)
    }
}

impl ToCss for ComputedStyle {
    fn to_css(&self, buf: &mut String) {
        let default = ComputedStyle::default();

        // Font properties
        if let Some(ref family) = self.font_family {
            write!(buf, "font-family: {}; ", family).unwrap();
        }
        if self.font_size != default.font_size {
            buf.push_str("font-size: ");
            self.font_size.to_css(buf);
            buf.push_str("; ");
        }
        if self.font_weight != default.font_weight {
            buf.push_str("font-weight: ");
            self.font_weight.to_css(buf);
            buf.push_str("; ");
        }
        if self.font_style != default.font_style {
            buf.push_str("font-style: ");
            self.font_style.to_css(buf);
            buf.push_str("; ");
        }

        // Colors
        if let Some(color) = self.color {
            buf.push_str("color: ");
            color.to_css(buf);
            buf.push_str("; ");
        }
        if let Some(bg) = self.background_color {
            buf.push_str("background-color: ");
            bg.to_css(buf);
            buf.push_str("; ");
        }

        // Text properties
        if self.text_align != default.text_align {
            buf.push_str("text-align: ");
            self.text_align.to_css(buf);
            buf.push_str("; ");
        }
        if self.text_indent != default.text_indent {
            buf.push_str("text-indent: ");
            self.text_indent.to_css(buf);
            buf.push_str("; ");
        }
        if self.line_height != default.line_height {
            buf.push_str("line-height: ");
            self.line_height.to_css(buf);
            buf.push_str("; ");
        }

        // Text decorations
        let mut decorations = Vec::new();
        if self.text_decoration_underline {
            decorations.push("underline");
        }
        if self.text_decoration_line_through {
            decorations.push("line-through");
        }
        if !decorations.is_empty() {
            write!(buf, "text-decoration: {}; ", decorations.join(" ")).unwrap();
        }

        // Display (only if not block, which is the semantic default for most elements)
        if self.display != default.display {
            buf.push_str("display: ");
            self.display.to_css(buf);
            buf.push_str("; ");
        }

        // Margins
        if self.margin_top != default.margin_top {
            buf.push_str("margin-top: ");
            self.margin_top.to_css(buf);
            buf.push_str("; ");
        }
        if self.margin_bottom != default.margin_bottom {
            buf.push_str("margin-bottom: ");
            self.margin_bottom.to_css(buf);
            buf.push_str("; ");
        }
        if self.margin_left != default.margin_left {
            buf.push_str("margin-left: ");
            self.margin_left.to_css(buf);
            buf.push_str("; ");
        }
        if self.margin_right != default.margin_right {
            buf.push_str("margin-right: ");
            self.margin_right.to_css(buf);
            buf.push_str("; ");
        }

        // Padding
        if self.padding_top != default.padding_top {
            buf.push_str("padding-top: ");
            self.padding_top.to_css(buf);
            buf.push_str("; ");
        }
        if self.padding_bottom != default.padding_bottom {
            buf.push_str("padding-bottom: ");
            self.padding_bottom.to_css(buf);
            buf.push_str("; ");
        }
        if self.padding_left != default.padding_left {
            buf.push_str("padding-left: ");
            self.padding_left.to_css(buf);
            buf.push_str("; ");
        }
        if self.padding_right != default.padding_right {
            buf.push_str("padding-right: ");
            self.padding_right.to_css(buf);
            buf.push_str("; ");
        }

        // Vertical alignment
        if self.vertical_align_super {
            buf.push_str("vertical-align: super; ");
        } else if self.vertical_align_sub {
            buf.push_str("vertical-align: sub; ");
        }

        // List style
        if self.list_style_type != default.list_style_type {
            buf.push_str("list-style-type: ");
            self.list_style_type.to_css(buf);
            buf.push_str("; ");
        }

        // Font variant
        if self.font_variant != FontVariant::Normal {
            buf.push_str("font-variant: ");
            self.font_variant.to_css(buf);
            buf.push_str("; ");
        }

        // Letter spacing
        if self.letter_spacing != default.letter_spacing {
            buf.push_str("letter-spacing: ");
            self.letter_spacing.to_css(buf);
            buf.push_str("; ");
        }

        // Word spacing
        if self.word_spacing != default.word_spacing {
            buf.push_str("word-spacing: ");
            self.word_spacing.to_css(buf);
            buf.push_str("; ");
        }

        // Text transform
        if self.text_transform != default.text_transform {
            buf.push_str("text-transform: ");
            self.text_transform.to_css(buf);
            buf.push_str("; ");
        }

        // Hyphens
        if self.hyphens != default.hyphens {
            buf.push_str("hyphens: ");
            self.hyphens.to_css(buf);
            buf.push_str("; ");
        }

        // White-space nowrap
        if self.no_break {
            buf.push_str("white-space: nowrap; ");
        }

        // Underline style (if different from boolean)
        if self.underline_style != default.underline_style {
            buf.push_str("text-decoration-style: ");
            self.underline_style.to_css(buf);
            buf.push_str("; ");
        }

        // Overline
        if self.overline {
            buf.push_str("text-decoration-line: overline; ");
        }

        // Underline color
        if let Some(color) = self.underline_color {
            buf.push_str("text-decoration-color: ");
            color.to_css(buf);
            buf.push_str("; ");
        }

        // Width
        if self.width != default.width {
            buf.push_str("width: ");
            self.width.to_css(buf);
            buf.push_str("; ");
        }

        // Height
        if self.height != default.height {
            buf.push_str("height: ");
            self.height.to_css(buf);
            buf.push_str("; ");
        }

        // Max-width
        if self.max_width != default.max_width {
            buf.push_str("max-width: ");
            self.max_width.to_css(buf);
            buf.push_str("; ");
        }

        // Min-height
        if self.min_height != default.min_height {
            buf.push_str("min-height: ");
            self.min_height.to_css(buf);
            buf.push_str("; ");
        }

        // Float
        if self.float != default.float {
            buf.push_str("float: ");
            self.float.to_css(buf);
            buf.push_str("; ");
        }

        // Break before
        if self.break_before != default.break_before {
            buf.push_str("break-before: ");
            self.break_before.to_css(buf);
            buf.push_str("; ");
        }

        // Break after
        if self.break_after != default.break_after {
            buf.push_str("break-after: ");
            self.break_after.to_css(buf);
            buf.push_str("; ");
        }

        // Break inside
        if self.break_inside != default.break_inside {
            buf.push_str("break-inside: ");
            self.break_inside.to_css(buf);
            buf.push_str("; ");
        }

        // Border styles
        if self.border_style_top != default.border_style_top {
            buf.push_str("border-top-style: ");
            self.border_style_top.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_style_right != default.border_style_right {
            buf.push_str("border-right-style: ");
            self.border_style_right.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_style_bottom != default.border_style_bottom {
            buf.push_str("border-bottom-style: ");
            self.border_style_bottom.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_style_left != default.border_style_left {
            buf.push_str("border-left-style: ");
            self.border_style_left.to_css(buf);
            buf.push_str("; ");
        }

        // Border widths
        if self.border_width_top != default.border_width_top {
            buf.push_str("border-top-width: ");
            self.border_width_top.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_width_right != default.border_width_right {
            buf.push_str("border-right-width: ");
            self.border_width_right.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_width_bottom != default.border_width_bottom {
            buf.push_str("border-bottom-width: ");
            self.border_width_bottom.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_width_left != default.border_width_left {
            buf.push_str("border-left-width: ");
            self.border_width_left.to_css(buf);
            buf.push_str("; ");
        }

        // Border colors
        if let Some(color) = self.border_color_top {
            buf.push_str("border-top-color: ");
            color.to_css(buf);
            buf.push_str("; ");
        }
        if let Some(color) = self.border_color_right {
            buf.push_str("border-right-color: ");
            color.to_css(buf);
            buf.push_str("; ");
        }
        if let Some(color) = self.border_color_bottom {
            buf.push_str("border-bottom-color: ");
            color.to_css(buf);
            buf.push_str("; ");
        }
        if let Some(color) = self.border_color_left {
            buf.push_str("border-left-color: ");
            color.to_css(buf);
            buf.push_str("; ");
        }

        // Border radius
        if self.border_radius_top_left != default.border_radius_top_left {
            buf.push_str("border-top-left-radius: ");
            self.border_radius_top_left.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_radius_top_right != default.border_radius_top_right {
            buf.push_str("border-top-right-radius: ");
            self.border_radius_top_right.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_radius_bottom_left != default.border_radius_bottom_left {
            buf.push_str("border-bottom-left-radius: ");
            self.border_radius_bottom_left.to_css(buf);
            buf.push_str("; ");
        }
        if self.border_radius_bottom_right != default.border_radius_bottom_right {
            buf.push_str("border-bottom-right-radius: ");
            self.border_radius_bottom_right.to_css(buf);
            buf.push_str("; ");
        }

        // List style position
        if self.list_style_position != default.list_style_position {
            buf.push_str("list-style-position: ");
            self.list_style_position.to_css(buf);
            buf.push_str("; ");
        }

        // Visibility
        if self.visibility != default.visibility {
            buf.push_str("visibility: ");
            self.visibility.to_css(buf);
            buf.push_str("; ");
        }

        // Language (output as data attribute comment - not standard CSS)
        // Note: language is stored but typically output via HTML lang attribute
    }
}

/// SoA style pool for efficient storage and deduplication.
///
/// Styles are interned: identical styles share the same StyleId.
/// This is memory-efficient when many elements share the same style.
#[derive(Clone)]
pub struct StylePool {
    /// All unique styles.
    styles: Vec<ComputedStyle>,
    /// Hash-based deduplication map.
    intern_map: HashMap<ComputedStyle, StyleId>,
}

impl Default for StylePool {
    fn default() -> Self {
        Self::new()
    }
}

impl StylePool {
    /// Create a new style pool with the default style at index 0.
    pub fn new() -> Self {
        let default_style = ComputedStyle::default();
        let mut intern_map = HashMap::new();
        intern_map.insert(default_style.clone(), StyleId::DEFAULT);

        Self {
            styles: vec![default_style],
            intern_map,
        }
    }

    /// Intern a style, returning its StyleId.
    ///
    /// If an identical style already exists, returns the existing ID.
    /// Otherwise, allocates a new style and returns its ID.
    pub fn intern(&mut self, style: ComputedStyle) -> StyleId {
        if let Some(&id) = self.intern_map.get(&style) {
            return id;
        }

        let id = StyleId(self.styles.len() as u32);
        self.intern_map.insert(style.clone(), id);
        self.styles.push(style);
        id
    }

    /// Get a style by ID.
    pub fn get(&self, id: StyleId) -> Option<&ComputedStyle> {
        self.styles.get(id.0 as usize)
    }

    /// Get the number of unique styles.
    pub fn len(&self) -> usize {
        self.styles.len()
    }

    /// Check if the pool is empty (should never be, as default style is always present).
    pub fn is_empty(&self) -> bool {
        self.styles.is_empty()
    }

    /// Iterate over all (StyleId, ComputedStyle) pairs.
    pub fn iter(&self) -> impl Iterator<Item = (StyleId, &ComputedStyle)> {
        self.styles
            .iter()
            .enumerate()
            .map(|(i, s)| (StyleId(i as u32), s))
    }
}

impl std::fmt::Debug for StylePool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StylePool")
            .field("count", &self.styles.len())
            .finish()
    }
}

#[cfg(test)]
#[allow(clippy::field_reassign_with_default)]
mod tests {
    use super::*;

    #[test]
    fn test_color_to_css_opaque() {
        assert_eq!(Color::BLACK.to_css_string(), "#000000");
        assert_eq!(Color::WHITE.to_css_string(), "#ffffff");
        assert_eq!(Color::rgb(255, 0, 0).to_css_string(), "#ff0000");
        assert_eq!(Color::rgb(0, 128, 255).to_css_string(), "#0080ff");
    }

    #[test]
    fn test_color_to_css_transparent() {
        assert_eq!(Color::TRANSPARENT.to_css_string(), "transparent");
    }

    #[test]
    fn test_color_to_css_alpha() {
        let color = Color::rgba(255, 0, 0, 128);
        let css = color.to_css_string();
        assert!(css.starts_with("rgba(255,0,0,"));
        assert!(css.contains("0.50")); // ~128/255
    }

    #[test]
    fn test_length_to_css() {
        assert_eq!(Length::Auto.to_css_string(), "auto");
        assert_eq!(Length::Px(0.0).to_css_string(), "0");
        assert_eq!(Length::Px(16.0).to_css_string(), "16px");
        assert_eq!(Length::Em(1.5).to_css_string(), "1.5em");
        assert_eq!(Length::Rem(2.0).to_css_string(), "2rem");
        assert_eq!(Length::Percent(50.0).to_css_string(), "50%");
    }

    #[test]
    fn test_font_weight_to_css() {
        assert_eq!(FontWeight::NORMAL.to_css_string(), "normal");
        assert_eq!(FontWeight::BOLD.to_css_string(), "bold");
        assert_eq!(FontWeight(300).to_css_string(), "300");
        assert_eq!(FontWeight(600).to_css_string(), "600");
    }

    #[test]
    fn test_font_style_to_css() {
        assert_eq!(FontStyle::Normal.to_css_string(), "normal");
        assert_eq!(FontStyle::Italic.to_css_string(), "italic");
        assert_eq!(FontStyle::Oblique.to_css_string(), "oblique");
    }

    #[test]
    fn test_text_align_to_css() {
        assert_eq!(TextAlign::Left.to_css_string(), "left");
        assert_eq!(TextAlign::Center.to_css_string(), "center");
        assert_eq!(TextAlign::Justify.to_css_string(), "justify");
    }

    #[test]
    fn test_display_to_css() {
        assert_eq!(Display::Block.to_css_string(), "block");
        assert_eq!(Display::Inline.to_css_string(), "inline");
        assert_eq!(Display::None.to_css_string(), "none");
    }

    #[test]
    fn test_computed_style_to_css_default() {
        let style = ComputedStyle::default();
        // Default style should produce empty CSS (no non-default properties)
        assert_eq!(style.to_css_string(), "");
    }

    #[test]
    fn test_computed_style_to_css_bold() {
        let mut style = ComputedStyle::default();
        style.font_weight = FontWeight::BOLD;
        let css = style.to_css_string();
        assert!(css.contains("font-weight: bold;"));
    }

    #[test]
    fn test_computed_style_to_css_multiple() {
        let mut style = ComputedStyle::default();
        style.font_weight = FontWeight::BOLD;
        style.font_style = FontStyle::Italic;
        style.color = Some(Color::rgb(255, 0, 0));
        style.text_align = TextAlign::Center;

        let css = style.to_css_string();
        assert!(css.contains("font-weight: bold;"));
        assert!(css.contains("font-style: italic;"));
        assert!(css.contains("color: #ff0000;"));
        assert!(css.contains("text-align: center;"));
    }

    #[test]
    fn test_computed_style_to_css_decorations() {
        let mut style = ComputedStyle::default();
        style.text_decoration_underline = true;
        style.text_decoration_line_through = true;

        let css = style.to_css_string();
        assert!(css.contains("text-decoration: underline line-through;"));
    }

    #[test]
    fn test_style_pool_interning() {
        let mut pool = StylePool::new();

        let mut style1 = ComputedStyle::default();
        style1.font_weight = FontWeight::BOLD;

        let id1 = pool.intern(style1.clone());
        let id2 = pool.intern(style1);

        // Same style should get same ID
        assert_eq!(id1, id2);
        assert_eq!(pool.len(), 2); // default + bold
    }

    #[test]
    fn test_style_pool_iter() {
        let mut pool = StylePool::new();

        let mut style = ComputedStyle::default();
        style.font_weight = FontWeight::BOLD;
        pool.intern(style);

        let ids: Vec<StyleId> = pool.iter().map(|(id, _)| id).collect();
        assert_eq!(ids, vec![StyleId(0), StyleId(1)]);
    }
}