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
/*
Copyright (C) 2020-2021 Kunal Mehta <legoktm@debian.org>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

use crate::inclusion::NoInclude;
use crate::node::{Category, Comment, ExtLink, Section, WikiLink};
use crate::template::{self, Template};
use crate::Result;
use crate::Wikinode;
use kuchiki::iter::{Ancestors, Descendants, Siblings};
use kuchiki::NodeRef;
use std::iter::Rev;

/// Iterator wrapper to convert NodeRefs into Wikinodes
#[doc(hidden)]
pub struct WikinodeMap<I>(I);

impl<I> Iterator for WikinodeMap<I>
where
    I: Iterator<Item = NodeRef>,
{
    type Item = Wikinode;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|item| Wikinode::new_from_node(&item))
    }
}

/// Collection of iterators and mutators that allow operating on a tree of Wikinodes
pub trait WikinodeIterator {
    fn as_node(&self) -> &NodeRef;

    /* Mutators */

    /// Append a node as a child
    fn append(&self, code: &NodeRef) {
        self.as_node().append(code.clone());
    }

    /// Prepend a node as a child
    fn prepend(&self, code: &NodeRef) {
        self.as_node().prepend(code.clone());
    }

    /// Insert a node after the current node, as a sibling
    fn insert_after(&self, code: &NodeRef) {
        self.as_node().insert_after(code.clone());
    }

    /// Insert a node before the current node, as a sibling
    fn insert_before(&self, code: &NodeRef) {
        self.as_node().insert_before(code.clone());
    }

    /* Selectors */

    /// Select some wiki nodes
    fn select(&self, selector: &str) -> Vec<Wikinode> {
        match self.as_node().select(selector) {
            Ok(select) => select
                .map(|node| Wikinode::new_from_node(node.as_node()))
                .collect(),
            Err(_) => vec![],
        }
    }

    /// Get the first element that matches the selector, if possible
    fn select_first(&self, selector: &str) -> Option<Wikinode> {
        match self.as_node().select_first(selector) {
            Ok(node) => Some(Wikinode::new_from_node(node.as_node())),
            Err(_) => None,
        }
    }

    /* Wiki iterators */
    /// Get a list of all wikilinks (`[[Foo|bar]]`)
    fn filter_links(&self) -> Vec<WikiLink> {
        self.select(WikiLink::SELECTOR)
            .iter()
            .map(|ref_| WikiLink::new_from_node(ref_.as_node()))
            .collect()
    }

    /// Get a list of all external links (`[https://example.org/ Example]`)
    fn filter_external_links(&self) -> Vec<ExtLink> {
        self.select(ExtLink::SELECTOR)
            .iter()
            .map(|ref_| ExtLink::new_from_node(ref_.as_node()))
            .collect()
    }

    /// Get a list of all categories
    fn filter_categories(&self) -> Vec<Category> {
        self.select(Category::SELECTOR)
            .iter()
            .map(|ref_| Category::new_from_node(ref_.as_node()))
            .collect()
    }

    /// Get a list of all comments (`<!-- example -->`)
    fn filter_comments(&self) -> Vec<Comment> {
        self.inclusive_descendants()
            .filter_map(|node| node.as_comment())
            .collect()
    }

    /// Get a list of templates
    fn filter_templates(&self) -> Result<Vec<Template>> {
        Ok(filter_templatelike(&self.select(Template::SELECTOR))?
            .iter()
            .filter_map(|temp| {
                if temp.is_template() {
                    Some(temp.clone())
                } else {
                    None
                }
            })
            .collect())
    }

    /// Get a list of parser functions.
    fn filter_parser_functions(&self) -> Result<Vec<Template>> {
        Ok(filter_templatelike(&self.select(Template::SELECTOR))?
            .iter()
            .filter_map(|temp| {
                if temp.is_parser_function() {
                    Some(temp.clone())
                } else {
                    None
                }
            })
            .collect())
    }

    fn iter_sections(&self) -> Vec<Section> {
        // TODO: maybe filter_map to unwrap Wikinode::Section(Section)?
        self.select(Section::SELECTOR)
            .iter()
            .map(|node| Section::new_from_node(node.as_node()))
            .collect()
    }

    fn filter_noinclude(&self) -> Vec<NoInclude> {
        self.select(NoInclude::SELECTOR)
            .iter()
            .filter_map(|node| {
                let start = node;
                let mut siblings = vec![];
                for sibling in node.following_siblings() {
                    if let Some(element) = sibling.as_element() {
                        if element.name.local == local_name!("meta")
                            && element.attributes.borrow().get("typeof")
                                == Some(NoInclude::TYPEOF_END)
                        {
                            return Some(NoInclude::new_from_node(
                                start, &sibling, &siblings,
                            ));
                        }
                    }
                    siblings.push(sibling.as_node().clone());
                }
                None
            })
            .collect()
    }

    /* Iterators */

    /// Return an iterator of references to this node and its ancestors.
    fn inclusive_ancestors(&self) -> WikinodeMap<Ancestors> {
        WikinodeMap(self.as_node().inclusive_ancestors())
    }

    /// Return an iterator of references to this node’s ancestors.
    fn ancestors(&self) -> WikinodeMap<Ancestors> {
        WikinodeMap(self.as_node().ancestors())
    }

    /// Return an iterator of references to this node and the siblings before it.
    fn inclusive_preceding_siblings(&self) -> WikinodeMap<Rev<Siblings>> {
        WikinodeMap(self.as_node().inclusive_preceding_siblings())
    }

    /// Return an iterator of references to this node’s siblings before it.
    fn preceding_simblings(&self) -> WikinodeMap<Rev<Siblings>> {
        WikinodeMap(self.as_node().preceding_siblings())
    }

    /// Return an iterator of references to this node and the siblings after it.
    fn inclusive_following_siblings(&self) -> WikinodeMap<Siblings> {
        WikinodeMap(self.as_node().inclusive_following_siblings())
    }

    /// Return an iterator of references to this node’s siblings after it.
    fn following_siblings(&self) -> WikinodeMap<Siblings> {
        WikinodeMap(self.as_node().following_siblings())
    }

    /// Return an iterator of references to this node’s children.
    fn children(&self) -> WikinodeMap<Siblings> {
        WikinodeMap(self.as_node().children())
    }

    /// Return an iterator of references to this node and its descendants, in tree order.
    /// Parent nodes appear before the descendants.
    fn inclusive_descendants(&self) -> WikinodeMap<Descendants> {
        WikinodeMap(self.as_node().inclusive_descendants())
    }

    /// Return an iterator of references to this node’s descendants, in tree order.
    /// Parent nodes appear before the descendants.
    fn descendants(&self) -> WikinodeMap<Descendants> {
        WikinodeMap(self.as_node().descendants())
    }

    /* -- these don't work because Traverse's Item is not NodeRef
    /// Return an iterator of the start and end edges of this node and its descendants, in tree order.
    fn traverse_inclusive(&self) -> WikinodeMap<Traverse> {
        WikinodeMap(self.as_node().traverse_inclusive())
    }

    /// Return an iterator of the start and end edges of this node’s descendants, in tree order.
    fn traverse(&self) -> WikinodeMap<Traverse> {
        WikinodeMap(self.as_node().traverse())
    }
    */
}

/// Filters template-like things (actual templates and parser functions)
fn filter_templatelike(nodes: &[Wikinode]) -> Result<Vec<Template>> {
    let mut templates = vec![];
    for ref_ in nodes {
        let element = ref_.as_node();
        let data: template::Transclusion = serde_json::from_str(
            element
                .as_element()
                .unwrap()
                .attributes
                .borrow()
                .get("data-mw")
                .unwrap(),
        )?;
        // Identify siblings with the same about attribute
        let siblings = match element
            .as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("about")
        {
            Some(about) => {
                // TODO: do we need preceding_siblings?
                element
                    .following_siblings()
                    .filter(|node| {
                        if let Some(element) = node.as_element() {
                            if let Some(new_about) =
                                element.attributes.borrow().get("about")
                            {
                                return about == new_about;
                            }
                        }

                        false
                    })
                    .collect()
            }
            None => vec![],
        };

        for (part_num, part) in data.parts.iter().enumerate() {
            if let template::TransclusionPart::Template { template: _ } = part {
                templates.push(Template::new_from_node(
                    element, &siblings, part_num,
                ));
            }
            // Note: we ignore interspersed wikitext, and treat it as read-only,
            // which is the behavior documented in the spec.
        }
    }

    Ok(templates)
}