docx_rust/document/
table_cell.rs

1#![allow(unused_must_use)]
2use std::borrow::{Borrow, Cow};
3
4use derive_more::From;
5use hard_xml::{XmlRead, XmlWrite};
6
7use crate::{__setter, __xml_test_suites, document::Paragraph, formatting::TableCellProperty};
8
9/// Table Cell
10///
11/// ```rust
12/// use docx_rust::document::*;
13/// use docx_rust::formatting::*;
14///
15/// let cell = TableCell::from(Paragraph::default());
16///
17/// let cell = TableCell::paragraph(Paragraph::default())
18///     .property(TableCellProperty::default());
19/// ```
20#[derive(Debug, Default, XmlRead, XmlWrite, Clone)]
21#[cfg_attr(test, derive(PartialEq))]
22#[xml(tag = "w:tc")]
23pub struct TableCell<'a> {
24    #[xml(default, child = "w:tcPr")]
25    pub property: TableCellProperty,
26    #[xml(child = "w:p")]
27    pub content: Vec<TableCellContent<'a>>,
28}
29
30impl<'a> TableCell<'a> {
31    __setter!(property: TableCellProperty);
32
33    pub fn paragraph<T: Into<Paragraph<'a>>>(par: T) -> Self {
34        TableCell {
35            property: TableCellProperty::default(),
36            content: vec![TableCellContent::Paragraph(par.into())],
37        }
38    }
39
40    pub fn iter_text(&self) -> impl Iterator<Item = &Cow<'a, str>> {
41        self.content
42            .iter()
43            .filter_map(|content| match content {
44                TableCellContent::Paragraph(p) => Some(p.iter_text()),
45            })
46            .flatten()
47    }
48
49    pub fn iter_text_mut(&mut self) -> impl Iterator<Item = &mut Cow<'a, str>> {
50        self.content
51            .iter_mut()
52            .filter_map(|content| match content {
53                TableCellContent::Paragraph(p) => Some(p.iter_text_mut()),
54            })
55            .flatten()
56    }
57
58    pub fn replace_text<'b, I, T, S>(&mut self, dic: T) -> crate::DocxResult<()>
59    where
60        S: AsRef<str> + 'b,
61        T: IntoIterator<Item = I> + Copy,
62        I: Borrow<(S, S)>,
63    {
64        for content in self.content.iter_mut() {
65            match content {
66                TableCellContent::Paragraph(p) => p.replace_text(dic)?,
67            }
68        }
69        Ok(())
70    }
71}
72
73impl<'a, T: Into<TableCellContent<'a>>> From<T> for TableCell<'a> {
74    fn from(content: T) -> Self {
75        TableCell {
76            property: TableCellProperty::default(),
77            content: vec![content.into()],
78        }
79    }
80}
81
82#[derive(Debug, From, XmlRead, XmlWrite, Clone)]
83#[cfg_attr(test, derive(PartialEq))]
84pub enum TableCellContent<'a> {
85    #[xml(tag = "w:p")]
86    Paragraph(Paragraph<'a>),
87    // #[xml(tag = "w:tbl")]
88    // Table(Table<'a>),
89}
90
91__xml_test_suites!(
92    TableCell,
93    TableCell::paragraph(Paragraph::default()),
94    r#"<w:tc><w:tcPr><w:vAlign w:val="top"/></w:tcPr><w:p/></w:tc>"#,
95);