docx_rs/documents/elements/
instr_pageref.rs

1use serde::Serialize;
2use std::io::Write;
3
4use crate::documents::*;
5use crate::xml_builder::XMLBuilder;
6
7// https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_PAGEREFPAGEREF_topic_ID0EHXK1.html
8#[derive(Serialize, Debug, Clone, PartialEq, Default)]
9#[serde(rename_all = "camelCase")]
10pub struct InstrPAGEREF {
11    pub page_ref: String,
12    pub hyperlink: bool,
13    pub relative_position: bool,
14}
15
16impl InstrPAGEREF {
17    pub fn new(r: impl Into<String>) -> Self {
18        Self {
19            page_ref: r.into(),
20            ..Default::default()
21        }
22    }
23
24    pub fn hyperlink(mut self) -> Self {
25        self.hyperlink = true;
26        self
27    }
28
29    pub fn relative_position(mut self) -> Self {
30        self.relative_position = true;
31        self
32    }
33}
34
35impl BuildXML for InstrPAGEREF {
36    fn build_to<W: Write>(
37        &self,
38        stream: xml::writer::EventWriter<W>,
39    ) -> xml::writer::Result<xml::writer::EventWriter<W>> {
40        XMLBuilder::from(stream)
41            .plain_text("PAGEREF ")?
42            .plain_text(&self.page_ref)?
43            .apply_if(self.relative_position, |b| b.plain_text(" \\p"))?
44            .apply_if(self.hyperlink, |b| b.plain_text(" \\h"))?
45            .into_inner()
46    }
47}
48
49impl std::str::FromStr for InstrPAGEREF {
50    type Err = ();
51
52    fn from_str(instr: &str) -> Result<Self, Self::Err> {
53        let mut s = instr.split(' ');
54        let text = s.next();
55        let mut page_ref = InstrPAGEREF::new(text.unwrap_or_default());
56        loop {
57            if let Some(i) = s.next() {
58                match i {
59                    "\\h" => page_ref = page_ref.hyperlink(),
60                    "\\p" => page_ref = page_ref.relative_position(),
61                    _ => {}
62                }
63            } else {
64                return Ok(page_ref);
65            }
66        }
67    }
68}
69
70#[cfg(test)]
71mod tests {
72
73    use super::*;
74    #[cfg(test)]
75    use pretty_assertions::assert_eq;
76    use std::str;
77
78    #[test]
79    fn test_page_ref() {
80        let b = InstrPAGEREF::new("_Toc00000000").hyperlink().build();
81        assert_eq!(str::from_utf8(&b).unwrap(), r#"PAGEREF _Toc00000000 \h"#);
82    }
83}