docx-rs/docx-core/src/documents/elements/table_cell.rs

79 lines
1.9 KiB
Rust
Raw Normal View History

2019-11-12 12:11:58 +02:00
use super::{Paragraph, TableCellProperty};
2019-11-12 11:57:16 +02:00
use crate::documents::BuildXML;
2019-11-13 08:00:53 +02:00
use crate::types::*;
2019-11-12 11:57:16 +02:00
use crate::xml_builder::*;
#[derive(Debug, Clone)]
pub struct TableCell {
property: TableCellProperty,
contents: Vec<TableCellContent>,
}
#[derive(Debug, Clone)]
pub enum TableCellContent {
Paragraph(Paragraph),
}
impl TableCell {
2019-11-12 12:11:58 +02:00
pub fn new() -> TableCell {
let property = TableCellProperty::new();
2019-11-12 11:57:16 +02:00
let contents = vec![];
Self { property, contents }
}
pub fn add_paragraph(mut self, p: Paragraph) -> TableCell {
self.contents.push(TableCellContent::Paragraph(p));
self
}
2019-11-13 08:00:53 +02:00
pub fn vertical_merge(mut self, t: VMergeType) -> TableCell {
self.property = self.property.vertical_merge(t);
self
}
pub fn grid_span(mut self, v: usize) -> TableCell {
self.property = self.property.grid_span(v);
self
}
2019-11-12 11:57:16 +02:00
}
impl BuildXML for TableCell {
fn build(&self) -> Vec<u8> {
let b = XMLBuilder::new();
let mut b = b.open_table_cell().add_child(&self.property);
for c in &self.contents {
match c {
TableCellContent::Paragraph(p) => b = b.add_child(p),
}
}
b.close().build()
}
}
#[cfg(test)]
mod tests {
2019-11-12 12:11:58 +02:00
use super::super::*;
2019-11-12 11:57:16 +02:00
use super::*;
#[cfg(test)]
use pretty_assertions::assert_eq;
use std::str;
#[test]
fn test_cell() {
2019-11-12 12:11:58 +02:00
let b = TableCell::new().build();
2019-11-13 06:55:58 +02:00
assert_eq!(str::from_utf8(&b).unwrap(), r#"<w:tc><w:tcPr /></w:tc>"#);
2019-11-12 11:57:16 +02:00
}
#[test]
fn test_cell_add_p() {
2019-11-12 12:11:58 +02:00
let b = TableCell::new()
2019-11-13 09:51:58 +02:00
.add_paragraph(Paragraph::new().add_run(Run::new().add_text("Hello")))
2019-11-12 11:57:16 +02:00
.build();
assert_eq!(
str::from_utf8(&b).unwrap(),
2019-11-13 06:55:58 +02:00
r#"<w:tc><w:tcPr /><w:p><w:pPr><w:pStyle w:val="Normal" /><w:rPr /></w:pPr><w:r><w:rPr /><w:t xml:space="preserve">Hello</w:t></w:r></w:p></w:tc>"#
2019-11-12 11:57:16 +02:00
);
}
}