docxcraft 0.1.0

Generate editable DOCX documents with rich text, tables, charts and SVG drawings
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
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 ALGFORCE INC.

use scraper::{Html, Selector};

use crate::get_font_for_locale;

#[derive(Debug, Clone)]
pub struct HtmlParagraph {
    pub content: String,
    pub locale: String,
    pub max_font_size: Option<u32>,
    pub font_family: Option<String>,
    pub font_size: Option<u32>,
    pub font_weight: Option<u16>,
    pub color: Option<String>,
}

/// HTML 到 Word 段落的转换器
/// 将富文本 HTML 转换为符合 OpenXML 标准的 Word 段落
pub struct HtmlToParagraph {
    /// 默认字体
    pub default_font: String,
    /// 默认字体大小(半点,docx 标准)
    pub default_font_size: u32,
    /// 可选的字号上限(半点)
    pub max_font_size: Option<u32>,
    pub default_font_weight: u16,
    pub default_color: Option<String>,
}

impl Default for HtmlToParagraph {
    fn default() -> Self {
        Self {
            default_font: "Arial".to_owned(),
            default_font_size: 22, // 11pt = 22 半点
            max_font_size: None,
            default_font_weight: 400,
            default_color: None,
        }
    }
}

/// 文本样式
#[derive(Debug, Clone)]
struct TextStyle {
    bold: bool,
    italic: bool,
    underline: bool,
    strike: bool,
    color: Option<String>,
    background_color: Option<String>,
    font_size: u32, // 半点单位
    font_family: String,
}

impl TextStyle {
    fn new(font_family: String, font_size: u32) -> Self {
        Self {
            bold: false,
            italic: false,
            underline: false,
            strike: false,
            color: None,
            background_color: None,
            font_size,
            font_family,
        }
    }
}

/// 段落对齐方式
#[derive(Debug, Clone, Copy)]
enum TextAlign {
    Left,
    Center,
    Right,
    Justify,
}

impl TextAlign {
    fn to_docx(&self) -> &'static str {
        match self {
            TextAlign::Left => "left",
            TextAlign::Center => "center",
            TextAlign::Right => "right",
            TextAlign::Justify => "both",
        }
    }
}

impl Default for TextAlign {
    fn default() -> Self {
        TextAlign::Left
    }
}

/// 文本块(一个具有相同样式的文本片段)
#[derive(Debug, Clone)]
struct TextRun {
    text: String,
    style: TextStyle,
}

/// 段落
#[derive(Debug)]
struct Paragraph {
    runs: Vec<TextRun>,
    align: TextAlign,
    is_heading: bool,
    heading_level: u8,
    is_list_item: bool,
    list_type: ListType,
    list_index: Option<usize>,
}

/// 列表类型
#[derive(Debug, Clone, Copy, PartialEq)]
enum ListType {
    None,
    Ordered,   // 有序列表
    Unordered, // 无序列表
}

impl HtmlToParagraph {
    fn initial_style(&self, font_size: u32) -> TextStyle {
        let mut style = TextStyle::new(self.default_font.clone(), font_size);
        style.bold = self.default_font_weight >= 700;
        style.color = self.default_color.clone();
        style
    }

    /// 创建新的转换器实例
    pub fn new() -> Self {
        Self::default()
    }

    /// 根据 locale 设置默认字体
    ///
    /// # 参数
    /// - locale: 语言代码
    ///
    /// # 示例
    /// ```
    /// use docxcraft::html_paragraph::HtmlToParagraph;
    ///
    /// let converter = HtmlToParagraph::new().with_locale("zh".to_string());
    /// ```
    pub fn with_locale(mut self, locale: String) -> Self {
        self.default_font = get_font_for_locale(&locale);
        self
    }

    /// 设置默认字体
    pub fn with_font(mut self, font: String) -> Self {
        self.default_font = font;
        self
    }

    /// 设置默认字体大小(半点单位)
    pub fn with_font_size(mut self, size: u32) -> Self {
        self.default_font_size = size;
        self
    }

    pub fn with_font_weight(mut self, weight: u16) -> Self {
        self.default_font_weight = weight;
        self
    }

    pub fn with_color(mut self, color: String) -> Self {
        self.default_color = Some(color.trim_start_matches('#').to_string());
        self
    }

    /// 设置最大字体大小(半点单位)
    pub fn with_max_font_size(mut self, size: u32) -> Self {
        self.max_font_size = Some(size);
        self
    }

    /// 将 HTML 转换为 Word 段落 XML
    pub fn convert(&self, html: &str) -> String {
        println!("{}", html);
        // 检查是否是纯文本(没有 HTML 标签)
        let trimmed = html.trim();
        // 检查是否需要包装在 <p> 标签中
        let needs_wrapping = if trimmed.is_empty() {
            false
        } else if !trimmed.starts_with('<') {
            // 纯文本,需要包装
            true
        } else {
            // 以标签开头,检查是否是块级段落/标题/列表标签
            let block_tags = ["<p", "<h1", "<h2", "<h3", "<h4", "<h5", "<h6", "<ul", "<ol"];
            !block_tags.iter().any(|tag| {
                trimmed.starts_with(tag)
                    && (trimmed[tag.len()..].starts_with('>')
                        || trimmed[tag.len()..].starts_with(' '))
            })
        };

        let html_to_parse = if needs_wrapping {
            // 如果是纯文本或内联标签,自动包装在 <p> 标签中
            format!("<p>{}</p>", html)
        } else {
            html.to_string()
        };

        let document = Html::parse_document(&html_to_parse);
        let paragraphs = self.parse_html(&document);
        self.generate_docx_xml(&paragraphs)
    }

    /// 解析 HTML 文档
    fn parse_html(&self, document: &Html) -> Vec<Paragraph> {
        let mut paragraphs = Vec::new();

        // 选择 body 元素,如果没有则使用根元素
        let body_selector = Selector::parse("body").unwrap();
        let root = if let Some(body) = document.select(&body_selector).next() {
            body
        } else {
            // 如果没有 body,使用 html 根元素
            let html_selector = Selector::parse("html").unwrap();
            if let Some(html) = document.select(&html_selector).next() {
                html
            } else {
                // 如果连 html 标签都没有,直接返回空列表
                return paragraphs;
            }
        };

        // 按 DOM 顺序遍历直接子元素
        for child in root.children() {
            if let Some(element) = scraper::ElementRef::wrap(child) {
                match element.value().name() {
                    "p" => {
                        let paragraph = self.parse_paragraph(element, false, 0);
                        paragraphs.push(paragraph);
                    }
                    "h1" => {
                        let paragraph = self.parse_paragraph(element, true, 1);
                        paragraphs.push(paragraph);
                    }
                    "h2" => {
                        let paragraph = self.parse_paragraph(element, true, 2);
                        paragraphs.push(paragraph);
                    }
                    "h3" => {
                        let paragraph = self.parse_paragraph(element, true, 3);
                        paragraphs.push(paragraph);
                    }
                    "h4" => {
                        let paragraph = self.parse_paragraph(element, true, 4);
                        paragraphs.push(paragraph);
                    }
                    "h5" => {
                        let paragraph = self.parse_paragraph(element, true, 5);
                        paragraphs.push(paragraph);
                    }
                    "h6" => {
                        let paragraph = self.parse_paragraph(element, true, 6);
                        paragraphs.push(paragraph);
                    }
                    "ol" => {
                        let list_paragraphs = self.parse_list(element, ListType::Ordered);
                        paragraphs.extend(list_paragraphs);
                    }
                    "ul" => {
                        let list_paragraphs = self.parse_list(element, ListType::Unordered);
                        paragraphs.extend(list_paragraphs);
                    }
                    _ => {}
                }
            }
            // 处理文本节点
            else if let scraper::Node::Text(text) = child.value() {
                let text_content = text.to_string();
                if !text_content.trim().is_empty() {
                    // 将裸文本包装成一个段落
                    let initial_style = self.initial_style(self.default_font_size);
                    let runs = vec![TextRun {
                        text: text_content,
                        style: initial_style,
                    }];

                    paragraphs.push(Paragraph {
                        runs,
                        align: TextAlign::Left,
                        is_heading: false,
                        heading_level: 0,
                        is_list_item: false,
                        list_type: ListType::None,
                        list_index: None,
                    });
                }
            }
        }

        paragraphs
    }

    /// 解析列表(有序或无序)
    fn parse_list(&self, list_element: scraper::ElementRef, list_type: ListType) -> Vec<Paragraph> {
        let mut paragraphs = Vec::new();
        let li_selector = Selector::parse("li").unwrap();
        let mut actual_index = 0; // 实际的编号索引(跳过空项后)

        for li_element in list_element.select(&li_selector) {
            let mut runs = Vec::new();
            let initial_style = self.initial_style(self.default_font_size);

            // 不添加列表标记文本,使用 OpenXML 原生列表格式
            // 解析列表项内容
            self.parse_node_content(li_element, &mut runs, initial_style);

            // 只有当列表项有实际内容时才添加段落
            // 过滤掉空的列表项(没有runs或所有runs都是空白)
            let has_content = runs.iter().any(|run| !run.text.trim().is_empty());

            if has_content {
                paragraphs.push(Paragraph {
                    runs,
                    align: TextAlign::Left,
                    is_heading: false,
                    heading_level: 0,
                    is_list_item: true,
                    list_type,
                    list_index: Some(actual_index),
                });
                actual_index += 1; // 只在添加段落时增加索引
            }
        }

        paragraphs
    }

    /// 解析单个段落
    fn parse_paragraph(
        &self,
        element: scraper::ElementRef,
        is_heading: bool,
        heading_level: u8,
    ) -> Paragraph {
        let mut runs = Vec::new();
        let mut align = TextAlign::Left;

        // 检查对齐方式
        if let Some(style) = element.value().attr("style") {
            align = self.parse_text_align(style);
        }

        // 检查 class 属性中的对齐方式
        if let Some(class) = element.value().attr("class") {
            if class.contains("text-center") {
                align = TextAlign::Center;
            } else if class.contains("text-right") {
                align = TextAlign::Right;
            } else if class.contains("text-justify") {
                align = TextAlign::Justify;
            }
        }

        // 计算字体大小(半点单位)
        let font_size = if is_heading {
            match heading_level {
                1 => self.default_font_size * 2,       // h1: 约 32pt
                2 => (self.default_font_size * 3) / 2, // h2: 约 24pt
                3 => (self.default_font_size * 5) / 4, // h3: 约 18pt
                4 => self.default_font_size,           // h4: 约 16pt
                5 => (self.default_font_size * 7) / 8, // h5: 约 14pt
                6 => (self.default_font_size * 3) / 4, // h6: 约 12pt
                _ => self.default_font_size,
            }
        } else {
            // 检查 class 属性中的字体大小
            if let Some(class) = element.value().attr("class") {
                self.parse_font_size_from_class(class)
            } else {
                self.default_font_size
            }
        };
        let font_size = self.clamp_font_size(font_size);

        // 解析文本内容
        let initial_style = self.initial_style(font_size);
        self.parse_node_content(element, &mut runs, initial_style);

        Paragraph {
            runs,
            align,
            is_heading,
            heading_level,
            is_list_item: false,
            list_type: ListType::None,
            list_index: None,
        }
    }

    /// 从 style 属性中解析对齐方式
    fn parse_text_align(&self, style: &str) -> TextAlign {
        if style.contains("text-align: center") || style.contains("text-align:center") {
            TextAlign::Center
        } else if style.contains("text-align: right") || style.contains("text-align:right") {
            TextAlign::Right
        } else if style.contains("text-align: justify") || style.contains("text-align:justify") {
            TextAlign::Justify
        } else {
            TextAlign::Left
        }
    }

    /// 从 class 属性中解析字体大小
    fn parse_font_size_from_class(&self, class: &str) -> u32 {
        // 基于 TipTap 常用的字体大小类名
        let size = if class.contains("text-xs") {
            (self.default_font_size * 7) / 8 // 小号
        } else if class.contains("text-sm") {
            self.default_font_size // 较小
        } else if class.contains("text-base") {
            self.default_font_size // 标准
        } else if class.contains("text-lg") {
            (self.default_font_size * 5) / 4 // 大号
        } else if class.contains("text-xl") {
            (self.default_font_size * 3) / 2 // 特大
        } else if class.contains("text-2xl") {
            self.default_font_size * 2 // 2倍大
        } else if class.contains("text-3xl") {
            (self.default_font_size * 5) / 2 // 3倍大
        } else if class.contains("text-4xl") {
            self.default_font_size * 3 // 4倍大
        } else {
            self.default_font_size
        };
        self.clamp_font_size(size)
    }

    /// 递归解析节点内容
    fn parse_node_content(
        &self,
        element: scraper::ElementRef,
        runs: &mut Vec<TextRun>,
        parent_style: TextStyle,
    ) {
        for node in element.children() {
            match node.value() {
                scraper::Node::Text(text) => {
                    let text_content = text.to_string();
                    // HTML 空白折叠:将换行/制表/连续空格合并为单个空格,保留首尾空格(维持行内元素间词间距)
                    let normalized = Self::normalize_whitespace(&text_content);
                    if !normalized.is_empty() {
                        runs.push(TextRun {
                            text: normalized,
                            style: parent_style.clone(),
                        });
                    }
                }
                scraper::Node::Element(elem) => {
                    let child_element = scraper::ElementRef::wrap(node).unwrap();
                    let mut new_style = parent_style.clone();

                    // 根据标签更新样式
                    match elem.name() {
                        "strong" | "b" => new_style.bold = true,
                        "em" | "i" => new_style.italic = true,
                        "u" => new_style.underline = true,
                        "s" | "strike" | "del" => new_style.strike = true,
                        "span" => {
                            // 处理 span 的 style 属性
                            if let Some(style) = elem.attr("style") {
                                self.parse_inline_style(style, &mut new_style);
                            }
                        }
                        "mark" => {
                            // mark 标签用于背景色高亮
                            if let Some(style) = elem.attr("style") {
                                self.parse_inline_style(style, &mut new_style);
                            }
                            // 如果 style 属性中没有指定背景色,使用默认黄色
                            if new_style.background_color.is_none() {
                                if let Some(data_color) = elem.attr("data-color") {
                                    new_style.background_color = Some(data_color.to_string());
                                } else {
                                    new_style.background_color = Some("FFFF00".to_string());
                                }
                            }
                        }
                        "br" => {
                            // 换行符,在 docx 中用 <w:br/> 表示
                            runs.push(TextRun {
                                text: "\n".to_string(),
                                style: parent_style.clone(),
                            });
                            continue;
                        }
                        _ => {}
                    }

                    // 递归处理子节点
                    self.parse_node_content(child_element, runs, new_style);
                }
                _ => {}
            }
        }
    }

    /// 解析内联样式
    fn parse_inline_style(&self, style: &str, text_style: &mut TextStyle) {
        // 解析 background-color
        if let Some(bg_start) = style.find("background-color:") {
            let bg_str = &style[bg_start + 17..];
            if let Some(bg_end) = bg_str.find(';').or_else(|| Some(bg_str.len())) {
                let bg_color = bg_str[..bg_end].trim();
                text_style.background_color = Some(self.parse_color(bg_color));
            }
        }

        // 解析 color(但要排除 background-color)
        for (i, _) in style.match_indices("color:") {
            let is_background_color = if i >= 11 {
                &style[i - 11..i] == "background-"
            } else {
                false
            };

            if !is_background_color {
                let color_str = &style[i + 6..];
                if let Some(color_end) = color_str.find(';').or_else(|| Some(color_str.len())) {
                    let color = color_str[..color_end].trim();
                    if color != "inherit" {
                        text_style.color = Some(self.parse_color(color));
                    }
                }
                break;
            }
        }

        // 解析 font-size
        if let Some(size_start) = style.find("font-size:") {
            let size_str = &style[size_start + 10..];
            if let Some(size_end) = size_str.find(';').or_else(|| Some(size_str.len())) {
                let size = size_str[..size_end].trim();
                if let Some(parsed_size) = self.parse_font_size(size) {
                    text_style.font_size = self.clamp_font_size(parsed_size);
                }
            }
        }
    }

    /// 解析颜色值,转换为 docx 格式(6位十六进制)
    fn parse_color(&self, color: &str) -> String {
        let color = color.trim();

        // 移除 # 号
        if color.starts_with('#') {
            let hex = &color[1..];
            // 确保是 6 位十六进制
            if hex.len() == 6 {
                return hex.to_uppercase();
            } else if hex.len() == 3 {
                // 3位缩写,转换为6位
                let r = &hex[0..1];
                let g = &hex[1..2];
                let b = &hex[2..3];
                return format!("{}{}{}{}{}{}", r, r, g, g, b, b).to_uppercase();
            }
        }

        // 处理 rgb(r, g, b) 格式
        if color.starts_with("rgb(") && color.ends_with(')') {
            let rgb = &color[4..color.len() - 1];
            let parts: Vec<&str> = rgb.split(',').collect();
            if parts.len() == 3 {
                let r = parts[0].trim().parse::<u8>().unwrap_or(0);
                let g = parts[1].trim().parse::<u8>().unwrap_or(0);
                let b = parts[2].trim().parse::<u8>().unwrap_or(0);
                return format!("{:02X}{:02X}{:02X}", r, g, b);
            }
        }

        // 默认黑色
        "000000".to_string()
    }

    /// 解析字体大小,转换为半点单位
    fn parse_font_size(&self, size: &str) -> Option<u32> {
        let size = size.trim();

        if size.ends_with("px") {
            // 像素转换为点:1pt = 1.333px
            let px = size[..size.len() - 2].parse::<f64>().ok()?;
            let pt = px / 1.333;
            Some((pt * 2.0) as u32) // 转换为半点
        } else if size.ends_with("pt") {
            // 点直接转换
            let pt = size[..size.len() - 2].parse::<f64>().ok()?;
            Some((pt * 2.0) as u32)
        } else {
            None
        }
    }

    fn clamp_font_size(&self, size: u32) -> u32 {
        self.max_font_size.map(|max| size.min(max)).unwrap_or(size)
    }

    /// 生成 docx XML
    fn generate_docx_xml(&self, paragraphs: &[Paragraph]) -> String {
        let mut xml = String::new();

        for paragraph in paragraphs {
            xml.push_str(&self.generate_paragraph_xml(paragraph));
        }

        xml
    }

    /// 生成单个段落的 XML
    fn generate_paragraph_xml(&self, paragraph: &Paragraph) -> String {
        let mut xml = String::new();

        xml.push_str("<w:p>");

        // 生成段落属性
        let has_list = paragraph.is_list_item && paragraph.list_type != ListType::None;
        let has_align = paragraph.align as u8 != TextAlign::Left as u8;
        let has_heading = paragraph.is_heading;

        if has_list || has_align || has_heading {
            xml.push_str("<w:pPr>");

            // 标题样式
            if has_heading {
                xml.push_str(&format!(
                    r#"<w:pStyle w:val="Heading{}"/>"#,
                    paragraph.heading_level
                ));
            }

            // 列表编号
            if has_list {
                // 使用编号样式
                // numId 1 用于有序列表, numId 2 用于无序列表
                let num_id = match paragraph.list_type {
                    ListType::Ordered => 1,
                    ListType::Unordered => 2,
                    ListType::None => 0,
                };
                xml.push_str(&format!(
                    r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="{}"/></w:numPr>"#,
                    num_id
                ));
            }

            // 对齐方式
            if has_align {
                xml.push_str(&format!(r#"<w:jc w:val="{}"/>"#, paragraph.align.to_docx()));
            }

            xml.push_str("</w:pPr>");
        }

        // 生成文本运行
        for run in &paragraph.runs {
            xml.push_str(&self.generate_run_xml(run));
        }

        xml.push_str("</w:p>");
        xml
    }

    /// 生成单个 run 的 XML
    fn generate_run_xml(&self, run: &TextRun) -> String {
        let mut xml = String::new();

        // 处理换行符
        if run.text == "\n" {
            return "<w:r><w:br/></w:r>".to_string();
        }

        xml.push_str("<w:r>");

        // 生成 run 属性(始终生成,因为至少需要字体和字体大小)
        xml.push_str("<w:rPr>");

        // 字体
        xml.push_str(&format!(
            r#"<w:rFonts w:ascii="{}" w:hAnsi="{}" w:eastAsia="{}"/>"#,
            run.style.font_family, run.style.font_family, run.style.font_family
        ));

        // 字体大小
        xml.push_str(&format!(r#"<w:sz w:val="{}"/>"#, run.style.font_size));
        xml.push_str(&format!(r#"<w:szCs w:val="{}"/>"#, run.style.font_size));

        // 加粗
        if run.style.bold {
            xml.push_str("<w:b/>");
        }

        // 斜体
        if run.style.italic {
            xml.push_str("<w:i/>");
        }

        // 下划线
        if run.style.underline {
            xml.push_str(r#"<w:u w:val="single"/>"#);
        }

        // 删除线
        if run.style.strike {
            xml.push_str("<w:strike/>");
        }

        // 文字颜色
        if let Some(color) = &run.style.color {
            xml.push_str(&format!(r#"<w:color w:val="{}"/>"#, color));
        }

        // 背景色(高亮)
        if let Some(bg_color) = &run.style.background_color {
            xml.push_str(&format!(
                r#"<w:highlight w:val="{}"/>"#,
                self.map_highlight_color(bg_color)
            ));
        }

        xml.push_str("</w:rPr>");

        // 文本内容(xml:space="preserve" 防止 Word 自动吃掉首尾空格)
        xml.push_str(&format!(
            r#"<w:t xml:space="preserve">{}</w:t>"#,
            self.escape_xml(&run.text)
        ));

        xml.push_str("</w:r>");
        xml
    }

    /// 映射背景色到 docx 支持的高亮颜色
    /// docx 只支持有限的几种高亮颜色
    fn map_highlight_color(&self, color: &str) -> &'static str {
        let color_upper = color.to_uppercase();
        match color_upper.as_str() {
            "FFFF00" | "YELLOW" => "yellow",
            "00FF00" | "GREEN" => "green",
            "00FFFF" | "CYAN" => "cyan",
            "FF00FF" | "MAGENTA" => "magenta",
            "0000FF" | "BLUE" => "blue",
            "FF0000" | "RED" => "red",
            "000000" | "BLACK" => "black",
            "808080" | "GRAY" => "darkGray",
            "C0C0C0" | "LIGHTGRAY" => "lightGray",
            _ => "yellow", // 默认黄色
        }
    }

    /// HTML 空白折叠:将所有空白字符(换行、制表、多个空格)压缩为单个空格,
    /// 但保留首尾各一个空格,以维持行内元素(如 <strong>、<em>)两侧的词间距。
    fn normalize_whitespace(text: &str) -> String {
        let has_leading_space = text.starts_with(|c: char| c.is_whitespace());
        let has_trailing_space = text.ends_with(|c: char| c.is_whitespace());

        let words: Vec<&str> = text.split_whitespace().collect();
        if words.is_empty() {
            return String::new();
        }

        let mut result = words.join(" ");
        if has_leading_space {
            result.insert(0, ' ');
        }
        if has_trailing_space {
            result.push(' ');
        }
        result
    }

    /// 转义 XML 特殊字符
    fn escape_xml(&self, text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
            .replace('\'', "&apos;")
    }
}

/// 便捷函数:将 HTML 转换为 Word 段落 XML
///
/// # 参数
/// - html: HTML 字符串
///
/// # 返回
/// docx 段落 XML 字符串
pub fn convert(html: &str) -> String {
    let converter = HtmlToParagraph::new();
    converter.convert(html)
}

/// 便捷函数:将 HTML 转换为 Word 段落 XML,使用自定义字体
///
/// # 参数
/// - html: HTML 字符串
/// - font: 字体名称
/// - font_size: 字体大小(半点单位)
///
/// # 返回
/// docx 段落 XML 字符串
pub fn convert_with_font(html: &str, font: String, font_size: u32) -> String {
    let converter = HtmlToParagraph::new()
        .with_font(font)
        .with_font_size(font_size);
    converter.convert(html)
}