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
/*
 * render/text/elements.rs
 *
 * ftml - Library to parse Wikidot text
 * Copyright (C) 2019-2021 Wikijump Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

//! Module that implements text rendering for `Element` and its children.

use super::super::condition::{check_ifcategory, check_iftags};
use super::TextContext;
use crate::log::prelude::*;
use crate::render::ModuleRenderMode;
use crate::tree::{ContainerType, Element, LinkLocation, ListItem, ListType};
use crate::url::normalize_link;
use std::borrow::Cow;

pub fn render_elements(log: &Logger, ctx: &mut TextContext, elements: &[Element]) {
    debug!(log, "Rendering elements"; "elements-len" => elements.len());

    for element in elements {
        render_element(log, ctx, element);
    }
}

pub fn render_element(log: &Logger, ctx: &mut TextContext, element: &Element) {
    debug!(log, "Rendering element"; "element" => element.name());

    match element {
        Element::Container(container) => {
            let mut invisible = false;
            let (add_newlines, prefix) = match container.ctype() {
                // Don't render this at all.
                ContainerType::Hidden => return,

                // Render it, but invisibly.
                // Requires setting a special mode in the context.
                ContainerType::Invisible => {
                    ctx.enable_invisible();
                    invisible = true;

                    (false, None)
                }

                // If container is "terminating" (e.g. blockquote, p), then add newlines.
                // Also, determine if we add a prefix.
                ContainerType::Div | ContainerType::Paragraph => (true, None),
                ContainerType::Blockquote => (true, Some("    ")),
                ContainerType::Header(heading) => {
                    (true, Some(heading.level.prefix_with_space()))
                }

                // Inline or miscellaneous container.
                _ => (false, None),
            };

            if add_newlines {
                // Add prefix, if there's one
                if let Some(prefix) = prefix {
                    ctx.push_prefix(prefix);
                }

                ctx.add_newline();
            }

            // Render internal elements
            render_elements(log, ctx, container.elements());

            if add_newlines {
                // Pop prefix, if there's one
                if prefix.is_some() {
                    ctx.pop_prefix();
                }

                ctx.add_newline();
            }

            if invisible {
                ctx.disable_invisible();
            }
        }
        Element::Module(module) => {
            ctx.handle()
                .render_module(log, ctx.buffer(), module, ModuleRenderMode::Text)
        }
        Element::Text(text) | Element::Raw(text) | Element::Email(text) => {
            ctx.push_str(text)
        }
        Element::Anchor {
            elements,
            attributes,
            ..
        } => {
            render_elements(log, ctx, elements);

            if let Some(href) = attributes.get().get("href") {
                let link = LinkLocation::parse(cow!(href));
                let url = get_url_from_link(ctx, &link);

                str_write!(ctx, " [{}]", url);
            }
        }
        Element::Link { link, label, .. } => {
            let url = get_url_from_link(ctx, link);

            ctx.handle().get_link_label(log, link, label, |label| {
                ctx.push_str(label);

                // Don't show URL if it's a name link, or an anchor
                if url != label && !url.starts_with('#') {
                    str_write!(ctx, " [{}]", url);
                }
            });
        }
        Element::Image {
            source,
            link,
            alignment,
            attributes,
        } => {
            let source_url = ctx.handle().get_image_link(log, ctx.info(), source);

            str_write!(ctx, "Image: {}", &source_url);

            if let Some(image) = alignment {
                let float = if image.float { " float" } else { "" };
                str_write!(ctx, " [Align: {}{}]", image.align.name(), float);
            }

            if let Some(link) = link {
                str_write!(ctx, " [Link: {}]", get_url_from_link(ctx, link));
            }

            if let Some(alt_text) = attributes.get().get("alt") {
                str_write!(ctx, " [Alt: {}]", alt_text);
            }

            if let Some(title) = attributes.get().get("title") {
                str_write!(ctx, " [Title: {}]", title);
            }
        }
        Element::List { ltype, items, .. } => {
            if !ctx.ends_with_newline() {
                ctx.add_newline();
            }

            for item in items {
                match item {
                    ListItem::Elements(elements) => {
                        // Don't do anything if it's empty
                        if elements.is_empty() {
                            continue;
                        }

                        // Render bullet and its depth
                        let depth = ctx.list_depth();
                        for _ in 0..depth {
                            ctx.push(' ');
                        }

                        match *ltype {
                            ListType::Bullet => ctx.push_str("* "),
                            ListType::Numbered => {
                                let index = ctx.next_list_index();
                                str_write!(ctx, "{}. ", index);
                            }
                            ListType::Generic => (),
                        }

                        // Render elements for this list item
                        render_elements(log, ctx, elements);
                        ctx.add_newline();
                    }
                    ListItem::SubList(list) => {
                        // Update bullet depth
                        ctx.incr_list_depth();
                        render_element(log, ctx, list);
                        ctx.decr_list_depth();
                    }
                }
            }
        }
        Element::ListItem(_) => panic!("Reached ancillary element"),
        Element::RadioButton { checked, .. } => {
            str_write!(ctx, "({}) ", if *checked { '*' } else { ' ' })
        }
        Element::CheckBox { checked, .. } => {
            str_write!(ctx, "[{}] ", if *checked { 'X' } else { ' ' })
        }
        Element::Collapsible {
            elements,
            show_text,
            hide_text,
            show_top,
            show_bottom,
            ..
        } => {
            macro_rules! get_text {
                ($input:expr, $message:expr) => {
                    match $input {
                        Some(ref text) => &text,
                        None => ctx.handle().get_message(log, ctx.language(), $message),
                    }
                };
            }

            let show_text = get_text!(show_text, "collapsible-open");
            let hide_text = get_text!(hide_text, "collapsible-hide");

            // Top of collapsible
            ctx.add_newline();
            ctx.push_str(show_text);
            ctx.add_newline();

            if *show_top {
                ctx.push_str(hide_text);
                ctx.add_newline();
            }

            // Collapsible contents
            render_elements(log, ctx, elements);

            // Bottom of collapsible
            if *show_bottom {
                ctx.add_newline();
                ctx.push_str(hide_text);
                ctx.add_newline();
            }
        }
        Element::IfCategory {
            conditions,
            elements,
        } => {
            if check_ifcategory(log, ctx.info(), conditions) {
                render_elements(log, ctx, elements);
            }
        }
        Element::IfTags {
            conditions,
            elements,
        } => {
            if check_iftags(log, ctx.info(), conditions) {
                render_elements(log, ctx, elements);
            }
        }
        Element::TableOfContents { .. } => {
            debug!(log, "Rendering table of contents");

            let table_of_contents_title =
                ctx.handle()
                    .get_message(log, ctx.language(), "table-of-contents");

            ctx.add_newline();
            ctx.push_str(table_of_contents_title);
            ctx.add_newline();
            render_elements(log, ctx, ctx.table_of_contents());
        }
        Element::User { name, .. } => ctx.push_str(name),
        Element::Color { elements, .. } => render_elements(log, ctx, elements),
        Element::Code { contents, language } => {
            let language = match language {
                Some(language) => language,
                None => "",
            };

            str_write!(ctx, "```{}\n{}\n```", language, contents);
        }
        Element::Html { contents } => {
            str_write!(ctx, "```html\n{}\n```", contents);
        }
        Element::Iframe { url, .. } => str_write!(ctx, "[iframe: {}]", url),
        Element::LineBreak => ctx.add_newline(),
        Element::LineBreaks(amount) => {
            for _ in 0..amount.get() {
                ctx.add_newline();
            }
        }
        Element::ClearFloat(_) => {
            if !ctx.ends_with_newline() {
                ctx.add_newline();
            }

            ctx.push_str("~~~~~~");
            ctx.add_newline();
        }
        Element::HorizontalRule => {
            if !ctx.ends_with_newline() {
                ctx.add_newline();
            }

            ctx.push_str("------");
            ctx.add_newline();
        }
    }
}

fn get_url_from_link<'a>(ctx: &TextContext, link: &'a LinkLocation<'a>) -> Cow<'a, str> {
    let url = normalize_link(link, ctx.handle());

    // TODO: when we remove inline javascript stuff
    if url.as_ref() == "javascript:;" {
        return Cow::Borrowed("#");
    }

    url
}