Skip to main content

noonoo_engine/
lib.rs

1//! # noonoo-engine
2//!
3//! Orchestration: the crate that gives you a *working* page — the equivalent of
4//! the replaced engine's `BaseDocument` / `HtmlDocument`, but assembled from the
5//! small crates instead of a monolith.
6//!
7//! An [`Engine`] owns a [`noonoo_dom::Document`], the [`Stylesheet`]s parsed out
8//! of the document, and (once the `resolve` feature is on) the layout caches
9//! that keep it presentable. Each of those abilities is a different crate
10//! underneath, and — crucially — the parse and style-ingest steps are **ours**:
11//! [`noonoo_html`] and [`noonoo_css`], not a borrowed parser.
12//!
13//! ## The `Send` question
14//!
15//! The replaced engine's `Document` was `!Send`, which blocked running a page
16//! off the UI thread and forced consumers into a texture-overlay workaround for
17//! sub-documents. Noonoo's tree owns no `Rc`/`RefCell` and promises nothing
18//! unsafe, so an engine is `Send` whenever its payload is.
19
20#![forbid(unsafe_code)]
21#![warn(missing_docs)]
22
23use noonoo_css::Stylesheet;
24use noonoo_dom::{Change, Changes, Document, NodeData, NodeId};
25use noonoo_style::{Cascade, Interaction, Styles, Viewport};
26
27mod resources;
28
29/// A page: a DOM document, its stylesheets, and (later) its resolved layout.
30pub struct Engine {
31    dom: Document,
32    stylesheets: Vec<Stylesheet>,
33    /// The `<style>` elements the stylesheets came from, in order.
34    style_elements: Vec<NodeId>,
35    /// The stylesheets prepared for [`Engine::restyle`], once it has run.
36    cascade: Option<Cascade>,
37    /// Subresources: the loader, what was asked of it, and what arrived.
38    resources: resources::Resources,
39}
40
41impl Default for Engine {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl Engine {
48    /// Create an empty engine with a fresh document.
49    pub fn new() -> Self {
50        Self {
51            dom: Document::new(),
52            stylesheets: Vec::new(),
53            style_elements: Vec::new(),
54            cascade: None,
55            resources: resources::Resources::default(),
56        }
57    }
58
59    /// Parse `html` into a fresh engine, collecting its stylesheets.
60    pub fn from_html(html: &str) -> Self {
61        let mut engine = Self {
62            dom: noonoo_html::parse(html),
63            ..Self::new()
64        };
65        engine.refresh_stylesheets();
66        engine
67    }
68
69    /// Borrow the underlying DOM document.
70    pub fn dom(&self) -> &Document {
71        &self.dom
72    }
73
74    /// Mutably borrow the underlying DOM document.
75    pub fn dom_mut(&mut self) -> &mut Document {
76        &mut self.dom
77    }
78
79    /// The stylesheets collected from the document's `<style>` elements.
80    pub fn stylesheets(&self) -> &[Stylesheet] {
81        &self.stylesheets
82    }
83
84    /// Re-scan the document's `<style>` elements for stylesheets.
85    pub fn refresh_stylesheets(&mut self) {
86        (self.style_elements, self.stylesheets) = collect_stylesheets(&self.dom);
87        self.cascade = None;
88    }
89
90    /// Bring `styles` up to date with the document, its stylesheets,
91    /// `viewport` and `interaction`, restyling only what changed since the
92    /// last call. Returns how many times an element was styled.
93    ///
94    /// Start from [`Styles::default`]: the first call computes everything.
95    /// After that, edits made through [`Document::mutate`] restyle only the
96    /// subtrees they can reach, and a hover, focus or press moving restyles
97    /// the nodes it moved between. An edit to a `<style>` element, a new
98    /// viewport, or raw writes through [`Document::tree_mut`] restyle
99    /// everything.
100    pub fn restyle(
101        &mut self,
102        styles: &mut Styles,
103        viewport: noonoo_geometry::Size,
104        interaction: Interaction,
105    ) -> usize {
106        let changes = self.dom.take_changes();
107        if self.touches_stylesheets(&changes) {
108            self.refresh_stylesheets();
109        }
110        let viewport = Viewport {
111            width: viewport.width,
112            height: viewport.height,
113        };
114        match &self.cascade {
115            Some(cascade) if cascade.viewport() == viewport => {
116                cascade.restyle(styles, &self.dom, interaction, &changes)
117            }
118            _ => {
119                let cascade = Cascade::new(&self.stylesheets, viewport);
120                *styles = cascade.compute(&self.dom, interaction);
121                self.cascade = Some(cascade);
122                self.dom.elements().len()
123            }
124        }
125    }
126
127    /// Whether `changes` may have changed what the `<style>` elements say:
128    /// text inside one changed, or one was added or removed.
129    fn touches_stylesheets(&self, changes: &Changes) -> bool {
130        if changes.overflowed() {
131            return true;
132        }
133        let in_style = |node: NodeId| {
134            std::iter::once(node)
135                .chain(self.dom.tree().ancestors(node))
136                .any(|id| is_style(&self.dom, id))
137        };
138        let mut moved = false;
139        for change in changes.iter() {
140            match *change {
141                // `collect_stylesheets` reads no attributes.
142                Change::Attributes(_) => {}
143                Change::Text(node) if in_style(node) => return true,
144                Change::Text(_) => {}
145                Change::Children(node) if in_style(node) => return true,
146                Change::Children(_) => moved = true,
147            }
148        }
149        moved && style_elements(&self.dom) != self.style_elements
150    }
151
152    /// The `@font-face` descriptors collected from the stylesheets, in source
153    /// order.
154    ///
155    /// A host loads each `src` (`noonoo-net` covers `file:` and `data:`),
156    /// parses the bytes with `noonoo-ttf`'s `Font`, and registers the face
157    /// with a `FontSet`; see the `noonoo` CLI's `--paint` for the pattern.
158    pub fn font_faces(&self) -> Vec<noonoo_css::FontFace> {
159        self.stylesheets
160            .iter()
161            .flat_map(|sheet| sheet.font_faces())
162            .collect()
163    }
164
165    /// Compute every element's style: cascade the collected stylesheets over the
166    /// user-agent sheet and any inline `style` attributes.
167    ///
168    /// Viewport-relative units resolve against
169    /// [`noonoo_style::Viewport::DEFAULT`]; [`Engine::compute_styles_for`] uses a
170    /// real viewport instead.
171    pub fn compute_styles(&self) -> noonoo_style::Styles {
172        noonoo_style::compute(&self.dom, &self.stylesheets)
173    }
174
175    /// Compute every element's style against `viewport`, so `vw`/`vh` and
176    /// `calc(100vw - 2rem)` resolve correctly.
177    pub fn compute_styles_for(&self, viewport: noonoo_geometry::Size) -> noonoo_style::Styles {
178        self.compute_styles_in(viewport, noonoo_style::Interaction::default())
179    }
180
181    /// Compute every element's style against `viewport` and the interactive
182    /// state, so `:hover`/`:focus`/`:active` style the elements they name.
183    pub fn compute_styles_in(
184        &self,
185        viewport: noonoo_geometry::Size,
186        interaction: noonoo_style::Interaction,
187    ) -> noonoo_style::Styles {
188        noonoo_style::compute_interactive(
189            &self.dom,
190            &self.stylesheets,
191            noonoo_style::Viewport {
192                width: viewport.width,
193                height: viewport.height,
194            },
195            interaction,
196        )
197    }
198
199    /// Lay the document out for a viewport, using the given text shaper.
200    pub fn layout(
201        &self,
202        viewport: noonoo_geometry::Size,
203        shaper: &dyn noonoo_layout::Shaper,
204    ) -> noonoo_layout::LayoutTree {
205        let styles = self.compute_styles_for(viewport);
206        noonoo_layout::layout_with_images(&self.dom, &styles, viewport, shaper, self.images())
207    }
208
209    /// Lay out and paint the document, returning the render command stream.
210    pub fn paint(
211        &self,
212        viewport: noonoo_geometry::Size,
213        shaper: &dyn noonoo_layout::Shaper,
214    ) -> noonoo_paint::CommandList {
215        self.paint_with(viewport, shaper, &noonoo_paint::TextRuns)
216    }
217
218    /// Lay out and paint the document, drawing text with `glyphs`.
219    ///
220    /// Use this with a font-backed shaper and matching glyph renderer to render
221    /// vector text (see `noonoo-ttf`'s `FontShaper` + `OutlineGlyphs`).
222    pub fn paint_with(
223        &self,
224        viewport: noonoo_geometry::Size,
225        shaper: &dyn noonoo_layout::Shaper,
226        glyphs: &dyn noonoo_paint::Glyphs,
227    ) -> noonoo_paint::CommandList {
228        let styles = self.compute_styles_for(viewport);
229        let layout =
230            noonoo_layout::layout_with_images(&self.dom, &styles, viewport, shaper, self.images());
231        noonoo_paint::paint_with(&styles, &layout, glyphs)
232    }
233
234    /// Consume the engine and return its document.
235    pub fn into_dom(self) -> Document {
236        self.dom
237    }
238}
239
240/// Collect and parse the `<style>` elements in a document.
241///
242/// A `<style>` whose text is empty or fails to parse is skipped; a page with a
243/// broken stylesheet still yields its DOM.
244/// The document's `<style>` elements, and the stylesheets parsed from them.
245fn collect_stylesheets(dom: &Document) -> (Vec<NodeId>, Vec<Stylesheet>) {
246    let elements = style_elements(dom);
247    let sheets = elements
248        .iter()
249        .filter_map(|&id| {
250            let text = dom.text_content(id);
251            if text.trim().is_empty() {
252                None
253            } else {
254                Stylesheet::parse(&text).ok()
255            }
256        })
257        .collect();
258    (elements, sheets)
259}
260
261fn style_elements(dom: &Document) -> Vec<NodeId> {
262    dom.get_elements_by_tag_name("style")
263}
264
265fn is_style(dom: &Document, id: NodeId) -> bool {
266    matches!(dom.node(id), Some(NodeData::Element(element)) if element.name == "style")
267}
268
269/// The version of this crate, taken from the workspace.
270pub const VERSION: &str = env!("CARGO_PKG_VERSION");
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn new_engine_has_a_document_root() {
278        let engine = Engine::new();
279        let root = engine.dom().root();
280        assert!(engine.dom().tree().contains(root));
281        assert!(engine.stylesheets().is_empty());
282    }
283
284    #[test]
285    fn from_html_parses_the_tree() {
286        let engine = Engine::from_html("<div id=\"box\"><span>hi</span></div>");
287        let box_id = engine.dom().get_element_by_id("box").unwrap();
288        assert_eq!(engine.dom().element(box_id).unwrap().name, "div");
289    }
290
291    #[test]
292    fn collects_style_sheets() {
293        let engine = Engine::from_html("<style>body { color: red; margin: 0 }</style><p>hi</p>");
294        assert_eq!(engine.stylesheets().len(), 1);
295        assert_eq!(engine.stylesheets()[0].rules.len(), 1);
296    }
297
298    #[test]
299    fn collects_font_face_descriptors() {
300        let engine = Engine::from_html(
301            "<style>@font-face { font-family: A; src: url(a.ttf); font-weight: bold }</style>
302             <style>@font-face { font-family: B; src: url(b.ttf) url(b.woff) }</style>",
303        );
304        let faces = engine.font_faces();
305        assert_eq!(faces.len(), 2);
306        assert_eq!(faces[0].family, "A");
307        assert_eq!(faces[0].weight, 700);
308        assert_eq!(faces[1].src, vec!["b.ttf".to_owned(), "b.woff".to_owned()]);
309    }
310
311    #[test]
312    fn skips_empty_and_broken_stylesheets() {
313        let engine = Engine::from_html(
314            "<style></style><style>a { color: red</style><style>b { color: blue }</style>",
315        );
316        // The empty one is dropped, the unclosed one fails to parse, the valid one stays.
317        assert_eq!(engine.stylesheets().len(), 1);
318    }
319
320    #[test]
321    fn computes_styles_for_a_page() {
322        let engine = Engine::from_html(
323            "<style>p { display: flex; color: red; margin: 5px }</style><p>x</p>",
324        );
325        let styles = engine.compute_styles();
326        let p = engine.dom().get_elements_by_tag_name("p")[0];
327        let style = styles.get(p).unwrap();
328        assert_eq!(style.display, noonoo_style::Display::Flex);
329        assert_eq!(style.color, noonoo_css::Color::rgb(255, 0, 0));
330        assert_eq!(style.margin.top, noonoo_style::Dimension::Px(5.0));
331    }
332
333    #[test]
334    fn lays_out_a_page() {
335        let engine = Engine::from_html(
336            "<style>body { margin: 0 } #a { height: 40px }</style><div id=\"a\"></div>",
337        );
338        let tree = engine.layout(
339            noonoo_geometry::Size::new(300.0, 200.0),
340            &noonoo_layout::MetricShaper,
341        );
342        let a = engine.dom().get_element_by_id("a").unwrap();
343        let box_ = tree.get(a).unwrap();
344        assert_eq!(box_.rect.width, 300.0);
345        assert_eq!(box_.rect.height, 40.0);
346    }
347
348    #[test]
349    fn paints_a_page() {
350        let engine = Engine::from_html(
351            "<style>#a { background-color: #102030 }</style><div id=\"a\">hi</div>",
352        );
353        let list = engine.paint(
354            noonoo_geometry::Size::new(200.0, 100.0),
355            &noonoo_layout::MetricShaper,
356        );
357        assert!(!list.is_empty());
358    }
359}