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
use crate::document::ParseError;

#[derive(PartialEq, Debug, Default, Clone, Serialize)]
pub struct Heading {
    pub level: u8,
    pub title: crate::Rendered,
    pub id: crate::ValueWithDefault<String>,
}

impl ToString for Heading {
    fn to_string(&self) -> String {
        self.to_p1().to_string().trim_end().to_string()
    }
}

impl Heading {
    pub fn new(level: u8, title: &str) -> Self {
        Heading {
            level,
            title: crate::Rendered::line(title),
            id: crate::ValueWithDefault::Default(slug::slugify(title)),
        }
    }

    pub fn with_level(p1: &crate::p1::Section, level: u8) -> Result<Self, ParseError> {
        let title = match p1.caption {
            Some(ref c) => c.trim().to_string(),
            None => return Err(ParseError::ValidationError("heading is empty".to_string())),
        };

        Ok(Heading {
            level,
            title: crate::Rendered::line(title.as_str()),
            id: match p1.header.string_optional("id")? {
                Some(v) => crate::ValueWithDefault::Found(v),
                None => crate::ValueWithDefault::Default(slug::slugify(title)),
            },
        })
    }

    pub fn to_p1(&self) -> crate::p1::Section {
        let p1 = crate::p1::Section::with_name(format!("h{}", self.level).as_str())
            .and_caption(self.title.original.as_str());
        match self.id {
            crate::ValueWithDefault::Found(ref v) => p1.add_header("id", v.as_str()),
            crate::ValueWithDefault::Default(_) => p1,
        }
    }

    pub fn from_p1(p1: &crate::p1::Section) -> Result<Self, ParseError> {
        match p1.caption {
            Some(ref c) => {
                let mut parts = c.splitn(2, ' ');
                match (parts.next(), parts.next()) {
                    (Some(l), Some(r)) => {
                        let (title, level) = match l.parse() {
                            Ok(l) => (r.trim().to_string(), l),
                            Err(_) => (c.trim().to_string(), 0),
                        };

                        Ok(Heading {
                            level,
                            title: crate::Rendered::line(title.as_str()),
                            id: match p1.header.string_optional("id")? {
                                Some(v) => crate::ValueWithDefault::Found(v),
                                None => crate::ValueWithDefault::Default(slug::slugify(title)),
                            },
                        })
                    }
                    _ => Err(ParseError::ValidationError(
                        "heading must have level and title".to_string(),
                    )),
                }
            }
            None => Err(ParseError::ValidationError("heading is empty".to_string())),
        }
    }
}

#[cfg(test)]
mod test {
    use crate::prelude::*;

    #[test]
    fn headings() {
        assert_eq!(
            "-- h27: hello world",
            crate::Heading {
                level: 27,
                title: crate::Rendered::line("hello world"),
                id: crate::ValueWithDefault::Default("hello-world".to_string()),
            }
            .to_string()
        );

        p(
            &indoc!(
                "
                 -- heading: hello world2
            "
            ),
            &vec![crate::Section::Heading(crate::Heading {
                level: 0,
                title: crate::Rendered::line("hello world2"),
                id: crate::ValueWithDefault::Default("hello-world2".to_string()),
            })],
        );

        // NOT: this is no longer supported
        // p(
        //     &indoc!(
        //         "
        //          -- heading: hello world2
        //          this is the body
        //
        //          multi line
        //     "
        //     ),
        //     Module {
        //         sections: vec![
        //             Section::Heading(Heading {
        //                 level: 0,
        //                 title: crate::Rendered::line("hello world2"),
        //             }),
        //             Section::Markdown(Markdown {
        //                 body: crate::Rendered::from("this is the body\n\nmulti line"),
        //                 hard_breaks: false,
        //                 auto_links: true,
        //                 align: Align::default(),
        //                 direction: TextDirection::default(),
        //                 two_columns: false,
        //             }),
        //         ],
        //     },
        // );

        // NOT: this is no longer supported
        // p(
        //     &indoc!(
        //         "
        //          -- heading: hello world2
        //          this is the body
        //
        //          multi line
        //          -- heading: hello 2 world
        //     "
        //     ),
        //     Module {
        //         sections: vec![
        //             Section::Heading(Heading {
        //                 level: 0,
        //                 title: crate::Rendered::line("hello world2"),
        //             }),
        //             Section::Markdown(Markdown {
        //                 body: crate::Rendered::from("this is the body\n\nmulti line"),
        //                 hard_breaks: false,
        //                 auto_links: true,
        //                 align: Align::default(),
        //                 direction: TextDirection::default(),
        //                 two_columns: false,
        //             }),
        //             Section::Heading(Heading {
        //                 level: 0,
        //                 title: crate::Rendered::line("hello 2 world"),
        //             }),
        //         ],
        //     },
        // );

        p(
            // should this be syntax error?
            &indoc!(
                "
                 -- heading:12 hello world
            "
            ),
            &vec![crate::Section::Heading(crate::Heading {
                level: 12,
                title: crate::Rendered::line("hello world"),
                id: crate::ValueWithDefault::Default("hello-world".to_string()),
            })],
        );

        // NOTE: this is no longer supported
        // p(
        //     // level must follow right after colon, without space, else its part of title
        //     &indoc!(
        //         "
        //          -- heading: 12 hello world
        //     "
        //     ),
        //     Module {
        //         sections: vec![Section::Heading(Heading {
        //             level: 0,
        //             title: crate::Rendered::line("12 hello world"),
        //         })],
        //     },
        // );
        f("-- heading: ", "ValidationError: heading is empty");
        p(
            "-- heading:1 yo\n\nhello",
            &vec![
                crate::Section::Heading(crate::Heading {
                    level: 1,
                    title: crate::Rendered::line("yo"),
                    id: crate::ValueWithDefault::Default("yo".to_string()),
                }),
                crate::Section::Markdown(crate::Markdown {
                    body: crate::Rendered::from("hello"),
                    caption: None,
                    hard_breaks: false,
                    auto_links: true,
                    align: crate::Align::default(),
                    direction: crate::TextDirection::default(),
                    two_columns: false,
                    collapsed: false,
                }),
            ],
        );
    }
}