html-filter 0.2.3

Parse HTML into a typed tree, then search for tags, attributes, classes, filter out comments or find and extract the exact data you want with a short builder pattern - zero dependencies, zero overhead
Documentation
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Module to filter an HTML tree to keep or remove specific nodes, with a set
//! of rules.
//!
//! You can either filter your HTML with [`Html::filter`] or find a specific
//! node with [`Html::find`].
//!
//! For more information on how to define the filtering rules, please refer to
//! [`Filter`].

extern crate alloc;
mod api;
mod element;
mod node_type;
pub mod types;

use alloc::borrow::Cow;
use core::cmp::Ordering;
use core::mem::take;

use node_type::NodeTypeFilter;
use types::Filter;

use crate::errors::{safe_expect, safe_unreachable};
use crate::{Html, Tag};

/// State to follow if the wanted nodes where found at what depth
///
/// # Note
///
/// We implement the discriminant and specify the representation size in order
/// to derive [`Ord`] trait.
#[repr(u8)]
#[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
enum DepthSuccess {
    /// Wanted node wanting more depth
    Found(usize) = 1,
    /// Not wanted node, doesn't respect the filters
    #[default]
    None = 2,
    /// Wanted node with already the wanted depth
    Success = 0,
}

impl DepthSuccess {
    /// Increment the depth, if applicable
    fn incr(mut self) -> Self {
        if let Self::Found(depth) = &mut self {
            *depth = safe_expect!(depth.checked_add(1), "Smaller than required depth");
        }

        self
    }
}

/// Status of the filtering on recursion calls
#[derive(Default, Debug)]
struct FilterSuccess {
    /// Indicates if the filter found a wanted node
    ///
    /// Is
    /// - `None` if no wanted node was found
    /// - `Some(depth)` if a wanted node was found at depth `depth`. If there
    ///   are embedded nodes that satisfy the filter, `depth` is the smallest
    ///   possible.
    depth: DepthSuccess,
    /// Result of the filtering
    html: Html,
}

impl FilterSuccess {
    /// Increment the depth, if applicable
    #[expect(clippy::unnecessary_wraps, reason = "useful for filter method")]
    fn incr(mut self) -> Option<Self> {
        self.depth = self.depth.incr();
        Some(self)
    }

    /// Creates a [`FilterSuccess`] from an [`Html`]
    ///
    /// This is the method to use when the node is considered `found`, i.e.,
    /// when it was the node the user was looking for.
    #[expect(clippy::unnecessary_wraps, reason = "useful for filter method")]
    const fn make_found(html: Html) -> Option<Self> {
        Some(Self { depth: DepthSuccess::Found(0), html })
    }

    /// Creates a [`FilterSuccess`] from an [`Html`]
    ///
    /// This is the method to use when the node isn't interesting alone, it can
    /// be if it is in the right scope though.
    #[expect(clippy::unnecessary_wraps, reason = "useful for filter method")]
    fn make_none(html: Cow<'_, Html>) -> Option<Self> {
        Some(Self { depth: DepthSuccess::None, html: html.into_owned() })
    }
}

impl Html {
    /// Method to check if a wanted node is visible
    ///
    /// This methods stop checking after a maximum depth, as the current node
    /// will be discarded if it is deeper in the tree.
    fn check_depth(&self, max_depth: usize, filter: &Filter) -> Option<usize> {
        match self {
            Self::Empty | Self::Text(_) | Self::Comment { .. } | Self::Doctype { .. } => None,
            Self::Tag { tag, .. } if filter.tag_explicitly_allowed(tag) => Some(0),
            Self::Tag { .. } | Self::Vec(_) if max_depth == 0 => None,
            Self::Tag { child, .. } => child
                .check_depth(
                    #[expect(clippy::arithmetic_side_effects, reason = "non-0")]
                    {
                        max_depth - 1
                    },
                    filter,
                )
                .map(
                    #[expect(clippy::arithmetic_side_effects, reason = "< initial max_depth")]
                    |depth| depth + 1,
                ),
            Self::Vec(vec) => vec
                .iter()
                .try_fold(Some(usize::MAX), |acc, child| {
                    if acc == Some(0) { Err(()) } else { Ok(child.check_depth(max_depth, filter)) }
                })
                .unwrap_or(Some(0)),
        }
    }

    /// Filters html based on a defined filter.
    ///
    /// See [`Filter`] to learn how to create filters.
    ///
    /// Filters allow you to select the portions of the html code you want to
    /// keep or remove.
    ///
    /// # Returns
    ///
    /// The html tree obtains by keeping only the nodes that fulfil the
    /// filter.
    #[must_use]
    pub fn filter(self, filter: &Filter) -> Self {
        filter_aux(Cow::Owned(self), filter, false).html
    }

    /// Finds an html node based on a defined filter.
    ///
    /// See [`Filter`] to know how to define a filter.
    ///
    /// Filters allow you to select the portions of the html code you want to
    /// keep or remove.
    ///
    /// # Returns
    ///
    /// The first node that fulfils the filter.
    #[must_use]
    pub fn find(self, filter: &Filter) -> Self {
        self.filter(filter).into_first()
    }

    /// Keeps only the first element of a filtered output
    fn into_first(self) -> Self {
        if let Self::Vec(vec) = self {
            for elt in vec {
                let res = elt.into_first();
                if !res.is_empty() {
                    return res;
                }
            }
            safe_unreachable!("Filtering removes empty nodes in vec.")
        } else {
            self
        }
    }

    /// Filters html based on a defined filter.
    ///
    /// Equivalent of [`Html::filter`] when data is not owned.
    #[must_use]
    pub fn to_filtered(&self, filter: &Filter) -> Self {
        filter_aux(Cow::Borrowed(self), filter, false).html
    }

    /// Finds an html node based on a defined filter.
    ///
    /// Equivalent of [`Html::find`] when data is not owned.
    // TODO: data except first is cloned
    #[must_use]
    pub fn to_found(&self, filter: &Filter) -> Self {
        self.to_filtered(filter).into_first()
    }
}

/// Wrapper for [`Html::filter`]
///
/// Refer to [`Html::filter`] for documentation.
///
/// This methods takes an additional `clean` boolean to indicate when a tag
/// returns the child. In that case, the texts must disappear if present at
/// root.
///
/// This methods returns a wrapper of the final html in a [`FilterSuccess`]
/// to follow the current depth of the last found node. See
/// [`FilterSuccess`] for more information.
#[allow(clippy::allow_attributes, reason = "expect is buggy")]
#[allow(clippy::enum_glob_use, reason = "heavy syntax and Html is the main struct")]
fn filter_aux(cow_html: Cow<'_, Html>, filter: &Filter, found: bool) -> FilterSuccess {
    use Html::*;
    match cow_html {
        Cow::Borrowed(Comment(_)) | Cow::Owned(Comment(_))
            if !filter.comment_explicitly_allowed() =>
            None,
        Cow::Borrowed(Doctype { .. }) | Cow::Owned(Doctype { .. }) if !filter.doctype_allowed() =>
            None,
        Cow::Borrowed(Doctype { .. } | Comment(_)) | Cow::Owned(Doctype { .. } | Comment(_)) =>
            FilterSuccess::make_none(cow_html),
        Cow::Borrowed(Text(text)) if filter.text_explicitly_allowed() && filter.should_trim() =>
            FilterSuccess::make_none(Cow::Owned(Html::trim_text(text))),
        Cow::Owned(Text(text)) if filter.text_explicitly_allowed() && filter.should_trim() =>
            FilterSuccess::make_none(Cow::Owned(Html::trim_text(&text))),
        Cow::Borrowed(Text(_)) | Cow::Owned(Text(_)) if filter.text_explicitly_allowed() =>
            FilterSuccess::make_none(cow_html),
        Cow::Borrowed(Text(_) | Empty) | Cow::Owned(Text(_) | Empty) => None,
        // incorrect
        Cow::Borrowed(Tag { tag, child }) =>
            filter_aux_tag(Cow::Borrowed(&**child), Cow::Borrowed(tag), filter, found),
        Cow::Owned(Tag { tag, child }) =>
            filter_aux_tag(Cow::Owned(*child), Cow::Owned(tag), filter, found),
        Cow::Borrowed(Vec(vec)) => filter_aux_vec(Cow::Borrowed(vec), filter),
        Cow::Owned(Vec(vec)) => filter_aux_vec(Cow::Owned(vec), filter),
    }
    .unwrap_or_default()
}

/// Auxiliary method for [`filter_aux`] on [`Html::Tag`]
#[expect(clippy::arithmetic_side_effects, reason = "incr depth when smaller than filter_depth")]
fn filter_aux_tag(
    child: Cow<'_, Html>,
    tag: Cow<'_, Tag>,
    filter: &Filter,
    found: bool,
) -> Option<FilterSuccess> {
    if filter.tag_allowed(tag.as_ref()) {
        FilterSuccess::make_found(Html::Tag {
            tag: tag.into_owned(),
            child: Box::new(filter_light(child, filter)),
        })
    } else if filter.as_depth() == 0 {
        filter_aux(child, filter, found).incr()
    } else {
        let rec = filter_aux(child, filter, found);
        match rec.depth {
            DepthSuccess::None => None,
            DepthSuccess::Success => Some(rec),
            DepthSuccess::Found(depth) => match depth.cmp(&filter.as_depth()) {
                Ordering::Less => Some(FilterSuccess {
                    depth: DepthSuccess::Found(depth + 1),
                    html: Html::Tag { tag: tag.into_owned(), child: Box::new(rec.html) },
                }),
                Ordering::Equal | Ordering::Greater =>
                    Some(FilterSuccess { depth: DepthSuccess::Success, html: rec.html }),
            },
        }
    }
}

/// Auxiliary method for [`filter_aux`] on [`Html::Vec`]
#[expect(clippy::arithmetic_side_effects, reason = "incr depth when smaller than filter_depth")]
fn filter_aux_vec(vec: Cow<'_, Box<[Html]>>, filter: &Filter) -> Option<FilterSuccess> {
    match vec
        .as_ref()
        .iter()
        .filter_map(|child| child.check_depth(filter.as_depth() + 1, filter))
        .min()
    {
        Some(depth) if depth < filter.as_depth() => Some(FilterSuccess {
            depth: DepthSuccess::Found(depth),
            html: unwrap_vec(
                vec.iter()
                    .map(|child| filter_light(Cow::Borrowed(child), filter))
                    .filter(|child| !child.is_empty())
                    .collect(),
                filter.as_collapse(),
            ),
        }),
        Some(_) => Some(FilterSuccess {
            depth: DepthSuccess::Success,
            html: unwrap_vec(
                into_iter_filter_map_collect(vec, |child| {
                    let rec = filter_aux(child, filter, true).html;
                    if rec.is_empty() { None } else { Some(rec) }
                }),
                filter.as_collapse(),
            ),
        }),
        None => {
            let mut filtered: Vec<FilterSuccess> = into_iter_filter_map_collect(vec, |child| {
                let rec = filter_aux(child, filter, false);
                if rec.html.is_empty() { None } else { Some(rec) }
            });
            if filtered.len() <= 1 {
                filtered.pop()
            } else {
                filtered.iter().map(|child| child.depth).min().map(|depth| FilterSuccess {
                    depth,
                    html: unwrap_vec(
                        filtered.into_iter().map(|child| child.html).collect(),
                        filter.as_collapse(),
                    ),
                })
            }
        }
    }
}

/// Light filter without complicated logic, just filtering on types.
///
/// This method does take into account the [`Filter::tag_name`],
///   [`Filter::attribute_name`] and [`Filter::attribute_value`] methods,
/// only the types of [`NodeTypeFilter`].
///
/// The return type is [`Html`] and not [`Cow`] has it is only called on
/// successes.
#[allow(clippy::allow_attributes, reason = "expect is buggy")]
#[allow(clippy::enum_glob_use, reason = "heavy syntax and Html is the main struct")]
fn filter_light(cow_html: Cow<'_, Html>, filter: &Filter) -> Html {
    use Html::*;
    #[allow(clippy::ref_patterns, reason = "!")]
    match cow_html {
        Cow::Borrowed(Text(txt)) if filter.text_allowed() && filter.should_trim() =>
            Html::trim_text(txt),
        Cow::Owned(Text(txt)) if filter.text_allowed() && filter.should_trim() =>
            Html::trim_text(&txt),
        Cow::Owned(Text(_)) | Cow::Borrowed(Text(_)) if filter.text_allowed() =>
            cow_html.into_owned(),
        Cow::Borrowed(Comment(_)) | Cow::Owned(Comment(_)) if filter.comment_allowed() =>
            cow_html.into_owned(),
        Cow::Borrowed(Doctype { .. }) | Cow::Owned(Doctype { .. }) if filter.doctype_allowed() =>
            cow_html.into_owned(),
        Cow::Borrowed(Tag { tag, .. }) if filter.tag_explicitly_blacklisted(tag) => Html::Empty,
        Cow::Owned(Tag { tag, .. }) if filter.tag_explicitly_blacklisted(&tag) => Html::Empty,
        Cow::Borrowed(Tag { tag, child }) => Tag {
            tag: tag.to_owned(),
            child: Box::new(filter_light(Cow::Borrowed(&**child), filter)),
        },
        Cow::Owned(Tag { tag, child }) =>
            Tag { tag, child: Box::new(filter_light(Cow::Owned(*child), filter)) },
        Cow::Borrowed(Vec(vec)) => unwrap_vec(
            vec.iter()
                .map(|child| filter_light(Cow::Borrowed(child), filter))
                .filter(|html| !html.is_empty())
                .collect(),
            filter.as_collapse(),
        ),
        Cow::Owned(Vec(vec)) => unwrap_vec(
            vec.into_iter()
                .map(|child| filter_light(Cow::Owned(child), filter))
                .filter(|html| !html.is_empty())
                .collect(),
            filter.as_collapse(),
        ),
        Cow::Borrowed(Empty | Text(_) | Comment { .. } | Doctype { .. })
        | Cow::Owned(Empty | Text(_) | Comment { .. } | Doctype { .. }) => Html::Empty,
    }
}

/// Unwrap a [`Vec<Html>`] to not have vecs of 0 and 1 element.
fn unwrap_vec(vec: Vec<Html>, collapse: bool) -> Html {
    let mut res = if collapse {
        let mut previous = String::new();
        let mut res = Vec::with_capacity(vec.len());
        for this in vec {
            if let Html::Text(text) = this {
                previous.push_str(&text);
            } else {
                if !previous.is_empty() {
                    res.push(Html::Text(take(&mut previous)));
                }
                res.push(this);
            }
        }
        if !previous.is_empty() {
            res.push(Html::Text(take(&mut previous)));
        }
        res
    } else {
        vec
    };
    if res.len() <= 1 {
        res.first_mut().map(take).unwrap_or_default()
    } else {
        Html::Vec(res.into_boxed_slice())
    }
}

/// Method to apply [`Iterator::filter_map`] on an iterator inside a Cow,
/// without losing the Cow.
fn into_iter_filter_map_collect<T, U, V, F>(cow: Cow<'_, Box<[T]>>, map: F) -> V
where
    T: Clone,
    V: FromIterator<U>,
    F: Fn(Cow<'_, T>) -> Option<U>,
{
    match cow {
        Cow::Borrowed(borrowed) =>
            borrowed.into_iter().filter_map(|elt| map(Cow::Borrowed(elt))).collect(),
        Cow::Owned(owned) => owned.into_iter().filter_map(|elt| map(Cow::Owned(elt))).collect(),
    }
}