typst-html 0.15.1

Typst's HTML exporter.
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
408
409
410
411
412
413
414
use std::fmt::Write;

use comemo::{Track, Tracked};
use ecow::{EcoString, eco_format};
use typst_library::diag::{At, SourceResult, StrResult, bail};
use typst_library::foundations::Repr;
use typst_library::model::LateLinkResolver;
use typst_syntax::Span;

use crate::{
    HtmlDocument, HtmlElement, HtmlFrame, HtmlNode, HtmlTag, attr, charsets, property,
    tag,
};

/// Settings for HTML export.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
pub struct HtmlOptions {
    /// Whether to format the HTML in a human-readable way.
    pub pretty: bool,
}

/// Encodes an HTML document into a string.
pub fn html(document: &HtmlDocument, options: &HtmlOptions) -> SourceResult<String> {
    let link_resolver = LateLinkResolver::new(None, document.introspector().as_ref());
    let w = Writer::new(link_resolver.track(), options.pretty);
    html_impl(w, document.root())
}

/// Encodes an HTML root element into a string as part of a bundle.
///
/// See `export_html` in `typst-bundle` for more details on why this takes the
/// root element instead of the document.
pub fn html_in_bundle(
    root: &HtmlElement,
    options: &HtmlOptions,
    link_resolver: Tracked<LateLinkResolver>,
) -> SourceResult<String> {
    let w = Writer::new(link_resolver, options.pretty);
    html_impl(w, root)
}

/// The shared implementation of [`html`] and [`html_in_bundle`].
fn html_impl(mut w: Writer, root: &HtmlElement) -> SourceResult<String> {
    w.buf.push_str("<!DOCTYPE html>");
    write_indent(&mut w);
    write_element(&mut w, root)?;
    if w.pretty {
        w.buf.push('\n');
    }
    Ok(w.buf)
}

/// Encodes HTML.
struct Writer<'a> {
    /// The output buffer.
    buf: String,
    /// The current indentation level
    level: usize,
    /// Used to resolve links between the document and contained frames as well
    /// as cross-document links in bundle export.
    link_resolver: Tracked<'a, LateLinkResolver<'a>>,
    /// Whether pretty printing is enabled.
    pretty: bool,
}

impl<'a> Writer<'a> {
    /// Creates a new writer.
    fn new(link_resolver: Tracked<'a, LateLinkResolver<'a>>, pretty: bool) -> Self {
        Self {
            buf: String::new(),
            level: 0,
            link_resolver,
            pretty,
        }
    }
}

/// Writes a newline and indent, if pretty printing is enabled.
fn write_indent(w: &mut Writer) {
    if w.pretty {
        w.buf.push('\n');
        for _ in 0..w.level {
            w.buf.push_str("  ");
        }
    }
}

/// Encodes an HTML node into the writer.
fn write_node(w: &mut Writer, node: &HtmlNode, escape_text: bool) -> SourceResult<()> {
    match node {
        HtmlNode::Tag(_) => {}
        HtmlNode::Text(text, span) => write_text(w, text, *span, escape_text)?,
        HtmlNode::Element(element) => write_element(w, element)?,
        HtmlNode::Frame(frame) => write_frame(w, frame),
    }
    Ok(())
}

/// Encodes plain text into the writer.
fn write_text(w: &mut Writer, text: &str, span: Span, escape: bool) -> SourceResult<()> {
    for c in text.chars() {
        if escape || !charsets::is_valid_in_normal_element_text(c) {
            write_escape(w, c).at(span)?;
        } else {
            w.buf.push(c);
        }
    }
    Ok(())
}

/// Encodes one element into the writer.
fn write_element(w: &mut Writer, element: &HtmlElement) -> SourceResult<()> {
    w.buf.push('<');
    w.buf.push_str(&element.tag.resolve());

    for (attr, value) in &element.attrs.0 {
        w.buf.push(' ');
        w.buf.push_str(&attr.resolve());

        // If the string is empty, we can use shorthand syntax.
        // `<elem attr="">..</div` is equivalent to `<elem attr>..</div>`
        if !value.is_empty() {
            w.buf.push('=');
            w.buf.push('"');
            for c in value.chars() {
                if charsets::is_valid_in_attribute_value(c) {
                    w.buf.push(c);
                } else {
                    write_escape(w, c).at(element.span)?;
                }
            }
            w.buf.push('"');
        }
    }

    if tag::is_foreign_self_closing(element.tag) {
        w.buf.push('/');
    }

    w.buf.push('>');

    if tag::is_void(element.tag) || tag::is_foreign_self_closing(element.tag) {
        if !element.children.is_empty() {
            bail!(element.span, "HTML void elements must not have children");
        }
        return Ok(());
    }

    // See HTML spec § 13.1.2.5.
    if matches!(element.tag, tag::pre | tag::textarea) && starts_with_newline(element) {
        w.buf.push('\n');
    }

    if tag::is_raw(element.tag) {
        write_raw(w, element)?;
    } else if tag::is_escapable_raw(element.tag) {
        write_escapable_raw(w, element)?;
    } else if !element.children.is_empty() {
        write_children(w, element)?;
    }

    w.buf.push_str("</");
    w.buf.push_str(&element.tag.resolve());
    w.buf.push('>');

    Ok(())
}

/// Encodes the children of an element.
fn write_children(w: &mut Writer, element: &HtmlElement) -> SourceResult<()> {
    let pretty = w.pretty;
    let pretty_inside = allows_pretty_inside(element.tag)
        && element.children.iter().any(|node| match node {
            HtmlNode::Element(child) => wants_pretty_around(child),
            HtmlNode::Frame(_) => true,
            _ => false,
        });

    w.pretty &= pretty_inside;
    let mut indent = w.pretty;

    w.level += 1;
    for c in &element.children {
        let pretty_around = match c {
            HtmlNode::Tag(_) => continue,
            HtmlNode::Element(child) => w.pretty && wants_pretty_around(child),
            HtmlNode::Text(..) | HtmlNode::Frame(_) => false,
        };

        if core::mem::take(&mut indent) || pretty_around {
            write_indent(w);
        }
        write_node(w, c, element.pre_span)?;
        indent = pretty_around;
    }
    w.level -= 1;

    write_indent(w);
    w.pretty = pretty;

    Ok(())
}

/// Whether the first character in the element is a newline.
fn starts_with_newline(element: &HtmlElement) -> bool {
    for child in &element.children {
        match child {
            HtmlNode::Tag(_) => {}
            HtmlNode::Text(text, _) => return text.starts_with(['\n', '\r']),
            _ => return false,
        }
    }
    false
}

/// Encodes the contents of a raw text element.
fn write_raw(w: &mut Writer, element: &HtmlElement) -> SourceResult<()> {
    let text = collect_raw_text(element)?;

    if let Some(closing) = find_closing_tag(&text, element.tag) {
        bail!(
            element.span,
            "HTML raw text element cannot contain its own closing tag";
            hint: "the sequence `{closing}` appears in the raw text";
        )
    }

    let mode = if w.pretty { RawMode::of(element, &text) } else { RawMode::Keep };
    match mode {
        RawMode::Keep => {
            w.buf.push_str(&text);
        }
        RawMode::Wrap => {
            w.buf.push('\n');
            w.buf.push_str(&text);
            write_indent(w);
        }
        RawMode::Indent => {
            w.level += 1;
            for line in text.lines() {
                write_indent(w);
                w.buf.push_str(line);
            }
            w.level -= 1;
            write_indent(w);
        }
    }

    Ok(())
}

/// Encodes the contents of an escapable raw text element.
fn write_escapable_raw(w: &mut Writer, element: &HtmlElement) -> SourceResult<()> {
    walk_raw_text(element, |piece, span| write_text(w, piece, span, false))
}

/// Collects the textual contents of a raw text element.
fn collect_raw_text(element: &HtmlElement) -> SourceResult<String> {
    let mut text = String::new();
    walk_raw_text(element, |piece, span| {
        if let Some(c) = piece.chars().find(|&c| !charsets::is_w3c_text_char(c)) {
            return Err(unencodable(c)).at(span);
        }
        text.push_str(piece);
        Ok(())
    })?;
    Ok(text)
}

/// Iterates over the textual contents of a raw text element.
fn walk_raw_text(
    element: &HtmlElement,
    mut f: impl FnMut(&str, Span) -> SourceResult<()>,
) -> SourceResult<()> {
    for c in &element.children {
        match c {
            HtmlNode::Tag(_) => continue,
            HtmlNode::Text(text, span) => f(text, *span)?,
            HtmlNode::Element(HtmlElement { span, .. })
            | HtmlNode::Frame(HtmlFrame { span, .. }) => {
                bail!(*span, "HTML raw text element cannot have non-text children")
            }
        }
    }
    Ok(())
}

/// Finds a closing sequence for the given tag in the text, if it exists.
///
/// See HTML spec § 13.1.2.6.
fn find_closing_tag(text: &str, tag: HtmlTag) -> Option<&str> {
    let s = tag.resolve();
    let len = s.len();
    text.match_indices("</").find_map(|(i, _)| {
        let rest = &text[i + 2..];
        let disallowed = rest.len() >= len
            && rest[..len].eq_ignore_ascii_case(&s)
            && rest[len..].starts_with(['\t', '\n', '\u{c}', '\r', ' ', '>', '/']);
        disallowed.then(|| &text[i..i + 2 + len])
    })
}

/// How to format the contents of a raw text element.
enum RawMode {
    /// Just don't touch it.
    Keep,
    /// Newline after the opening and newline + indent before the closing tag.
    Wrap,
    /// Newlines after opening and before closing tag and each line indented.
    Indent,
}

impl RawMode {
    fn of(element: &HtmlElement, text: &str) -> Self {
        match element.tag {
            tag::script
                if !element.attrs.0.iter().any(|(attr, value)| {
                    *attr == attr::r#type && value != "text/javascript"
                }) =>
            {
                // Template literals can be multi-line, so indent may change
                // the semantics of the JavaScript.
                if text.contains('`') { Self::Wrap } else { Self::Indent }
            }
            tag::style => Self::Indent,
            _ => Self::Keep,
        }
    }
}

/// Whether we are allowed to add an extra newline at the start and end of the
/// element's contents.
///
/// Technically, users can change CSS `display` properties such that the
/// insertion of whitespace may actually impact the visual output. For example,
/// <https://www.w3.org/TR/css-text-3/#example-af2745cd> shows how adding CSS
/// rules to `<p>` can make it sensitive to whitespace. For this reason, we
/// should also respect the `style` tag in the future.
fn allows_pretty_inside(tag: HtmlTag) -> bool {
    if tag::mathml::is_mathml(tag) && !tag::mathml::is_token(tag) {
        return true;
    }
    let Some(display) = property::Display::default_for(tag) else { return false };
    (display == property::Display::Block && tag != tag::pre)
        || display.is_tabular()
        || display == property::Display::ListItem
        || tag == tag::head
}

/// Whether newlines should be added before and after the element if the parent
/// allows it.
///
/// In contrast to `allows_pretty_inside`, which is purely spec-driven, this is
/// more subjective and depends on preference.
fn wants_pretty_around(element: &HtmlElement) -> bool {
    match element.tag {
        tag::mathml::math => {
            element.attrs.get(attr::mathml::display).is_some_and(|v| v == "block")
        }
        t if tag::mathml::is_mathml(t) => true,
        tag::pre => true,
        t if tag::is_metadata_content(t) => true,
        t => allows_pretty_inside(t),
    }
}

/// Escape a character.
fn write_escape(w: &mut Writer, c: char) -> StrResult<()> {
    // See <https://html.spec.whatwg.org/multipage/syntax.html#syntax-charref>
    match c {
        '&' => w.buf.push_str("&amp;"),
        '<' => w.buf.push_str("&lt;"),
        '>' => w.buf.push_str("&gt;"),
        '"' => w.buf.push_str("&quot;"),
        '\'' => w.buf.push_str("&apos;"),
        c if charsets::is_w3c_text_char(c) && c != '\r' => {
            write!(w.buf, "&#x{:x};", c as u32).unwrap()
        }
        _ => return Err(unencodable(c)),
    }
    Ok(())
}

/// The error message for a character that cannot be encoded.
#[cold]
fn unencodable(c: char) -> EcoString {
    eco_format!("the character `{}` cannot be encoded in HTML", c.repr())
}

/// Encode a laid out frame into the writer.
fn write_frame(w: &mut Writer, frame: &HtmlFrame) {
    let svg = typst_svg::svg_in_html(
        &frame.inner,
        frame.text_size,
        w.pretty,
        frame.id.as_deref(),
        &eco_format!("{}", frame.css.to_inline()),
        &frame.anchors,
        w.link_resolver,
    );

    if w.pretty {
        // Indent the SVG after generation. This ensures the frame is cached no
        // matter the current indentation of the outer HTML.
        for (i, line) in svg.lines().enumerate() {
            if i != 0 {
                write_indent(w);
            }
            w.buf.push_str(line);
        }
    } else {
        w.buf.push_str(&svg);
    }
}