Skip to main content

blitz_html/
html_sink.rs

1//! An implementation for Html5ever's sink trait, allowing us to parse HTML into a DOM.
2
3use html5ever::ParseOpts;
4use html5ever::tokenizer::TokenizerOpts;
5use html5ever::tree_builder::TreeBuilderOpts;
6use std::borrow::Cow;
7use std::cell::{Cell, Ref, RefCell, RefMut};
8
9use blitz_dom::node::Attribute;
10use blitz_dom::{DocumentMutator, HtmlParserProvider, NodeId};
11use html5ever::{
12    QualName,
13    tendril::{StrTendril, TendrilSink},
14    tree_builder::{ElementFlags, NodeOrText, QuirksMode, TreeSink},
15};
16
17/// Convert an html5ever Attribute which uses tendril for its value to a blitz Attribute
18/// which uses String.
19fn html5ever_to_blitz_attr(attr: html5ever::Attribute) -> Attribute {
20    Attribute {
21        name: attr.name,
22        value: attr.value.to_string(),
23    }
24}
25
26#[derive(Copy, Clone, Default, Debug)]
27pub struct HtmlProvider;
28
29impl HtmlParserProvider for HtmlProvider {
30    fn parse_inner_html<'m2, 'doc2>(
31        &self,
32        mutr: &'m2 mut DocumentMutator<'doc2>,
33        element_id: NodeId,
34        html: &str,
35    ) {
36        DocumentHtmlParser::parse_inner_html_into_mutator(mutr, element_id, html);
37    }
38
39    fn parse_document(
40        &self,
41        html: &str,
42        config: blitz_dom::DocumentConfig,
43    ) -> Box<dyn blitz_dom::Document> {
44        Box::new(crate::HtmlDocument::from_html(html, config))
45    }
46}
47
48pub struct DocumentHtmlParser<'m, 'doc> {
49    document_mutator: RefCell<&'m mut DocumentMutator<'doc>>,
50
51    /// Errors that occurred during parsing.
52    pub errors: RefCell<Vec<Cow<'static, str>>>,
53
54    /// The document's quirks mode.
55    pub quirks_mode: Cell<QuirksMode>,
56    pub is_xml: bool,
57}
58
59impl<'m, 'doc> DocumentHtmlParser<'m, 'doc> {
60    #[track_caller]
61    /// Get a mutable borrow of the DocumentMutator
62    fn mutr(&self) -> RefMut<'_, &'m mut DocumentMutator<'doc>> {
63        self.document_mutator.borrow_mut()
64    }
65}
66
67impl<'m, 'doc> DocumentHtmlParser<'m, 'doc> {
68    pub fn new(mutr: &'m mut DocumentMutator<'doc>) -> DocumentHtmlParser<'m, 'doc> {
69        DocumentHtmlParser {
70            document_mutator: RefCell::new(mutr),
71            errors: RefCell::new(Vec::new()),
72            quirks_mode: Cell::new(QuirksMode::NoQuirks),
73            is_xml: false,
74        }
75    }
76
77    /// Detects documents without an XML or DOCTYPE declaration whose root `<html>` element
78    /// declares the XHTML namespace (e.g. `<html xmlns="http://www.w3.org/1999/xhtml">`)
79    fn root_element_has_xhtml_namespace(html: &str) -> bool {
80        let rest = html.trim_start_matches('\u{feff}').trim_start();
81        let Some(rest) = rest.strip_prefix("<html") else {
82            return false;
83        };
84        let Some(tag_end) = rest.find('>') else {
85            return false;
86        };
87        rest[..tag_end].contains("xmlns=\"http://www.w3.org/1999/xhtml\"")
88            || rest[..tag_end].contains("xmlns='http://www.w3.org/1999/xhtml'")
89    }
90
91    pub fn parse_into_mutator<'a, 'd>(mutr: &'a mut DocumentMutator<'d>, html: &str) {
92        let mut sink = DocumentHtmlParser::new(mutr);
93
94        let is_xhtml_doc = html.starts_with("<?xml")
95            || html.starts_with("<!DOCTYPE") && {
96                let first_line = html.lines().next().unwrap();
97                first_line.contains("XHTML") || first_line.contains("xhtml")
98            }
99            || Self::root_element_has_xhtml_namespace(html);
100
101        if is_xhtml_doc {
102            // Parse as XHTML
103            sink.is_xml = true;
104            xml5ever::driver::parse_document(sink, Default::default())
105                .from_utf8()
106                .read_from(&mut html.as_bytes())
107                .unwrap();
108        } else {
109            // Parse as HTML
110            sink.is_xml = false;
111            let opts = ParseOpts {
112                tokenizer: TokenizerOpts::default(),
113                tree_builder: TreeBuilderOpts {
114                    exact_errors: false,
115                    scripting_enabled: false, // Enables parsing of <noscript> tags
116                    iframe_srcdoc: false,
117                    drop_doctype: true,
118                    quirks_mode: QuirksMode::NoQuirks,
119                },
120            };
121            html5ever::parse_document(sink, opts)
122                .from_utf8()
123                .read_from(&mut html.as_bytes())
124                .unwrap();
125        }
126    }
127
128    pub fn parse_inner_html_into_mutator<'a, 'd>(
129        mutr: &'a mut DocumentMutator<'d>,
130        element_id: NodeId,
131        html: &str,
132    ) {
133        let sink = DocumentHtmlParser::new(mutr);
134
135        let opts = ParseOpts {
136            tokenizer: TokenizerOpts::default(),
137            tree_builder: TreeBuilderOpts {
138                exact_errors: false,
139                scripting_enabled: false, // Enables parsing of <noscript> tags
140                iframe_srcdoc: false,
141                drop_doctype: true,
142                quirks_mode: QuirksMode::NoQuirks,
143            },
144        };
145        html5ever::driver::parse_fragment_for_element(sink, opts, element_id, false, None)
146            .from_utf8()
147            .read_from(&mut html.as_bytes())
148            .unwrap();
149
150        // html5ever creates a new fragment root node under the document node and parses the nodes into that fragment root.
151        // So here we move the children of the fragment root to element_id and then drop the fragment root.
152        let document_id = mutr.doc.root_node().id;
153        let fragment_root_id = mutr.last_child_id(document_id).unwrap();
154        let child_ids = mutr.child_ids(fragment_root_id);
155        mutr.append_children(element_id, &child_ids);
156        mutr.remove_and_drop_node(fragment_root_id);
157    }
158}
159
160impl<'m, 'doc> TreeSink for DocumentHtmlParser<'m, 'doc> {
161    type Output = ();
162
163    // we use the ID of the nodes in the tree as the handle
164    type Handle = NodeId;
165
166    type ElemName<'a>
167        = Ref<'a, QualName>
168    where
169        Self: 'a;
170
171    fn finish(self) -> Self::Output {
172        #[cfg(feature = "tracing")]
173        for error in self.errors.borrow().iter() {
174            tracing::error!("{error}");
175        }
176    }
177
178    fn parse_error(&self, msg: Cow<'static, str>) {
179        self.errors.borrow_mut().push(msg);
180    }
181
182    fn get_document(&self) -> Self::Handle {
183        self.document_mutator.borrow().doc.root_node().id
184    }
185
186    fn elem_name<'a>(&'a self, target: &'a Self::Handle) -> Self::ElemName<'a> {
187        Ref::map(self.document_mutator.borrow(), |docm| {
188            docm.element_name(*target)
189                .expect("TreeSink::elem_name called on a node which is not an element!")
190        })
191    }
192
193    fn create_element(
194        &self,
195        name: QualName,
196        attrs: Vec<html5ever::Attribute>,
197        _flags: ElementFlags,
198    ) -> Self::Handle {
199        let attrs = attrs.into_iter().map(html5ever_to_blitz_attr).collect();
200        self.mutr().create_element(name, attrs)
201    }
202
203    fn create_comment(&self, text: StrTendril) -> Self::Handle {
204        self.mutr().create_comment_node(&text)
205    }
206
207    fn create_pi(&self, _target: StrTendril, _data: StrTendril) -> Self::Handle {
208        self.mutr().create_comment_node("")
209    }
210
211    fn append(&self, parent_id: &Self::Handle, child: NodeOrText<Self::Handle>) {
212        match child {
213            NodeOrText::AppendNode(id) => self.mutr().append_children(*parent_id, &[id]),
214            // If content to append is text, first attempt to append it to the last child of parent.
215            // Else create a new text node and append it to the parent
216            NodeOrText::AppendText(text) => {
217                let last_child_id = self.mutr().last_child_id(*parent_id);
218                let has_appended = if let Some(id) = last_child_id {
219                    self.mutr().append_text_to_node(id, &text).is_ok()
220                } else {
221                    false
222                };
223                if !has_appended {
224                    let new_child_id = self.mutr().create_text_node(&text);
225                    self.mutr().append_children(*parent_id, &[new_child_id]);
226                }
227            }
228        }
229    }
230
231    // Note: The tree builder promises we won't have a text node after the insertion point.
232    // https://github.com/servo/html5ever/blob/main/rcdom/lib.rs#L338
233    fn append_before_sibling(&self, sibling_id: &Self::Handle, new_node: NodeOrText<Self::Handle>) {
234        match new_node {
235            NodeOrText::AppendNode(id) => self.mutr().insert_nodes_before(*sibling_id, &[id]),
236            // If content to append is text, first attempt to append it to the node before sibling_node
237            // Else create a new text node and insert it before sibling_node
238            NodeOrText::AppendText(text) => {
239                let previous_sibling_id = self.mutr().previous_sibling_id(*sibling_id);
240                let has_appended = if let Some(id) = previous_sibling_id {
241                    self.mutr().append_text_to_node(id, &text).is_ok()
242                } else {
243                    false
244                };
245                if !has_appended {
246                    let new_child_id = self.mutr().create_text_node(&text);
247                    self.mutr()
248                        .insert_nodes_before(*sibling_id, &[new_child_id]);
249                }
250            }
251        };
252    }
253
254    fn append_based_on_parent_node(
255        &self,
256        element: &Self::Handle,
257        prev_element: &Self::Handle,
258        child: NodeOrText<Self::Handle>,
259    ) {
260        if self.mutr().node_has_parent(*element) {
261            self.append_before_sibling(element, child);
262        } else {
263            self.append(prev_element, child);
264        }
265    }
266
267    fn append_doctype_to_document(
268        &self,
269        _name: StrTendril,
270        _public_id: StrTendril,
271        _system_id: StrTendril,
272    ) {
273        // Ignore. We don't care about the DOCTYPE for now.
274    }
275
276    fn get_template_contents(&self, target: &Self::Handle) -> Self::Handle {
277        // TODO: implement templates properly. This should allow to function like regular elements.
278        *target
279    }
280
281    fn same_node(&self, x: &Self::Handle, y: &Self::Handle) -> bool {
282        x == y
283    }
284
285    fn set_quirks_mode(&self, mode: QuirksMode) {
286        self.quirks_mode.set(mode);
287    }
288
289    fn add_attrs_if_missing(&self, target: &Self::Handle, attrs: Vec<html5ever::Attribute>) {
290        let attrs = attrs.into_iter().map(html5ever_to_blitz_attr).collect();
291        self.mutr().add_attrs_if_missing(*target, attrs);
292    }
293
294    fn remove_from_parent(&self, target: &Self::Handle) {
295        self.mutr().remove_node(*target);
296    }
297
298    fn reparent_children(&self, old_parent_id: &Self::Handle, new_parent_id: &Self::Handle) {
299        self.mutr()
300            .reparent_children(*old_parent_id, *new_parent_id);
301    }
302}
303
304#[test]
305fn parses_some_html() {
306    use blitz_dom::{BaseDocument, DocumentConfig};
307
308    let html = "<!DOCTYPE html><html><body><h1>hello world</h1></body></html>";
309    let mut doc = BaseDocument::new(DocumentConfig::default());
310    let mut mutr = doc.mutate();
311    let sink = DocumentHtmlParser::new(&mut mutr);
312
313    html5ever::parse_document(sink, Default::default())
314        .from_utf8()
315        .read_from(&mut html.as_bytes())
316        .unwrap();
317
318    drop(mutr);
319    doc.print_tree()
320
321    // Now our tree should have some nodes in it
322}