Skip to main content

html_to_markdown_rs/dom/
mod.rs

1//! A mutable DOM with source offsets, built on the `astral_html` token stream.
2
3use std::borrow::Cow;
4
5/// CSS selectors over a parsed document.
6pub mod queryselector;
7mod stream;
8mod util;
9pub use queryselector::Selector;
10
11/// The index of a node in the parser's node list.
12pub type InnerNodeHandle = u32;
13
14const VOID: [&str; 15] = [
15    "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track",
16    "wbr",
17];
18
19/// A byte string that borrows from the source or owns an edited value.
20#[derive(Debug, Clone, Default, Eq)]
21pub struct Bytes<'a>(Cow<'a, [u8]>);
22
23/// The error of [`Bytes::set`].
24#[derive(Debug)]
25pub enum SetBytesError {
26    /// The value is too long to store.
27    LengthOverflow,
28}
29
30impl Bytes<'_> {
31    /// Returns an empty byte string.
32    #[must_use]
33    pub fn new() -> Self {
34        Self::default()
35    }
36    /// Returns the bytes as text, with invalid UTF-8 replaced.
37    #[must_use]
38    pub fn as_utf8_str(&self) -> Cow<'_, str> {
39        String::from_utf8_lossy(&self.0)
40    }
41    /// Returns the bytes as text, or `None` if they are not valid UTF-8.
42    #[must_use]
43    pub fn try_as_utf8_str(&self) -> Option<&str> {
44        std::str::from_utf8(&self.0).ok()
45    }
46    /// Returns the raw bytes.
47    #[must_use]
48    pub fn as_bytes(&self) -> &[u8] {
49        &self.0
50    }
51    /// Returns a pointer to the first byte.
52    #[must_use]
53    pub fn as_ptr(&self) -> *const u8 {
54        self.0.as_ptr()
55    }
56    /// Replaces the bytes with an owned value.
57    pub fn set<B: Into<Vec<u8>>>(&mut self, data: B) -> Result<Option<Box<[u8]>>, SetBytesError> {
58        self.0 = Cow::Owned(data.into());
59        Ok(None)
60    }
61}
62
63impl std::hash::Hash for Bytes<'_> {
64    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
65        self.0.hash(state);
66    }
67}
68impl PartialEq for Bytes<'_> {
69    fn eq(&self, other: &Self) -> bool {
70        self.0 == other.0
71    }
72}
73impl PartialEq<str> for Bytes<'_> {
74    fn eq(&self, other: &str) -> bool {
75        self.as_bytes() == other.as_bytes()
76    }
77}
78impl PartialEq<&str> for Bytes<'_> {
79    fn eq(&self, other: &&str) -> bool {
80        self.as_bytes() == other.as_bytes()
81    }
82}
83impl PartialEq<[u8]> for Bytes<'_> {
84    fn eq(&self, other: &[u8]) -> bool {
85        self.as_bytes() == other
86    }
87}
88impl PartialEq<&[u8]> for Bytes<'_> {
89    fn eq(&self, other: &&[u8]) -> bool {
90        self.as_bytes() == *other
91    }
92}
93impl<'a> From<&'a str> for Bytes<'a> {
94    fn from(value: &'a str) -> Self {
95        Self(Cow::Borrowed(value.as_bytes()))
96    }
97}
98impl<'a> From<&'a [u8]> for Bytes<'a> {
99    fn from(value: &'a [u8]) -> Self {
100        Self(Cow::Borrowed(value))
101    }
102}
103impl TryFrom<String> for Bytes<'static> {
104    type Error = SetBytesError;
105    fn try_from(value: String) -> Result<Self, Self::Error> {
106        Ok(Self(Cow::Owned(value.into_bytes())))
107    }
108}
109
110/// Options of [`parse`]. It holds none.
111#[derive(Debug, Clone, Copy, Default)]
112pub struct ParserOptions;
113impl ParserOptions {
114    /// Returns the default options.
115    #[must_use]
116    pub const fn new() -> Self {
117        Self
118    }
119}
120
121/// The error of [`parse`].
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum ParseError {
124    /// The input is longer than `u32::MAX` bytes.
125    InvalidLength,
126}
127impl std::fmt::Display for ParseError {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        f.write_str("the input length exceeds the capacity of the parser")
130    }
131}
132impl std::error::Error for ParseError {}
133
134/// A handle to a node in a [`Parser`].
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
136pub struct NodeHandle(u32);
137impl NodeHandle {
138    /// Returns the handle of the node at this index.
139    #[must_use]
140    pub const fn new(node: u32) -> Self {
141        Self(node)
142    }
143    /// Returns the node this handle points to.
144    #[must_use]
145    pub fn get<'p, 'buf>(&self, parser: &'p Parser<'buf>) -> Option<&'p Node<'buf>> {
146        parser.tags.get(self.0 as usize)
147    }
148    /// Returns the node this handle points to, for an edit.
149    pub fn get_mut<'p, 'buf>(&self, parser: &'p mut Parser<'buf>) -> Option<&'p mut Node<'buf>> {
150        parser.tags.get_mut(self.0 as usize)
151    }
152    /// Returns the index of the node.
153    #[must_use]
154    pub const fn get_inner(&self) -> u32 {
155        self.0
156    }
157}
158
159/// The direct children of an element.
160pub type RawChildren = smallvec::SmallVec<[NodeHandle; 4]>;
161
162/// The attributes of an element, in source order.
163#[derive(Debug, Clone, Default)]
164pub struct Attributes<'a> {
165    raw: Vec<(Bytes<'a>, Option<Bytes<'a>>)>,
166}
167
168impl<'a> Attributes<'a> {
169    /// Returns the number of attributes.
170    #[must_use]
171    pub const fn len(&self) -> usize {
172        self.raw.len()
173    }
174    /// Returns `true` if the element has no attributes.
175    #[must_use]
176    pub const fn is_empty(&self) -> bool {
177        self.raw.is_empty()
178    }
179    /// Returns the value of the first attribute with this name. The inner `None` is an attribute with no value.
180    pub fn get<B: Into<Bytes<'a>>>(&self, key: B) -> Option<Option<&Bytes<'a>>> {
181        let key = key.into();
182        self.raw
183            .iter()
184            .find(|(name, _)| *name == key)
185            .map(|(_, value)| value.as_ref())
186    }
187    /// Returns `true` if an attribute has this name.
188    pub fn contains<B: Into<Bytes<'a>>>(&self, key: B) -> bool {
189        self.get(key).is_some()
190    }
191    /// Removes the first attribute with this name and returns its value.
192    pub fn remove<B: Into<Bytes<'a>>>(&mut self, key: B) -> Option<Option<Bytes<'a>>> {
193        let key = key.into();
194        let index = self.raw.iter().position(|(name, _)| *name == key)?;
195        Some(self.raw.remove(index).1)
196    }
197    /// Returns each attribute as a name and an optional value, in source order.
198    pub fn iter(&self) -> impl Iterator<Item = (Cow<'_, str>, Option<Cow<'_, str>>)> + '_ {
199        self.raw
200            .iter()
201            .map(|(name, value)| (name.as_utf8_str(), value.as_ref().map(Bytes::as_utf8_str)))
202    }
203    /// Returns `true` if the `class` attribute holds this class name.
204    pub fn is_class_member<B: AsRef<[u8]>>(&self, member: B) -> bool {
205        self.class().is_some_and(|class| {
206            class
207                .as_utf8_str()
208                .split_ascii_whitespace()
209                .any(|name| name.as_bytes() == member.as_ref())
210        })
211    }
212    /// Returns the value of the `id` attribute.
213    #[must_use]
214    pub fn id(&self) -> Option<&Bytes<'a>> {
215        self.get("id").flatten()
216    }
217    /// Returns the value of the `class` attribute.
218    #[must_use]
219    pub fn class(&self) -> Option<&Bytes<'a>> {
220        self.get("class").flatten()
221    }
222}
223
224/// An element with its name, attributes, children and source bytes.
225#[derive(Debug, Clone)]
226pub struct HTMLTag<'a> {
227    name: Bytes<'a>,
228    attributes: Attributes<'a>,
229    children: RawChildren,
230    raw: Bytes<'a>,
231    id: u32,
232    subtree_end: u32,
233}
234
235impl<'a> HTMLTag<'a> {
236    /// Returns the children of the element.
237    #[must_use]
238    pub const fn children(&self) -> Children<'a, '_> {
239        Children(self)
240    }
241    /// Returns the children of the element, for an edit.
242    #[cfg(test)]
243    pub(crate) const fn children_mut(&mut self) -> ChildrenMut<'a, '_> {
244        ChildrenMut(self)
245    }
246    /// Returns the tag name as written in the source.
247    #[must_use]
248    pub const fn name(&self) -> &Bytes<'a> {
249        &self.name
250    }
251    /// Returns the attributes of the element.
252    #[must_use]
253    pub const fn attributes(&self) -> &Attributes<'a> {
254        &self.attributes
255    }
256    /// Returns the attributes of the element, for an edit.
257    pub const fn attributes_mut(&mut self) -> &mut Attributes<'a> {
258        &mut self.attributes
259    }
260    /// Returns the source bytes of the element, from its start tag to its end tag.
261    #[must_use]
262    pub const fn raw(&self) -> &Bytes<'a> {
263        &self.raw
264    }
265    /// Returns the first and the last byte offset of the element in the source.
266    #[must_use]
267    pub fn boundaries(&self, parser: &Parser<'a>) -> (usize, usize) {
268        let offset = self.raw.as_ptr() as usize - parser.source.as_ptr() as usize;
269        (offset, offset + self.raw.as_bytes().len() - 1)
270    }
271    /// Returns the text of every descendant text node, joined.
272    #[must_use]
273    pub fn inner_text<'p>(&self, parser: &'p Parser<'a>) -> Cow<'p, str> {
274        let mut text = String::new();
275        for node in &parser.tags[self.id as usize + 1..self.subtree_end as usize] {
276            if let Node::Raw(bytes) = node {
277                text.push_str(&bytes.as_utf8_str());
278            }
279        }
280        Cow::Owned(text)
281    }
282}
283
284/// The children of an element.
285pub struct Children<'a, 'b>(&'b HTMLTag<'a>);
286
287impl<'a, 'b> Children<'a, 'b> {
288    /// Returns the direct children.
289    #[must_use]
290    pub const fn top(&self) -> &'b RawChildren {
291        &self.0.children
292    }
293    /// Returns every descendant node, in document order.
294    #[must_use]
295    pub fn all(&self, parser: &'b Parser<'a>) -> &'b [Node<'a>] {
296        &parser.tags[self.0.id as usize + 1..self.0.subtree_end as usize]
297    }
298}
299
300/// The children of an element, for an edit.
301#[cfg(test)]
302pub(crate) struct ChildrenMut<'a, 'b>(&'b mut HTMLTag<'a>);
303
304#[cfg(test)]
305impl ChildrenMut<'_, '_> {
306    /// Returns the direct children, for an edit.
307    pub(crate) const fn top_mut(&mut self) -> &mut RawChildren {
308        &mut self.0.children
309    }
310}
311
312/// A node of the tree.
313#[derive(Debug, Clone)]
314pub enum Node<'a> {
315    /// An element.
316    Tag(HTMLTag<'a>),
317    /// A text node.
318    Raw(Bytes<'a>),
319    /// A comment, with its delimiters.
320    Comment(Bytes<'a>),
321}
322
323impl<'a> Node<'a> {
324    /// Returns the text of the node and its descendants.
325    #[must_use]
326    pub fn inner_text<'s, 'p: 's>(&'s self, parser: &'p Parser<'a>) -> Cow<'s, str> {
327        match self {
328            Node::Tag(tag) => tag.inner_text(parser),
329            Node::Raw(bytes) => bytes.as_utf8_str(),
330            Node::Comment(_) => Cow::Borrowed(""),
331        }
332    }
333    /// Returns the children of an element, or `None` for another node.
334    #[must_use]
335    pub const fn children(&self) -> Option<Children<'a, '_>> {
336        match self {
337            Node::Tag(tag) => Some(tag.children()),
338            _ => None,
339        }
340    }
341    /// Returns the element, or `None` for another node.
342    #[must_use]
343    pub const fn as_tag(&self) -> Option<&HTMLTag<'a>> {
344        match self {
345            Node::Tag(tag) => Some(tag),
346            _ => None,
347        }
348    }
349    /// Returns the element for an edit, or `None` for another node.
350    pub const fn as_tag_mut(&mut self) -> Option<&mut HTMLTag<'a>> {
351        match self {
352            Node::Tag(tag) => Some(tag),
353            _ => None,
354        }
355    }
356    /// Returns the comment, or `None` for another node.
357    #[must_use]
358    pub const fn as_comment(&self) -> Option<&Bytes<'a>> {
359        match self {
360            Node::Comment(bytes) => Some(bytes),
361            _ => None,
362        }
363    }
364    /// Returns the text, or `None` for another node.
365    #[must_use]
366    pub const fn as_raw(&self) -> Option<&Bytes<'a>> {
367        match self {
368            Node::Raw(bytes) => Some(bytes),
369            _ => None,
370        }
371    }
372    /// Returns the text for an edit, or `None` for another node.
373    pub const fn as_raw_mut(&mut self) -> Option<&mut Bytes<'a>> {
374        match self {
375            Node::Raw(bytes) => Some(bytes),
376            _ => None,
377        }
378    }
379}
380
381/// The node list of a parsed document.
382#[derive(Debug, Clone)]
383pub struct Parser<'a> {
384    pub(crate) tags: Vec<Node<'a>>,
385    pub(crate) ast: Vec<NodeHandle>,
386    source: &'a str,
387}
388
389impl<'a> Parser<'a> {
390    /// Returns the node at this index.
391    #[must_use]
392    pub fn resolve_node_id(&self, id: u32) -> Option<&Node<'a>> {
393        self.tags.get(id as usize)
394    }
395
396    fn tag_mut(&mut self, id: u32) -> &mut HTMLTag<'a> {
397        match &mut self.tags[id as usize] {
398            Node::Tag(tag) => tag,
399            _ => unreachable!("the open stack holds tags"),
400        }
401    }
402
403    fn append(&mut self, node: Node<'a>, parent: Option<u32>) -> u32 {
404        let id = self.tags.len() as u32;
405        self.tags.push(node);
406        match parent {
407            Some(parent) => self.tag_mut(parent).children.push(NodeHandle(id)),
408            None => self.ast.push(NodeHandle(id)),
409        }
410        id
411    }
412
413    fn slice(&self, start: usize, end: usize) -> Bytes<'a> {
414        Bytes(Cow::Borrowed(&self.source.as_bytes()[start..end]))
415    }
416}
417
418/// A parsed document.
419#[derive(Debug, Clone)]
420pub struct VDom<'a> {
421    parser: Parser<'a>,
422}
423
424impl<'a> VDom<'a> {
425    /// Returns the node list.
426    #[must_use]
427    pub const fn parser(&self) -> &Parser<'a> {
428        &self.parser
429    }
430    /// Returns the node list, for an edit.
431    pub const fn parser_mut(&mut self) -> &mut Parser<'a> {
432        &mut self.parser
433    }
434    /// Renames the `elements` that carry a `data-as` attribute to the element it names.
435    ///
436    /// `None` uses [`DEFAULT_DATA_AS_ELEMENTS`]; `Some` of an empty slice renames nothing.
437    pub(crate) fn apply_data_as(&mut self, elements: Option<&[String]>) {
438        match elements {
439            Some(elements) => apply_data_as(&mut self.parser, elements),
440            None => apply_data_as(&mut self.parser, &DEFAULT_DATA_AS_ELEMENTS),
441        }
442    }
443    /// Returns every node, in document order.
444    #[must_use]
445    pub fn nodes(&self) -> &[Node<'a>] {
446        &self.parser.tags
447    }
448    /// Returns every node, for an edit.
449    pub fn nodes_mut(&mut self) -> &mut [Node<'a>] {
450        &mut self.parser.tags
451    }
452    /// Returns the top-level nodes.
453    #[must_use]
454    pub fn children(&self) -> &[NodeHandle] {
455        &self.parser.ast
456    }
457    /// Returns the elements that match a CSS selector, or `None` if the selector does not parse.
458    #[must_use]
459    pub fn query_selector<'b>(
460        &'b self,
461        selector: &'b str,
462    ) -> Option<queryselector::QuerySelectorIterator<'a, 'b, Self>> {
463        let selector = queryselector::Parser::new(selector.as_bytes()).selector()?;
464        Some(queryselector::QuerySelectorIterator::new(selector, &self.parser, self))
465    }
466}
467
468/// The stack of open elements. An end tag closes the element on top when it spells that name and
469/// closes nothing otherwise, so the walks in the converter that find an omitted or a discarded end
470/// tag read this tree as they read `tl`.
471#[derive(Default)]
472struct Scopes {
473    open: Vec<u32>,
474    /// True inside a re-read body: text there stays text, so a re-read cannot re-read itself.
475    rereading: bool,
476}
477
478impl Scopes {
479    fn close_top(&mut self, end: u32, parser: &mut Parser<'_>) -> Option<u32> {
480        let id = self.open.pop()?;
481        parser.tag_mut(id).subtree_end = end;
482        Some(id)
483    }
484
485    fn top_is(&self, parser: &Parser<'_>, name: &[u8]) -> bool {
486        let top = self.open.last().and_then(|id| parser.tags[*id as usize].as_tag());
487        top.is_some_and(|tag| tag.name.as_bytes().eq_ignore_ascii_case(name))
488    }
489
490    /// True when the nearest open `svg` is not under an element that holds HTML again.
491    fn in_svg(&self, parser: &Parser<'_>) -> bool {
492        let names = self
493            .open
494            .iter()
495            .rev()
496            .filter_map(|id| parser.tags[*id as usize].as_tag());
497        for tag in names {
498            match tag.name.as_bytes() {
499                b"svg" => return true,
500                b"foreignObject" | b"desc" | b"title" => return false,
501                _ => {}
502            }
503        }
504        false
505    }
506}
507
508/// The SVG element names that HTML spells in mixed case, keyed by their lower-case form.
509const SVG_ELEMENTS: [(&str, &str); 37] = [
510    ("altglyph", "altGlyph"),
511    ("altglyphdef", "altGlyphDef"),
512    ("altglyphitem", "altGlyphItem"),
513    ("animatecolor", "animateColor"),
514    ("animatemotion", "animateMotion"),
515    ("animatetransform", "animateTransform"),
516    ("clippath", "clipPath"),
517    ("feblend", "feBlend"),
518    ("fecolormatrix", "feColorMatrix"),
519    ("fecomponenttransfer", "feComponentTransfer"),
520    ("fecomposite", "feComposite"),
521    ("feconvolvematrix", "feConvolveMatrix"),
522    ("fediffuselighting", "feDiffuseLighting"),
523    ("fedisplacementmap", "feDisplacementMap"),
524    ("fedistantlight", "feDistantLight"),
525    ("fedropshadow", "feDropShadow"),
526    ("feflood", "feFlood"),
527    ("fefunca", "feFuncA"),
528    ("fefuncb", "feFuncB"),
529    ("fefuncg", "feFuncG"),
530    ("fefuncr", "feFuncR"),
531    ("fegaussianblur", "feGaussianBlur"),
532    ("feimage", "feImage"),
533    ("femerge", "feMerge"),
534    ("femergenode", "feMergeNode"),
535    ("femorphology", "feMorphology"),
536    ("feoffset", "feOffset"),
537    ("fepointlight", "fePointLight"),
538    ("fespecularlighting", "feSpecularLighting"),
539    ("fespotlight", "feSpotLight"),
540    ("fetile", "feTile"),
541    ("feturbulence", "feTurbulence"),
542    ("foreignobject", "foreignObject"),
543    ("glyphref", "glyphRef"),
544    ("lineargradient", "linearGradient"),
545    ("radialgradient", "radialGradient"),
546    ("textpath", "textPath"),
547];
548
549/// The name of an element as HTML reads it: lower case, with the mixed-case SVG names inside `svg`.
550fn element_name<'a>(parser: &Parser<'a>, scopes: &Scopes, name: Cow<'a, str>) -> Bytes<'a> {
551    let svg_name = SVG_ELEMENTS
552        .iter()
553        .find(|(lower, _)| *lower == name)
554        .map(|(_, mixed)| *mixed);
555    match svg_name {
556        Some(mixed) if scopes.in_svg(parser) => Bytes::from(mixed),
557        _ => match name {
558            Cow::Borrowed(name) => Bytes::from(name),
559            Cow::Owned(name) => Bytes(Cow::Owned(name.into_bytes())),
560        },
561    }
562}
563
564fn attributes_of(list: Vec<astral_html::Attribute<'_>>) -> Attributes<'_> {
565    let raw = list
566        .into_iter()
567        .map(|attribute| {
568            let key = match attribute.name {
569                Cow::Borrowed(name) => Bytes::from(name),
570                Cow::Owned(name) => Bytes(Cow::Owned(name.into_bytes())),
571            };
572            (key, attribute.raw_value.map(Bytes::from))
573        })
574        .collect();
575    Attributes { raw }
576}
577
578fn start_tag<'a>(parser: &mut Parser<'a>, scopes: &mut Scopes, tag: astral_html::Tag<'a>, start: usize, end: usize) {
579    let closed = tag.self_closing || VOID.contains(&tag.name.as_ref());
580    let node = HTMLTag {
581        name: element_name(parser, scopes, tag.name),
582        attributes: attributes_of(tag.attributes),
583        children: RawChildren::new(),
584        raw: parser.slice(start, end),
585        id: parser.tags.len() as u32,
586        subtree_end: parser.tags.len() as u32 + 1,
587    };
588    let parent = scopes.open.last().copied();
589    let id = parser.append(Node::Tag(node), parent);
590    if !closed {
591        scopes.open.push(id);
592    }
593}
594
595/// An end tag closes the element on top when it names that element in any letter case, as HTML reads it.
596fn end_tag(parser: &mut Parser<'_>, scopes: &mut Scopes, name: &str, end: usize) {
597    let closes = scopes.open.last().is_some_and(|id| match &parser.tags[*id as usize] {
598        Node::Tag(tag) => tag.name.as_bytes().eq_ignore_ascii_case(name.as_bytes()),
599        _ => false,
600    });
601    if !closes {
602        return;
603    }
604    let subtree_end = parser.tags.len() as u32;
605    if let Some(id) = scopes.close_top(subtree_end, parser) {
606        let start = parser.tag_mut(id).raw.as_ptr() as usize - parser.source.as_ptr() as usize;
607        let raw = parser.slice(start, end);
608        parser.tag_mut(id).raw = raw;
609    }
610}
611
612fn flush_text(parser: &mut Parser<'_>, scopes: &mut Scopes, text: &mut Option<(usize, usize)>) {
613    let Some((from, to)) = text.take() else { return };
614    // ~keep The reader takes these bodies as text, and the converter decides on the markup in them,
615    // ~keep so the body is read again in place. An `xmp` that closes reaches this point with its
616    // ~keep markup escaped. Only an `xmp` with no end tag holds markup here.
617    let reread = [b"noframes".as_slice(), b"noembed", b"plaintext", b"xmp"];
618    if !scopes.rereading && reread.iter().any(|name| scopes.top_is(parser, name)) {
619        scopes.rereading = true;
620        let mut tokens = astral_html::Tokenizer::new(&parser.source[from..to]);
621        read_region(parser, scopes, &mut tokens, from);
622        scopes.rereading = false;
623        return;
624    }
625    let bytes = parser.slice(from, to);
626    let parent = scopes.open.last().copied();
627    parser.append(Node::Raw(bytes), parent);
628}
629
630/// The two token streams of the parse. The reader follows the raw-text rules of HTML. The
631/// tokenizer stays in markup, so a re-read body holds no second raw-text body.
632trait Tokens<'a> {
633    fn next_token(&mut self) -> Option<astral_html::Token<'a>>;
634    fn offset(&self) -> usize;
635}
636
637impl<'a> Tokens<'a> for astral_html::Reader<'a> {
638    fn next_token(&mut self) -> Option<astral_html::Token<'a>> {
639        self.next()
640    }
641    fn offset(&self) -> usize {
642        self.position()
643    }
644}
645
646impl<'a> Tokens<'a> for astral_html::Tokenizer<'a> {
647    fn next_token(&mut self) -> Option<astral_html::Token<'a>> {
648        self.next()
649    }
650    fn offset(&self) -> usize {
651        self.position()
652    }
653}
654
655fn token_start(source: &str, token: &astral_html::Token<'_>, start: usize, end: usize) -> usize {
656    let consumed = &source[start..end];
657    let data = consumed.trim_start_matches("</>");
658    if data.len() == consumed.len() {
659        return start;
660    }
661    // ~keep The tokenizer skips empty end tags in data but emits them literally in raw text.
662    // ~keep Data text may start with the same spelling after entity decoding.
663    if let astral_html::Token::Text(value) = token
664        && value.starts_with("</>")
665        && astral_html::decode(data, false) != *value
666    {
667        return start;
668    }
669    end - data.len()
670}
671
672fn read_region<'a>(parser: &mut Parser<'a>, scopes: &mut Scopes, tokens: &mut impl Tokens<'a>, base: usize) {
673    let input = parser.source;
674    let mut start = base;
675    let mut text: Option<(usize, usize)> = None;
676    while let Some(token) = tokens.next_token() {
677        let end = base + tokens.offset();
678        let actual_start = token_start(input, &token, start, end);
679        if matches!(token, astral_html::Token::Text(_)) {
680            if actual_start != start {
681                flush_text(parser, scopes, &mut text);
682            }
683            text = Some((text.map_or(actual_start, |(from, _)| from), end));
684            start = end;
685            continue;
686        }
687        flush_text(parser, scopes, &mut text);
688        match token {
689            astral_html::Token::StartTag(tag) => start_tag(parser, scopes, tag, actual_start, end),
690            astral_html::Token::EndTag(tag) => end_tag(parser, scopes, &tag.name, end),
691            astral_html::Token::Comment(_) if input.as_bytes()[actual_start..].starts_with(b"<!--") => {
692                let bytes = parser.slice(actual_start, end);
693                let parent = scopes.open.last().copied();
694                parser.append(Node::Comment(bytes), parent);
695            }
696            _ => {}
697        }
698        start = end;
699    }
700    flush_text(parser, scopes, &mut text);
701}
702
703/// Parses an HTML document into a tree.
704pub fn parse(input: &str, _options: ParserOptions) -> Result<VDom<'_>, ParseError> {
705    let Ok(_) = u32::try_from(input.len()) else {
706        return Err(ParseError::InvalidLength);
707    };
708    let mut parser = Parser {
709        tags: Vec::new(),
710        ast: Vec::new(),
711        source: input,
712    };
713    let mut scopes = Scopes::default();
714    read_region(&mut parser, &mut scopes, &mut astral_html::Reader::new(input), 0);
715    let subtree_end = parser.tags.len() as u32;
716    while scopes.close_top(subtree_end, &mut parser).is_some() {}
717    Ok(VDom { parser })
718}
719
720/// The elements whose `data-as` attribute is honored when `ConversionOptions::data_as_elements` is unset.
721const DEFAULT_DATA_AS_ELEMENTS: [&str; 2] = ["span", "div"];
722
723/// The element a `data-as` value asks a `span` to stand for, if it names one the converter treats as a block.
724fn data_as_element(value: &str) -> Option<&'static str> {
725    const ELEMENTS: [&str; 13] = [
726        "p",
727        "h1",
728        "h2",
729        "h3",
730        "h4",
731        "h5",
732        "h6",
733        "li",
734        "ul",
735        "ol",
736        "blockquote",
737        "pre",
738        "div",
739    ];
740    let value = crate::text::decode_attribute_value_cow(value);
741    let value = value.trim_ascii();
742    ELEMENTS.into_iter().find(|name| value.eq_ignore_ascii_case(name))
743}
744
745/// Renames each element of `elements` that has a `data-as` attribute to the element the attribute names,
746/// so the converter handles it exactly as it handles that element (Mintlify writes a paragraph as
747/// `<span data-as="p">`).
748fn apply_data_as<S: AsRef<str>>(parser: &mut Parser<'_>, elements: &[S]) {
749    if elements.is_empty() {
750        return;
751    }
752    for node in &mut parser.tags {
753        let Node::Tag(tag) = node else { continue };
754        let name = tag.name.as_bytes();
755        if !elements
756            .iter()
757            .any(|element| name.eq_ignore_ascii_case(element.as_ref().as_bytes()))
758        {
759            continue;
760        }
761        let Some(Some(value)) = tag.attributes.get("data-as") else {
762            continue;
763        };
764        if let Some(element) = data_as_element(&value.as_utf8_str()) {
765            tag.name = Bytes::from(element);
766        }
767    }
768}