Skip to main content

flm_core/stdlib/backends/html/
page.rs

1//! The output regions of the HTML output, and the page the backend's final
2//! stage assembles from them.
3//!
4//! The entry artifact of the `html` output is a **page**: an HTML document a
5//! person can open in a browser and a validator can check. A host that wants
6//! the HTML of each document tree without a page around it reads the table
7//! `flm.output.html` ([`HtmlFragments`]) instead; that table and the page's
8//! table `flm.output.html.document` are written in the same run.
9//!
10//! The page is made in two steps:
11//!
12//! 1. [`regions`] makes the page's output regions. An output region is one
13//!    named part of an output's entry artifact, which the backend writes once
14//!    into the table `flm.output.<backend>.regions` ([`Regions`]). On this
15//!    backend the regions are the document's content (with every tree placed in
16//!    another tree written where it was placed), each piece the render places (a
17//!    [piece](crate::core::piece::Piece) is a document-level value a backend
18//!    places beside the content, such as the title), the stylesheets, the
19//!    scripts, the words of the page's title and its language. The stage `flm.html.regions`
20//!    ([`HtmlRegionsStage`](super::stages::HtmlRegionsStage)) calls it and
21//!    writes the result into the table `flm.output.html.regions`.
22//! 2. [`assemble`] writes the page from those regions; the backend's final
23//!    stage ([`HtmlFinalStage`](super::stages::HtmlFinalStage)) calls it. A
24//!    host may assemble the same regions through a template of its own instead
25//!    (see [output regions and the final
26//!    stage](crate::guide::concepts_overview#output-regions-and-the-final-stage)).
27//!
28//! # The page's layout
29//!
30//! The final stage reads the regions alone and takes no template. The page
31//! holds, in order: the document type line; `<html>`, with the `lang`
32//! attribute when there is a [`LANG`] region; `<head>`, holding the character
33//! encoding, the viewport line, the `<title>` holding the words of the
34//! [`TITLE`] region, and the stylesheets; then `<body>`, holding
35//! `<main id="flm-content" class="flm-content">` and, after it, the scripts.
36//! Inside `<main>` come the pieces placed before the content, the content, and
37//! the pieces placed after the content.
38//!
39//! The parts of a region are placed as block-level content
40//! ([`HtmlSink::markup_block`](super::HtmlSink::markup_block)), so that the
41//! line break this backend writes between two block-level tags is present
42//! where a tree begins, between two trees, and before the closing tag of the
43//! element they are written into. The bytes of each part are written
44//! unchanged, indentation included: re-indenting finished HTML would require
45//! reading output back, which this backend's sink does not allow.
46//!
47//! # Stylesheets and scripts
48//!
49//! The stylesheets and the scripts are the style and script definitions the
50//! document requires, read from the definitions table
51//! [`flm.html.definitions`](super::defs::DEFINITIONS_TABLE), in the order that
52//! table gives. The [stage that writes that table](super::defs) has already
53//! decided each definition's delivery (written into the page, loaded from an
54//! address, or left to the host), and the regions stage reads nothing else
55//! about definitions:
56//!
57//! - a text part becomes a `<style>` or a `<script>` holding it;
58//! - an address part becomes a `<link rel="stylesheet">` or a
59//!   `<script src defer>`;
60//! - a file part, which this library does not read, and a text part the page
61//!   cannot hold are left out and reported
62//!   ([`DefinitionNotInlinable`]);
63//! - a definition the host provides itself writes nothing.
64//!
65//! Every element written for a definition carries the attribute
66//! [`DEF_ATTRIBUTE`], so that a reader of the page can tell which definition it
67//! came from.
68//!
69//! # Why this module writes unescaped bytes
70//!
71//! This module writes three kinds of bytes without escaping them, each through
72//! an entry point of the [sink](super::HtmlSink) made for it:
73//!
74//! - **The HTML of each tree and each piece.** The [emitter](super::emit)
75//!   wrote those bytes through the same sink, with all document text escaped
76//!   where it was written. The page writes them unchanged as a
77//!   [`Markup`] value created by this library; escaping them again would show
78//!   the markup instead of rendering it.
79//! - **The document type line** ([`DOCTYPE`]), written the same way, because it
80//!   is not a tag and the tag builder cannot write it.
81//! - **The text of a style or script definition**, written into a `<style>` or
82//!   a `<script>` through
83//!   [`raw_text_element`](super::HtmlSink::raw_text_element). A browser reads
84//!   the content of those two elements character by character, so nothing in
85//!   it can be escaped. That text comes from a feature's author or from the
86//!   host's settings, never from a document. The only sequence it must not hold
87//!   is the element's own closing tag, which that entry point refuses; the
88//!   part is then left out and reported.
89//!
90//! An address a definition carries is written unchanged as an attribute value
91//! (escaped like every attribute value). It comes from a feature's author or a
92//! host, not from a document, so the [address policy](super::check_address), which
93//! decides which addresses a link or an image may carry, does not apply to it,
94//! and this library never fetches it.
95
96use std::collections::BTreeSet;
97
98use crate::core::artifact::ArtifactId;
99use crate::core::piece::PiecePlace;
100use crate::core::region::{CONTENT, LANG, Region, Regions, SCRIPTS, STYLES, TITLE};
101use crate::core::registry::DefContent;
102use crate::model::addr::TreeId;
103use crate::stdlib::features::metadata::TITLE as TITLE_PIECE;
104
105use super::conventions::CONTENT_CLASS;
106use super::defs::{
107    DefinitionKind, DefinitionNotInlinable, NotInlinablePart, ResolvedDefinition,
108    ResolvedDefinitions,
109};
110use super::escape::{escape_attr_into, escape_text_into};
111use super::feature::{DefinitionOverride, HtmlRenderOptions};
112use super::markup::Markup;
113use super::sink::HtmlSink;
114use super::stages::{
115    ARTIFACT_NAME, ARTIFACT_OWNER, HtmlFragments, HtmlPieces, HtmlSegment, MEDIA_TYPE,
116};
117
118/// The first line of every page, `<!DOCTYPE html>`: the document type
119/// declaration that puts a browser in its standards mode.
120///
121/// It is not a tag, so the tag builder cannot write it; [`assemble`] writes it
122/// as a [`Markup`] value created by this library. The line break after it is
123/// the one the sink writes before the `<html>` element that follows.
124pub const DOCTYPE: &str = "<!DOCTYPE html>";
125
126/// The `id` of the `<main>` element holding the document's content,
127/// `flm-content`: the same string as its class
128/// ([`CONTENT_CLASS`]), so that a host can
129/// select the content either way.
130pub const CONTENT_ID: &str = "flm-content";
131
132/// The value of the viewport line (`<meta name="viewport">`) every page
133/// carries, which tells a small screen to lay the page out at its own width
134/// rather than at a desktop's.
135pub const VIEWPORT: &str = "width=device-width, initial-scale=1";
136
137/// The attribute every element written for a style or script definition
138/// carries, holding that definition's identifier: `data-flm-def`.
139///
140/// It is the page's own attribute, not one derived from a presentation
141/// element. It lets a reader of the page (a person, or a tool that removes a
142/// definition again) tell which definition each `<style>`, `<script>` or
143/// `<link>` came from.
144pub const DEF_ATTRIBUTE: &str = "data-flm-def";
145
146/// The event that a script updating a page in place dispatches on a region's
147/// element once that element's content has been replaced:
148/// `flm:region-updated`.
149///
150/// It is one of the two conventions for a page updated in place, which the
151/// rendering guide describes ([a page updated in
152/// place](crate::guide::rendering#a-page-updated-in-place)); the other is
153/// [`ORIGINAL_HTML_ATTRIBUTE`]. The event bubbles, so it reaches a listener on
154/// the region's element and one on `document`. Its `detail` holds `region`,
155/// the `id` of the region's element, and `artifacts`, the paths of the files
156/// beside the page that changed with it. A script of the page that transforms
157/// elements in the browser listens to it to transform the region's new
158/// elements, as the formula renderer's configuration ([`super::mathjax`])
159/// does.
160pub const REGION_UPDATED_EVENT: &str = "flm:region-updated";
161
162/// The attribute in which a script that transformed an element in the browser
163/// records the HTML the element held before: `data-flm-original-html`.
164///
165/// It is the second convention for a page updated in place
166/// ([`REGION_UPDATED_EVENT`] is the first). The script that updates the page
167/// leaves an element carrying this attribute unchanged when the new HTML for
168/// that element equals the recorded HTML, and otherwise replaces the element's
169/// content, which removes the record; the script that transformed the element
170/// then transforms it again when it receives the event. The formula
171/// renderer's configuration writes this attribute on each formula just before
172/// typesetting it.
173pub const ORIGINAL_HTML_ATTRIBUTE: &str = "data-flm-original-html";
174
175/// The event that a script of the page dispatches on the element holding a
176/// copy of part of the page, once the copy is in the page:
177/// `flm:content-copied`.
178///
179/// It extends the two conventions for a page updated in place
180/// ([`REGION_UPDATED_EVENT`], [`ORIGINAL_HTML_ATTRIBUTE`]) to content that a
181/// script copies within the page, such as a popup that previews the target of
182/// a link; the rendering guide describes it ([a page updated in
183/// place](crate::guide::rendering#a-page-updated-in-place)). The copy holds
184/// none of the page's identifiers and keeps the record of each element it
185/// copies. The event bubbles, and its `detail` holds nothing. A script of the
186/// page that transforms elements in the browser listens to it to transform the
187/// elements of the copy that are not transformed, as the formula renderer's
188/// configuration ([`super::mathjax`]) does.
189pub const CONTENT_COPIED_EVENT: &str = "flm:content-copied";
190
191/// The result of [`regions`]: the output regions of the HTML output, and what
192/// could not be written into them, for the regions stage to report.
193#[derive(Debug, Default, Clone, PartialEq, Eq)]
194pub struct HtmlRegions {
195    /// The output regions ([`crate::core::region`]): the content, each piece,
196    /// the stylesheets, the scripts, the title and, when the options give one,
197    /// the language.
198    pub regions: Regions,
199    /// The trees that a `flm.pres.subtree` node placed and that have no HTML,
200    /// in the order encountered; the regions stage reports each as
201    /// [`flm.html.missing-subtree`](super::stages::MissingSubtree).
202    pub missing: Vec<TreeId>,
203    /// The trees that a `flm.pres.subtree` node placed while they were already
204    /// being written (a placement cycle), in the order encountered; the regions
205    /// stage reports each as
206    /// [`flm.html.subtree-cycle`](super::stages::SubtreeCycle).
207    pub cycles: Vec<TreeId>,
208    /// The parts of required definitions that could not be written, in the
209    /// order encountered; the regions stage reports each as
210    /// [`flm.html.definition-not-inlinable`](super::defs::DefinitionNotInlinable).
211    pub not_inlinable: Vec<DefinitionNotInlinable>,
212}
213
214/// Makes the output regions of an HTML page from the HTML of the trees, the
215/// HTML of the pieces, the definitions table, the tree order and the render
216/// options. The regions stage
217/// ([`HtmlRegionsStage`](super::stages::HtmlRegionsStage)) calls it.
218///
219/// It makes these regions, in this order:
220///
221/// - [`CONTENT`], from `fragments`: the trees listed in `order`, in that order.
222///   Each part of the region is one segment of HTML a tree's emission wrote,
223///   so that the final stage places each on a line of its own. A tree that a
224///   `flm.pres.subtree` node places in another tree is written where it was
225///   placed, and not again at the top level, even when `order` lists it.
226///   Trees that are placed only by one another, in a cycle, and by no other
227///   tree, are written at the top level after the other trees, so that their
228///   content still reaches the page.
229/// - One region per piece of `pieces`, with the piece's place and words.
230/// - [`STYLES`] and [`SCRIPTS`], from `definitions`: one part per element
231///   written for a part of a definition (a `<style>`, a `<link>` or a
232///   `<script>`).
233/// - [`TITLE`]: the words of the title piece
234///   ([`flm.metadata.title`](crate::stdlib::features::metadata::TITLE)) when `pieces`
235///   holds it and its words are not empty, otherwise the title of `options`
236///   ([`HtmlRenderOptions::title`]).
237/// - [`LANG`], when `options` gives a language ([`HtmlRenderOptions::lang`]).
238///
239/// The placement that closes a cycle, a placed tree with no HTML, and a
240/// definition part the page cannot hold write nothing and are recorded in the
241/// result ([`HtmlRegions`]; a cycle in [`HtmlRegions::cycles`]). A tree with no HTML at the top level writes nothing and
242/// is not recorded, because the failure that left it without HTML was reported
243/// where it happened.
244pub fn regions(
245    fragments: &HtmlFragments,
246    pieces: &HtmlPieces,
247    definitions: &ResolvedDefinitions,
248    order: &[TreeId],
249    options: &HtmlRenderOptions,
250) -> HtmlRegions {
251    let mut content = Content {
252        parts: Vec::new(),
253        fragments,
254        writing: Vec::new(),
255        written: BTreeSet::new(),
256        missing: Vec::new(),
257        cycles: Vec::new(),
258    };
259    let placed = placed_trees(fragments);
260    for id in order {
261        if content.written.contains(id) || placed.contains(id) {
262            continue;
263        }
264        content.top_level(*id);
265    }
266    // A tree every other tree's placement left unwritten — trees placing each
267    // other in a cycle — is written at the top level, so that its content is
268    // in the page and the cycle is reported rather than swallowed.
269    for id in order {
270        if !content.written.contains(id) {
271            content.top_level(*id);
272        }
273    }
274    let mut not_inlinable = Vec::new();
275    let styles = definition_parts(definitions, DefinitionKind::Style, &mut not_inlinable);
276    let scripts = definition_parts(definitions, DefinitionKind::Script, &mut not_inlinable);
277    let mut regions =
278        Regions::new(ArtifactId::new(ARTIFACT_OWNER, ARTIFACT_NAME), MEDIA_TYPE);
279    regions.regions.push(Region::new(CONTENT, content.parts));
280    for piece in &pieces.pieces {
281        let parts = piece
282            .fragment
283            .segments
284            .iter()
285            .filter_map(|segment| match segment {
286                HtmlSegment::Html(html) => Some(html.clone()),
287                HtmlSegment::Tree(_) => None,
288            })
289            .collect();
290        regions.regions.push(Region::piece(
291            piece.name.clone(),
292            piece.place,
293            parts,
294            piece.words.clone(),
295        ));
296    }
297    regions.regions.push(Region::new(STYLES, styles));
298    regions.regions.push(Region::new(SCRIPTS, scripts));
299    let title = pieces
300        .pieces
301        .iter()
302        .find(|piece| piece.name.as_str() == TITLE_PIECE && !piece.words.is_empty())
303        .map_or_else(|| options.title.clone(), |piece| piece.words.clone());
304    let mut part = String::new();
305    escape_text_into(&mut part, &title);
306    regions.regions.push(Region::with_words(TITLE, part, title));
307    if let Some(lang) = &options.lang {
308        let mut part = String::new();
309        escape_attr_into(&mut part, lang);
310        regions.regions.push(Region::with_words(LANG, part, lang.clone()));
311    }
312    let Content { missing, cycles, .. } = content;
313    HtmlRegions { regions, missing, cycles, not_inlinable }
314}
315
316/// Returns the page the backend's final stage writes, assembled from
317/// `regions`: the stylesheets in the head; in `<main>`, the pieces placed
318/// before the content, the content and the pieces placed after it; the
319/// scripts at the end of the body; the language and the title's words from
320/// the regions [`LANG`] and [`TITLE`]. The [module
321/// documentation](self#the-pages-layout) gives the full layout.
322///
323/// A region missing from `regions` contributes nothing. The page ends with a
324/// line break.
325pub fn assemble(regions: &Regions) -> String {
326    let words = |name: &str| regions.get(name).and_then(|region| region.words.as_deref());
327    let mut sink = HtmlSink::new();
328    sink.markup(&Markup::from_library(DOCTYPE));
329    let mut html = sink.open_block("html");
330    if let Some(lang) = words(LANG) {
331        html = html.attr("lang", lang);
332    }
333    html.finish();
334    sink.open_block("head").finish();
335    sink.void_block("meta").attr("charset", "utf-8").finish();
336    sink.void_block("meta").attr("name", "viewport").attr("content", VIEWPORT).finish();
337    sink.open_block("title").finish();
338    sink.text(words(TITLE).unwrap_or_default());
339    sink.close();
340    place(&mut sink, regions.get(STYLES));
341    sink.close();
342    sink.open_block("body").finish();
343    sink.open_block("main").class([CONTENT_CLASS]).attr("id", CONTENT_ID).finish();
344    for piece in regions.pieces_at(PiecePlace::BeforeContent) {
345        place(&mut sink, Some(piece));
346    }
347    place(&mut sink, regions.get(CONTENT));
348    for piece in regions.pieces_at(PiecePlace::AfterContent) {
349        place(&mut sink, Some(piece));
350    }
351    sink.close();
352    place(&mut sink, regions.get(SCRIPTS));
353    sink.close();
354    sink.close();
355    let mut text = sink.finish();
356    text.push('\n');
357    text
358}
359
360/// Writes every part of `region` as block-level content, each on a line of
361/// its own; writes nothing when `region` is `None`.
362fn place(sink: &mut HtmlSink, region: Option<&Region>) {
363    let Some(region) = region else { return };
364    for part in &region.parts {
365        // The bytes this backend wrote, through the same sink, with every
366        // piece of document text already escaped. They are placed as
367        // block-level content, so that the line break between two
368        // block-level tags is there at the seam as it is inside a tree; the
369        // bytes themselves keep the indentation they were written with, since
370        // re-indenting them where they land would be a pass over finished
371        // output.
372        sink.markup_block(&Markup::from_library(part.clone()));
373    }
374}
375
376/// Returns the parts of every definition of kind `kind` in `definitions`, in
377/// the table's order: one element per part, each written by a sink of its
378/// own. A part that cannot be written is pushed onto `not_inlinable` instead.
379fn definition_parts(
380    definitions: &ResolvedDefinitions,
381    kind: DefinitionKind,
382    not_inlinable: &mut Vec<DefinitionNotInlinable>,
383) -> Vec<String> {
384    let mut parts = Vec::new();
385    for definition in definitions.of_kind(kind) {
386        // A definition the host supplies itself writes nothing.
387        let DefinitionOverride::Parts(contents) = &definition.delivery else { continue };
388        for content in contents {
389            let mut sink = HtmlSink::new();
390            let written = match content {
391                DefContent::Inline(text) => definition_text(&mut sink, definition, text),
392                DefContent::Url(address) => {
393                    definition_address(&mut sink, definition, address);
394                    Ok(())
395                }
396                // This library opens no file. The host reads it and delivers
397                // its content itself, through the `definitions` option. One
398                // condition serves this and the refused text below, since the
399                // recovery is the same.
400                DefContent::File(path) => Err(DefinitionNotInlinable {
401                    definition: definition.id.to_string(),
402                    part: NotInlinablePart::File { path: path.clone() },
403                }),
404                // The resolve stage puts the table's text in the part's
405                // place; a part still naming its table came from a table built
406                // by other means, and is refused as a file is.
407                DefContent::Table(table) => Err(DefinitionNotInlinable {
408                    definition: definition.id.to_string(),
409                    part: NotInlinablePart::Table { table: table.to_string() },
410                }),
411            };
412            match written {
413                Ok(()) => parts.push(sink.finish()),
414                Err(refused) => not_inlinable.push(refused),
415            }
416        }
417    }
418    parts
419}
420
421/// Writes a text part as a `<style>` or a `<script>` holding it.
422///
423/// The content of those two elements cannot be escaped, because a browser
424/// reads it character by character, so the sink refuses text holding the
425/// element's own closing tag; the refusal is returned and nothing is written.
426fn definition_text(
427    sink: &mut HtmlSink,
428    definition: &ResolvedDefinition,
429    text: &str,
430) -> Result<(), DefinitionNotInlinable> {
431    let tag = match definition.kind {
432        DefinitionKind::Style => "style",
433        DefinitionKind::Script => "script",
434    };
435    // The one place this backend writes bytes that were never escaped and are
436    // not its own: a definition's content, written by a feature's author or
437    // put here by the host's settings.
438    sink.raw_text_element(tag, &[(DEF_ATTRIBUTE, definition.id.as_str())], text).map_err(
439        |refused| DefinitionNotInlinable {
440            definition: definition.id.to_string(),
441            part: NotInlinablePart::ClosingTag { tag: refused.tag, at: refused.at },
442        },
443    )
444}
445
446/// Writes an address part as a `<link rel="stylesheet">` or a
447/// `<script src defer>`.
448///
449/// The address comes from a feature's author or a host, so it is written
450/// unchanged (escaped as an attribute value); this library never fetches it.
451/// A script is written with `defer`, which lets a browser finish reading the
452/// page before the script runs and runs deferred scripts in the order they
453/// were written.
454fn definition_address(sink: &mut HtmlSink, definition: &ResolvedDefinition, address: &str) {
455    match definition.kind {
456        DefinitionKind::Style => {
457            sink.void_block("link")
458                .attr("rel", "stylesheet")
459                .attr("href", address)
460                .attr(DEF_ATTRIBUTE, definition.id.as_str())
461                .finish();
462        }
463        DefinitionKind::Script => {
464            sink.open_block("script")
465                .attr("src", address)
466                .flag("defer")
467                .attr(DEF_ATTRIBUTE, definition.id.as_str())
468                .finish();
469            sink.close();
470        }
471    }
472}
473
474/// Returns the trees that another tree's HTML places (a tree placing itself is
475/// a cycle: it is written at the top level and reported).
476fn placed_trees(fragments: &HtmlFragments) -> BTreeSet<TreeId> {
477    let mut placed = BTreeSet::new();
478    for (id, fragment) in &fragments.trees {
479        for segment in &fragment.segments {
480            if let HtmlSegment::Tree(tree) = segment {
481                if tree != id {
482                    placed.insert(*tree);
483                }
484            }
485        }
486    }
487    placed
488}
489
490/// The content region while it is being made.
491struct Content<'f> {
492    parts: Vec<String>,
493    fragments: &'f HtmlFragments,
494    /// The trees being written, outermost first (the placement cycle guard).
495    writing: Vec<TreeId>,
496    /// The trees written so far, at the top level or where they were placed.
497    written: BTreeSet<TreeId>,
498    missing: Vec<TreeId>,
499    cycles: Vec<TreeId>,
500}
501
502impl Content<'_> {
503    /// One of the document's own trees, at the top level of the content.
504    ///
505    /// A tree with no HTML — one whose lowering or emission failed — writes
506    /// nothing and is not reported here: the failure was reported where it
507    /// happened.
508    fn top_level(&mut self, id: TreeId) {
509        self.written.insert(id);
510        if self.fragments.trees.contains_key(&id) {
511            self.tree(id);
512        }
513    }
514
515    /// A tree another tree places, written where it was placed.
516    ///
517    /// Unlike a tree of the document's own, one that is placed and has no HTML
518    /// is reported: the node that placed it asked for something the page could
519    /// not give.
520    fn placed(&mut self, id: TreeId) {
521        if self.writing.contains(&id) {
522            self.cycles.push(id);
523            return;
524        }
525        if !self.fragments.trees.contains_key(&id) {
526            self.missing.push(id);
527            return;
528        }
529        self.tree(id);
530    }
531
532    /// One tree's HTML, with the trees it places written where they are
533    /// placed.
534    fn tree(&mut self, id: TreeId) {
535        let Some(fragment) = self.fragments.trees.get(&id) else { return };
536        self.writing.push(id);
537        self.written.insert(id);
538        for segment in &fragment.segments {
539            match segment {
540                HtmlSegment::Html(html) => self.parts.push(html.clone()),
541                HtmlSegment::Tree(placed) => self.placed(*placed),
542            }
543        }
544        self.writing.pop();
545    }
546}